How to get files from Salesforce using Python

5.8k views Asked by At

I am using Python/Beatbox to access Salesforce cases.

service = beatbox.PythonClient()  # instantiate the object
service.login(...)  # login using your sf credentials

query_result = service.query("SELECT Id, AccountId, CaseNumber FROM Case WHERE Id='xyz'  ")

I'm interested in a specific case:

print query_result[0].Id

Get attachments...

att_result = service.query("SELECT Id, ContentType, Name FROM Attachment WHERE ParentId= '" + str(query_result[0].Id) + "'")

So far the results are good. Now I want to download the files uploaded to the case. What should be my query? I tried following and its always empty..But Im sure the case has files as well as attachments..

doc_result = service.query("SELECT Id, ContentDocumentId, Title FROM AttachedContentDocument  WHERE Id= '" + str(query_result[0].Id) + "'")

I also tried the document object and still no success. I appreciate your help.

2

There are 2 answers

0
Dhaval Metrani On
att_body = att_result["records"][0]["Body"]
att_url = base_url + attachment_body
att_text_result = requests.get(url, headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % session_id })

Refer this for session_id: https://github.com/simple-salesforce/simple-salesforce

0
hynekcer On

You can get not more than one Attachment by one request in any Salesforce API. To be sure that you don't an attachment, get the Attachment.Id first, then get the body by a loop

SELECT Id FROM Attachment WHERE ParentId = '...'
for ...
    SELECT Body FROM Attachment WHERE Id = '...'"

A) SOAP API (Beatbox): Get the Attachment as a normal long base64encoded field.

import base64
ret = service.query("SELECT Id, Body FROM Attachment WHERE Id = '...'")
blob = base64.b64decode(ret)[0]['Body'])

The query should expect one row because the output is restricted to one row if the "Body" field is present.

B) If REST API is used (simple-salesforce package) with the same queries, the value of Body or VersionData fields is a URL of the form '/services/data/v40.0/sobjects/Attachment/<object_id>/Body' which can be downloaded by GET request.

C) Fetch Salesforce Attachment content with django-salesforce


Objects useful for Binary Large OBjects are Attachment, Document and ContentVersion. These useful queries allow to get a binary large object (Attachment or Document) as a normal long field by SOAP API (Beatbox). The ContentVersion object allows to store more versions of the same data. Attachment has a parent object. Document is without any parent object. Useful queries: (read restrictions by API above)

SELECT Id, Body FROM Attachment WHERE ParentId = '...'
SELECT Id, Body FROM Document WHERE ParentId = '...'
SELECT Id, VersionData FROM ContentVersion WHERE ...