In this Simple-Salesforce in Python tutorial, we will be covering how to download files from a record.

Subscribe: https://www.youtube.com/channel/UCvVZ19DRSLIC2-RUOeWx8ug

Source Code:


from pprint import pprint
import json
import os
import requests
import pandas as pd
from simple_salesforce import Salesforce, SalesforceLogin, SFType

username = '<username>'
password = '<password>'
security_token = '<security_token>'
domain = 'login' # or test

session_id, instance = SalesforceLogin(username=username, password=password, security_token=security_token, domain=domain)
sf = Salesforce(instance=instance, session_id=session_id)

# querySOQL = """
#           SELECT Id, Name, ParentId, Body 
#           From Attachment 
#           WHERE ParentId IN (SELECT Id FROM Project__c)
#           """


# query records method
response = sf.query(querySOQL)
lstRecords = response.get('records')
nextRecordsUrl = response.get('nextRecordsUrl')

while not response.get('done'):
    response = sf.query_more(nextRecordsUrl, identifier_is_url=True)
    lstRecords.extend(response.get('records'))
    nextRecordsUrl = response.get('nextRecordsUrl')

df_records = pd.DataFrame(lstRecords)


"""
Download files
"""

instance_name = sf.sf_instance
folder_path = '.\Attachments Download'

for row in df_records.iterrows():
    record_id = row[1]['ParentId']
    file_name = row[1]['Name']
    attachment_url = row[1]['Body']


    if not os.path.exists(os.path.join(folder_path, record_id)):
        os.mkdir(os.path.join(folder_path, record_id))       
        
    request = sf.session.get('https://{0}{1}'.format(instance_name, attachment_url), headers=sf.headers)
    with open(os.path.join(folder_path, record_id, file_name), 'wb') as f:
        f.write(request.content)
        f.close()


#python

Salesforce API in Python | Download Attachments (record files & attachments)
4.75 GEEK