How Can We Help?
< All Topics

Make calls to the Salesforce REST API

After successfully getting an access token, one can make calls the Salesforce REST API to extract data (leads, opportunities, etc.) or to modify and create new records.

import requests

def sf_api_call(action, parameters = {}, method = 'get', data = {}):
Helper function to make calls to Salesforce REST API.
Parameters: action (the URL), URL params, method (get, post or patch), data for POST/PATCH.
headers = {
'Content-type': 'application/json',
'Accept-Encoding': 'gzip',
'Authorization': 'Bearer %s' % access_token
if method == 'get':
r = requests.request(method, instance_url+action, headers=headers, params=parameters, timeout=30)
elif method in ['post', 'patch']:
r = requests.request(method, instance_url+action, headers=headers, json=data, params=parameters, timeout=10)
# other methods not implemented in this example
raise ValueError('Method should be get or post or patch.')
print('Debug: API %s call: %s' % (method, r.url) )
if r.status_code < 300:
if method=='patch':
return None
return r.json()
raise Exception('API error when calling %s : %s' % (r.url, r.content))

Please suggest edits or add your comments.

Your email address will not be published. Required fields are marked *

Scroll to Top