Force REST APIs using Python 3.x

This tutorial provides samples on how to use Python 3 to work with force.com REST APIs

Reference Source Code : force-rest-python

Setup

Create a util/config.yml file from util/config_sample.yml file and fill in the values appropriately from salesforce.com developer account.

$ cp util
$ cp config_sample.yml config.yml
$ cat config_sample.yml

Update the TODO with appropriate values for client_id, client_secret, username and password.

credentials:
    client_id: TODO
    client_secret: TODO
    username: TODO
    password: TODO

Common Methods

File util.py provides common methods for getting access token. Getting access token consists of following steps. We define a class Util in this file and add common methods as static in this file

Get Access Token

  • Load Credentials from config.yml into appropriate variables

  • Connect to the OAuth2 token url /services/oauth2/token

  • Create a new HTTP Connection Object

  • Do a secure HTTP Post to the url with the credentials

  • Get the result body and Parse the json

  • Extract the access_token and return it

Full code Listing shown below

def get_access_token():
    conn = get_login_connection()
    conn.request("POST", "/services/oauth2/token", params, headers)
    response = conn.getresponse()
    print(response.status, response.reason)
    data = response.read().decode('ascii')
    data_json = json.loads(data)
    print('access_token: ' + data_json['access_token'])
    return data_json

Get List of SObjects

Url used to make request depends on the instance where your account was created ( na1, na2, ap1, ap2 etc) as well the version of the API being used. We are using the base url https://ap2.salesforce.com/services/data/v35.0/sobjects/.

The function get_sobject_list(object_name) takes the object name for which list has to be created (Account, Contact etc). A HTTPs Get request is made to the URL listed above appended by the object_name. Header of the HTTP request has Access token set

def get_sobject_list(object_name):
  access_token = get_access_token()['access_token']
  access_token_header = {'Authorization': 'Bearer ' + access_token,
                         'Content-type': 'application/json'}
  url = base_url + object_name
  conn = get_connection()
  conn.request("GET", url, '', access_token_header)
  res = conn.getresponse()
  data = res.read().decode("utf-8")
  return data

This function is called from Account objects get_list function to get list of Accounts.

Get Account List

Returns the list of Accounts by accounts util.get_sobject_list() from function get_list(self) in Account class.

class Account:
 ...
 def get_list(self):
   util.get_sobject_list('Account')

This function is called from Python script get_account_list.py

from account import Account
import pprint
import json
if __name__ == "__main__":
    account = Account()
    data = account.get_list()
    pp = pprint.PrettyPrinter(indent=4)
    pp.pprint(json.loads(data))
    print(data)

Execute the program, It will return the list of Accounts created in the salesforce.com instance.

$ python get_account_list.py

Create Account

We added a new function in util.py, create_sobject(object_name, data). This function takes two parameters. object_name which is the sobject name we want to create, and data which is data object to be sent in json format.

Detailed steps

1.Get access token

access_token = get_access_token()
  1. Create a URL object ur; based on the object_name
  2. Convert data into a JSON Object
json_data = json.dumps(data)
  1. Create a POST request object
  2. Make sure the http object is set to user ssl
  3. Set up the request’s header to include access_token as shown below
request.initialize_http_header({"Authorization" => "Bearer " + access_token})
  1. Check for Object_Name to be of type Account

  2. Get connection object by calling get_connection() in util and make a POST request with json_data and access_token_header. These headers are container the access_token.

    conn = get_connection()
    conn.request("POST", url, json_data, access_token_header)
    res = conn.getresponse()
    

Full code Listing of the method

def create_sobject(object_name, data):
   access_token = get_access_token()['access_token']
   access_token_header = {'Authorization': 'Bearer ' + access_token,
                          'Content-type': 'application/json'}

   url = base_url + object_name
   json_data = json.dumps(data)

   conn = get_connection()
   conn.request("POST", url, json_data, access_token_header)
   res = conn.getresponse()
   data = res.read().decode("utf-8")
   return data

The method listed above is called from class Account’s create(..) function which in turn is called from create_account.py script

class Account
  ...

  def create(self, new_account_p):
      self.new_account = new_account_p
      access_token = util.get_access_token()['access_token']
      data = util.create_sobject('Account', self.new_account)
      pp = pprint.PrettyPrinter(indent=4)
      pp.pprint(json.loads(data))
      print(data)
from account import Account

if __name__ == "__main__":
    account = Account()
    new_account = {"Name": "BlueDart__2"}
    account.create(new_account)
$ python create_account.py

Delete Account

Function delete_sobject is the utility function in util.py which will be used to delete any SObject. It takes two parameters object_name and object_id.

Steps followed to delete an sobject

  1. Create a url from object_name and object_id
  2. Get connection object from get_connection() function
  3. Call DELETE HTTP method with the headers and url
  4. Get the response object res and print
def delete_sobject(object_name, object_id):
  .url = base_url + object_name + '/' + object_id
  conn = get_connection()
  conn.request("DELETE", url, '', headers)
  res = conn.getresponse()
  data = res.read().decode("utf-8")
  print(data)

The function delete_account() in Account class calls the function delete_object listed obove

def delete_sobject(object_name, object_id):
  access_token = get_access_token()['access_token']
  access_token_header = {'Authorization': 'Bearer ' + access_token,
                         'Content-type': 'application/json'}
  url = base_url + object_name + '/' + object_id
  conn = get_connection()
  conn.request("DELETE", url, '', access_token_header)
  res = conn.getresponse()
  data = res.read().decode("utf-8")
  print(data)

Script delete_account.py is executed which calls delete_account() function in Account class.

from account import Account

if __name__ == "__main__":
  account = Account()
  account_id = '0012800000AdAS2'
  account.delete(account_id)

Execute the code

$ python delete_account.py