Connecting To Salesforce Rest API in Python


Setup

To be able to begin to retrieve Metadata and other information from the Salesforce database, you will have to first establish a connection.

Note: If you are using a sandbox environment, the login url will be changed from login.salesforce.com to test.salesforce.com.

To establish the connection you will need to do the following things first.
1. Create a connected app in the Salesforce platform.
2. Get the consumerkey and consumersecret from the created app
3. Create a security token for your Salesforce account.

Establishing a connection

The python code below uses the SOAP API in Salesforce to grab data. It is kept as its own function, for simplicity, and to easily allow threading.

import requests  
import json  
# Pass the api endpoint that you want to retrieve data from
# Example: api = "/services/data/v37.0/sobjects/"
def connect(api):  
    sandbox=True
    payload = {
            'grant_type':       'password',
            'client_id':        consumer_key,
            'client_secret':    consumer_secret,
            'username':         username,
            'password':         password
        }

        #there are different login urls in sandbox and production
        if sandbox:
            loginUrl = "https://test.salesforce.com/services/oauth2/token"
        else:
            loginUrl  = "https://login.salesforce.com/services/oauth2/token"

        headerPayload = {"Content-Type":"application/x-www-form-urlencoded"}
        try:
            r = requests.post(loginUrl, headers=headerPayload,data=payload)
        except Exception as e:
            msg = "Error >> couldn't get login token  >>>>" + str(e)
            print msg
        try:
            body = json.loads(r.content)
        except Exception as e:
            print "couldn't get body"
            print str(e)
        try:
            token = body["access_token"]
        except Exception as e:
            print "ERROR couldn't get access token > " + str(e)
        try: #get the url to send
            url = body['instance_url'] + api
            logging.info( "url: " + url)
        except Exception as e:
            print "ERROR Couldnt get url > " + str(e)
        try: #get request
            r = requests.get(url, headers = {"Authorization":"Bearer " + token})
            #this will print out the output in an easy to read format
            parsedJson = json.loads(r.content)
            return parsedJson
        except Exception as e:
            print "ERROR couldn't get r.content > " + str(e)

Other Notes

  • There are a limited amount of rest calls allowed daily so it would be a good idea to check how many rest calls you have remaining and store them somewhere.
  • The rest calls get returned and processed by Salesforce extremely slowly. It is highly encouraged to use threads to send Rest calls much faster and Queue up as many as you need.
Press ` to check out my sick terminal!