Many, many, many moons ago I posted about writing an Insanely Simple Python Script that used the Salesforce REST API’s.  It was a great little example, updated later by Mr. Pat Patterson and eventually evolved into a longer script that I used for demonstrations.  Due to bad source control and a new laptop build, I recently lost the code to said longer script – but I still wanted a similar demo.  While losing code is a bummer, I always say that when life throws you lost code you hand life back new refactored code.

And so I recently discovered simple-salesforce, a Python REST API client for Salesforce which uses more moderns libs like requests to get a similar job done.  Out of the box, simple-salesforce is setup well for headless access to the REST API via a username and password pair:

from simple_salesforce import Salesforce
sf = Salesforce(username='[email protected]', password='password', security_token='token')

Which is going to cover a lot of different use cases one might need. Once you are logged in, you can then access the REST API in a very object friendly manner. For instance, if I wanted to change the name of a custom object – I could:

sf.Merchandise__c.update('a03i0000006Mbe0',{'Name': 'Python Example'})

There are convenience methods for all of the standard REST functions. The only problem with this demo is that I often show code to large groups of people at one time and really don’t want to be typing my super-secret passwords onto a big screen. My previous script used an OAuth work around that launched a browser and waited for user input – but for this iteration I wanted to show a proper OAuth flow. Since simple-salesforce will also accept an instance url and session ID, this wasn’t too hard:

 

#!/usr/bin/python

import cgi
import requests
import json
from simple_salesforce import Salesforce

#login here:
#https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=3MVG9A2kN3Bn17hsWsLDatw._IVMEUBoPKv.7ksp0tz7xLX4tWDVgyzwTCA7i_yTfP.qYuNOsSoPNcdVH6DuE&redirect_uri=http://localhost/cgi-bin/python/oauth.py

consumer_key = '3MVG9A2kN3Bn17hsWsLDatw._IVMEUBoPKv.7ksp0tz7xLX4tWDVgyzwTCA7i_yTfP.qYuNOsSoPNcdVH6DuE'
consumer_secret = '8779811613588378217'
request_token_url = 'https://login.salesforce.com/services/oauth2/token'
access_token_url = 'https://login.salesforce.com/services/oauth2/token'
redirect_uri = 'http://localhost/cgi-bin/python/oauth.py'
authorize_url = 'https://login.salesforce.com/services/oauth2/authorize' #?response_type=token&client_id='+consumer_key+'&redirect_uri='+redirect_uri

query = cgi.FieldStorage()
req = None


if 'login' in query:
	print "Location: https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id="+consumer_key+"&redirect_uri="+redirect_uri
	print

if 'code' in query:
	code = query.getvalue('code')
	
	data = {
	            'grant_type': 'authorization_code',
	            'redirect_uri': redirect_uri,
	            'code': code,
	            'client_id' : consumer_key,
	            'client_secret' : consumer_secret
	        }
	headers = {
	            'content-type': 'application/x-www-form-urlencoded'
	        }
	req = requests.post(access_token_url,data=data,headers=headers)
	response = req.json()
	sf = Salesforce(instance_url=response['instance_url'], session_id=response['access_token'])
	records = sf.query("SELECT Id, Name, Email FROM Contact")
	records = records['records']

#print web page
print "Content-type: text/html"
print

print "<html><body>"
print "<h1>SELECT Id, Name, Email FROM Contact</h1>"

print "<table>"
print "<tr><td><b>Name</b></td><td><b>Email</b></td></tr>"
for record in records:
		print "<tr><td>"+record['Name']+"</td><td>"+record['Email']+"</td></tr>"

print "</table>"

print "</body></html>"

Which is also available as a gist.  You can save this script as “force-oauth.py”, serve it up on a webserver  and go to “/force-oauth.py?login=true” to kick things off.  The Python script will consume the request token and get a proper access token in return.  From there I can use simple-salesforce to access the REST API.  If you wanted to try something like this out on OSX, it turns out that it is very easy to add Python scripts to Apache once you know where to look.

There you go, a quick and easy way to the use the REST API via Python.  If you’re using Python with Salesforce currently, or might in the future, let me know via twitter or in the comment boxes below.

If you like simple-salesforce, give Nick Catalano a shoutout on twitter.  You can also check out his OAuth2 implementation for Salesforce and Python.

 

tagged , , , , Bookmark the permalink. Trackbacks are closed, but you can post a comment.
  • Hans Villamil

    Hi Josh Im having trouble getting simple_salesforce to work after I compiled it with pyinstaller. I get the error:

    ssl.SSLError: [Errno 185090050] _ssl.c:340: error:0B084002:x509 certificate
    routines:X509_load_cert_crl_file:system lib

    I tried setting all the get and put requests in simple_salesforce with verify=False but still doesn’t work. Any help is much appreciated!