Many times we encounter the use cases when it becomes necessary or task can be done in a much effective way if we can connect directly with Salesforce using python or any other programming language. Here salesforce Rest APIs will play a major role. First, we have to do the authentication before calling the REST APIs and we will get access token and this access token will be used when we will call the REST APIs. In this example, we are going to use username password OAuth.

Step 1: First create a connected App into Salesforce Org. Follow the below steps for the same.

  • Go to setup, type App Manager in the quick find search box.
  • On the App Manager page click on the “New Connected App”.
  • Enter the name of the application.
  • Select the checkbox with label “Enable OAuth settings”.
  • In “Selected OAuth Scopes”, allow all the scopes available.
  • In the callback URL, type “http://localhost/”  and save.
  • After this, you will get “Consumer Key” and the “Consumer Secret”, jot it down at a safe place. We will use it in later steps.

Step 2: Salesforce Authenitication using Python, we will use username-password OAuth. With the help of the user’s credential and security token, we will authenticate and get the access token. This access token will be used when we will call REST APIs.

Use the below code to authenticate and get access token.

import requests
import json

params = {
    "grant_type": "password",
    "client_id": "######", # Consumer Key
    "client_secret": "#####", # Consumer Secret
    "username": "######", # The email you use to login
    "password": "######" # Concat your password and your security token
}
r = requests.post("https://login.salesforce.com/services/oauth2/token", params=params)
print(r.content)
access_token = r.json().get("access_token")
instance_url = r.json().get("instance_url")
print("Access Token:", access_token)

Step 3: Call the Salesforce REST API. Now we have access token that we got in the previous step, so we can make a call to the Salesforce REST API to extract data or to create new records.

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)
    else:
        # 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
        else:
            return r.json()
    els
        raise Exception('API error when calling %s : %s' % (r.url, r.content))

Example: let’s try to extract the next closing opportunities with the help of SOQL request.

print(json.dumps(sf_api_call('/services/data/v39.0/query/', {
    'q': 'SELECT Account.Name, Name, CloseDate from Opportunity where IsClosed = False order by CloseDate ASC LIMIT 10'
}), indent=2))

You will your output result in the JSON format. Complete code is available below GitHub URL.

https://github.com/piyush-singhal/salesforce_python

Happy Coding!!