Skip to content

Instantly share code, notes, and snippets.

@wadewegner
Last active October 20, 2022 05:59
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save wadewegner/df609a495df2e4bd7a07 to your computer and use it in GitHub Desktop.
Save wadewegner/df609a495df2e4bd7a07 to your computer and use it in GitHub Desktop.
Upload attachment to Salesforce using Python
import requests
import base64
import json
from simple_salesforce import Salesforce
userName = ''
password = ''
securityToken = ''
instance = ''
sf = Salesforce(username=userName, password=password, security_token=securityToken)
sessionId = sf.session_id
account = sf.query("SELECT Id, Name FROM Account LIMIT 1")
accountId = account["records"][0]["Id"]
body = ""
with open("text.txt", "r") as f:
body = base64.b64encode(f.read())
response = requests.post('https://%s.salesforce.com/services/data/v29.0/sobjects/Attachment/' % instance,
headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % sessionId },
data = json.dumps({
'ParentId': accountId,
'Name': 'rest_test.txt',
'body': body
})
)
print response.text
import beatbox
import base64
userName = ''
securityToken = ''
password = '' + securityToken
svc = beatbox.PythonClient()
svc.login(userName, password)
body = ""
with open("text.txt", "rb") as f:
body = base64.b64encode(f.read())
res = svc.query("SELECT Id, Name FROM Account LIMIT 1")
accountId = res[0].Id
print res[0].Name
update_dict = {
'type' : 'Attachment',
'ParentId' : accountId,
'Name' : 'text.txt',
'Body' : body
}
results = svc.create(update_dict)
print results
@wadewegner
Copy link
Author

upload_soap.py

Note that I've used beatbox, a Python library, for querying/updating Salesforce data via the SOAP API.

A few important things to remember about attachments:

  • You have to base64 encode the file.
  • Other than encoding the file it works the same way as creating any object.
  • If you want to add the attachment to something else (i.e. a Contact) simply attach the Contact Id as the ParentId.

upload_rest.py

Note that I've used simple_salesforce, a Python library, for login and querying Salesforce data via the REST API.
Enjoy!

@joeyscully
Copy link

Hi Wade - thanks for this example - really useful. Wondered if you had ever tried to do the opposite operation, downloading an attachment from SF? I am also using simple-salesforce, but it doesn't seem to have much guidance on downloading attachments.

@Aleccc
Copy link

Aleccc commented May 29, 2019

######
## Query a file from Salesforce Attachment, then download file
######

import requests
from simple_salesforce import Salesforce

userName = ''
password = ''
securityToken = ''
instance = ''

sf = Salesforce(username=userName, password=password, security_token=securityToken)

# retrieve the Body of the attachment you want to download
soql= ("select Id, Name, Body from Attachment where Parent.Id = 'foobar' ")
all_attachments = sf.query(soql)

# since query can return multiple results, let's take the first one for this example
body = all_attachments['records'][0]['Body']

# use requests to get the content, then write
url = 'https://na15.salesforce.com'
url += body
response = requests.get(url, headers=sf.headers)
with open(filename, 'wb') as output:
    output.write(response.content)

@ajeeb-kp-keleno
Copy link

ajeeb-kp-keleno commented May 15, 2020

IMHO,

	body = base64.b64encode(f.read())

Should be

	body = base64.b64encode(f.read()).decode('utf-8')

for python3 (ie. b64encode method returns a byte in python3, so convert that into a string).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment