Simple-Salesforce Python
Simple-Salesforce Python
Release 0.72.1
1 Examples 3
2 Record Management 5
3 Queries 7
4 Other Options 9
5 Using Apex 11
6 Additional Features 13
7 API documentation 15
7.1 simple_salesforce package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
8 Release history 27
8.1 v0.72 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
8.2 v0.71 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
8.3 v0.70 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
8.4 v0.69 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
8.5 v0.68.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
i
ii
simple-salesforce Documentation, Release 0.72.1
Simple Salesforce is a basic Salesforce.com REST API client built for Python 2.6, 2.7, 3.3, 3.4, 3.5 and 3.6. The goal
is to provide a very low-level interface to the REST Resource and APEX API, returning a dictionary of the API JSON
response.
You can find out more regarding the format of the results in the Official Salesforce.com REST API Documentation
Contents:
Contents 1
simple-salesforce Documentation, Release 0.72.1
2 Contents
CHAPTER 1
Examples
If you have the full URL of your instance (perhaps including the schema, as is included in the OAuth2 request process),
you can pass that in instead using instance_url:
There are also two means of authentication, one that uses username, password and security token and the other that
uses IP filtering, username, password and organizationId
To login using the security token method, simply include the Salesforce method and pass in your Salesforce username,
password and token (this is usually provided when you change your password):
To login using IP-whitelist Organization ID method, simply use your Salesforce username, password and organiza-
tionId:
If you’d like to enter a sandbox, simply add domain='test' to your Salesforce() call.
For example:
3
simple-salesforce Documentation, Release 0.72.1
Note that specifying if you want to use a domain is only necessary if you are using the built-in user-
name/password/security token authentication and is used exclusively during the authentication step.
If you’d like to keep track where your API calls are coming from, simply add client_id='My App' to your
Salesforce() call.
If you view the API calls in your Salesforce instance by Client Id it will be prefixed with RestForce/, for example
RestForce/My App.
When instantiating a Salesforce object, it’s also possible to include an instance of requests.Session. This is to allow
for specialized session handling not otherwise exposed by simple_salesforce.
For example:
session = requests.Session()
# manipulate the session instance (optional)
sf = Salesforce(
username='[email protected]', password='password', organizationId='OrgId',
session=session)
4 Chapter 1. Examples
CHAPTER 2
Record Management
sf.Contact.create({'LastName':'Smith','Email':'[email protected]'})
contact = sf.Contact.get('003e0000003GuNXAA0')
To get a dictionary with all the information regarding that record, using a custom field that was defined as External
ID:
To change that contact’s last name from ‘Smith’ to ‘Jones’ and add a first name of ‘John’ use:
sf.Contact.delete('003e0000003GuNXAA0')
To retrieve a list of deleted records between 2013-10-20 to 2013-10-29 (datetimes are required to be in UTC):
import pytz
import datetime
end = datetime.datetime.now(pytz.UTC) # we need to use UTC as salesforce API
˓→requires this!
To retrieve a list of updated records between 2014-03-20 to 2014-03-22 (datetimes are required to be in UTC):
5
simple-salesforce Documentation, Release 0.72.1
import pytz
import datetime
end = datetime.datetime.now(pytz.UTC) # we need to use UTC as salesforce API requires
˓→this
Note that Update, Delete and Upsert actions return the associated Salesforce HTTP Status Code
Use the same format to create any record, including ‘Account’, ‘Opportunity’, and ‘Lead’. Make sure to have all the
required fields for any entry. The Salesforce API has all objects found under ‘Reference -> Standard Objects’ and the
required fields can be found there.
Queries
It’s also possible to write select queries in Salesforce Object Query Language (SOQL) and search queries in Salesforce
Object Search Language (SOSL).
SOQL queries are done via:
If, due to an especially large result, Salesforce adds a nextRecordsUrl to your query result, such as
"nextRecordsUrl" : "/services/data/v26.0/query/01gD0000002HU6KIAW-2000", you can
pull the additional results with either the ID or the full URL (if using the full URL, you must pass ‘True’ as your
second argument)
sf.query_more("01gD0000002HU6KIAW-2000")
sf.query_more("/services/data/v26.0/query/01gD0000002HU6KIAW-2000", True)
As a convenience, to retrieve all of the results in a single local method call use
sf.search("FIND {Jones}")
There is also ‘Quick Search’, which inserts your query inside the {} in the SOSL syntax. Be careful, there is no
escaping!
sf.quick_search("Jones")
Search and Quick Search return None if there are no records, otherwise they return a dictionary of search results.
More details about syntax is available on the Salesforce Query Language Documentation Developer Website
7
simple-salesforce Documentation, Release 0.72.1
8 Chapter 3. Queries
CHAPTER 4
Other Options
sf.Contact.upsert('customExtIdField__c/11999',{'LastName': 'Smith','Email':
˓→'[email protected]'})
sf.Contact.metadata()
sf.Contact.describe()
To retrieve a description of the record layout of an object by its record layout unique id, use:
sf.Contact.describe_layout('39wmxcw9r23r492')
sf.describe()
for x in sf.describe()["sobjects"]:
print x["label"]
9
simple-salesforce Documentation, Release 0.72.1
Using Apex
You can also use this library to call custom Apex methods:
payload = {
"activity": [
{"user": "12345", "action": "update page", "time": "2014-04-21T13:00:15Z"}
]
}
result = sf.apexecute('User/Activity', method='POST', data=payload)
11
simple-salesforce Documentation, Release 0.72.1
Additional Features
There are a few helper classes that are used internally and available to you.
Included in them are SalesforceLogin, which takes in a username, password, security token, optional version
and optional domain and returns a tuple of (session_id, sf_instance) where session_id is the session ID
to use for authentication to Salesforce and sf_instance is the domain of the instance of Salesforce to use for the
session.
For example, to use SalesforceLogin for a sandbox account you’d use:
from simple_salesforce import SalesforceLogin
session_id, instance = SalesforceLogin(
username='[email protected]',
password='password',
security_token='token',
domain='test')
Simply leave off the final domain if you do not wish to use a sandbox.
Also exposed is the SFType class, which is used internally by the __getattr__() method in the Salesforce()
class and represents a specific SObject type. SFType requires object_name (i.e. Contact), session_id (an
authentication ID), sf_instance (hostname of your Salesforce instance), and an optional sf_version
To add a Contact using the default version of the API you’d use:
from simple_salesforce import SFType
contact = SFType('Contact','sessionid','na1.salesforce.com')
contact.create({'LastName':'Smith','Email':'[email protected]'})
To use a proxy server between your client and the SalesForce endpoint, use the proxies argument when creating
SalesForce object. The proxy argument is the same as what requests uses, a map of scheme to proxy URL:
proxies = {
"http": "http://10.10.1.10:3128",
"https": "http://10.10.1.10:1080",
}
SalesForce(instance='na1.salesforce.com', session_id='', proxies=proxies)
13
simple-salesforce Documentation, Release 0.72.1
All results are returned as JSON converted OrderedDict to preserve order of keys from REST responses.
API documentation
7.1.1 Subpackages
simple_salesforce.tests package
Submodules
simple_salesforce.tests.test_api module
simple_salesforce.tests.test_login module
simple_salesforce.tests.test_util module
15
simple-salesforce Documentation, Release 0.72.1
test_multiple_records_returned()
Test multiple records returned (a 300 code)
test_request_refused()
Test a refused request (403 code)
test_resource_not_found()
Test resource not found (404 code)
class simple_salesforce.tests.test_util.TestXMLParser(methodName=’runTest’)
Bases: unittest.case.TestCase
Test the XML parser utility function
test_date_to_iso8601()
Test date conversion
test_returns_valid_value()
Test that when given the correct XML a valid response is returned
Module contents
Simple-Salesforce Tests
7.1.2 Submodules
simple_salesforce.api module
• session – Custom requests session, created in calling code. This enables the use of requests Ses-
sion features not otherwise exposed by simple_salesforce.
create(data, headers=None)
Creates a new SObject using a POST to . . . /{object_name}/.
Returns a dict decoded from the JSON payload returned by Salesforce.
Arguments:
• data – a dict of the data to create the SObject from. It will be JSON-encoded before being trans-
mitted.
• headers – a dict with additional request headers.
delete(record_id, raw_response=False, headers=None)
Deletes an SObject using a DELETE to . . . /{object_name}/{record_id}.
If raw_response is false (the default), returns the status code returned by Salesforce. Otherwise, return the
requests.Response object.
Arguments:
• record_id – the Id of the SObject to delete
• raw_response – a boolean indicating whether to return the response directly, instead of the sta-
tus code.
• headers – a dict with additional request headers.
deleted(start, end, headers=None)
Gets a list of deleted records
Use the SObject Get Deleted resource to get a list of deleted records for the specified object.
. . . /deleted/?start=2013-05-05T00:00:00+00:00&end=2013-05-10T00:00:00+00:00
• start – start datetime object
• end – end datetime object
• headers – a dict with additional request headers.
describe(headers=None)
Returns the result of a GET to . . . /{object_name}/describe as a dict decoded from the JSON payload
returned by Salesforce.
Arguments:
• headers – a dict with additional request headers.
describe_layout(record_id, headers=None)
Returns the layout of the object
Returns the result of a GET to . . . /{object_name}/describe/layouts/<recordid> as a dict decoded from the
JSON payload returned by Salesforce.
Arguments:
• record_id – the Id of the SObject to get
• headers – a dict with additional request headers.
get(record_id, headers=None)
Returns the result of a GET to . . . /{object_name}/{record_id} as a dict decoded from the JSON payload
returned by Salesforce.
Arguments:
Arguments:
• record_id – an identifier for the SObject as described in the Salesforce documentation
• data – a dict of the data to create or update the SObject from. It will be JSON-encoded before
being transmitted.
• raw_response – a boolean indicating whether to return the response directly, instead of the sta-
tus code.
• headers – a dict with additional request headers.
class simple_salesforce.api.Salesforce(username=None, password=None, secu-
rity_token=None, session_id=None, instance=None,
instance_url=None, organizationId=None, sand-
box=None, version=’38.0’, proxies=None, ses-
sion=None, client_id=None, domain=None)
Bases: object
Salesforce Instance
An instance of Salesforce is a handy way to wrap a Salesforce session for easy use of the Salesforce REST API.
simple_salesforce.bulk module
simple_salesforce.exceptions module
Error Code: 401 The session ID or OAuth token used has expired or is invalid. The response body contains the
message and errorCode.
message = u'Expired session for {url}. Response content: {content}'
exception simple_salesforce.exceptions.SalesforceGeneralError(url, status, re-
source_name,
content)
Bases: simple_salesforce.exceptions.SalesforceError
A non-specific Salesforce error.
message = u'Error Code {status}. Response content: {content}'
exception simple_salesforce.exceptions.SalesforceMalformedRequest(url, sta-
tus, re-
source_name,
content)
Bases: simple_salesforce.exceptions.SalesforceError
Error Code: 400 The request couldn’t be understood, usually because the JSON or XML body contains an error.
simple_salesforce.login module
simple_salesforce.util module
Simple-Salesforce Package
Release history
8.1 v0.72
8.1.1 Bugs
• [134] query_all changed to be non-recursive due to recursion limit being hit for large result sets.
8.2 v0.71
8.2.1 Features
8.3 v0.70
8.3.1 Features
• [98] Requests session objects are now shared between SFType instances and the parent Salesforce object
8.4 v0.69
8.4.1 Features
• [103] Require requests[secure] to allow for system openssl, which will allow for TLSv1.2 in Python < 2.7.9
assuming system openssl is newer than Python’s.
27
simple-salesforce Documentation, Release 0.72.1
8.4.2 Other
• Replaced httpretty with responses for unit tests due to SSL-related errors in httpretty.
8.5 v0.68.2
8.5.1 Other
This package is released under an open source Apache 2.0 license. Simple-Salesforce was originally written by Nick
Catalano but most newer features and bugfixes come from community contributors. Pull requests submitted to the
GitHub Repo are highly encouraged!
Authentication mechanisms were adapted from Dave Wingate’s RestForce and licensed under a MIT license
The latest build status can be found at Travis CI
29
simple-salesforce Documentation, Release 0.72.1
• genindex
• modindex
• search
31
simple-salesforce Documentation, Release 0.72.1
s
simple_salesforce, 25
simple_salesforce.api, 16
simple_salesforce.bulk, 22
simple_salesforce.exceptions, 23
simple_salesforce.login, 24
simple_salesforce.tests, 16
simple_salesforce.tests.test_util, 15
simple_salesforce.util, 25
33
simple-salesforce Documentation, Release 0.72.1
35
simple-salesforce Documentation, Release 0.72.1
Q test_generic_error_code() (sim-
query() (simple_salesforce.api.Salesforce method), 20 ple_salesforce.tests.test_util.TestExceptionHandler
query() (simple_salesforce.bulk.SFBulkType method), 23 method), 15
query_all() (simple_salesforce.api.Salesforce method), test_malformed_request() (sim-
20 ple_salesforce.tests.test_util.TestExceptionHandler
query_more() (simple_salesforce.api.Salesforce method), method), 15
20 test_multiple_records_returned() (sim-
quick_search() (simple_salesforce.api.Salesforce ple_salesforce.tests.test_util.TestExceptionHandler
method), 21 method), 15
test_request_refused() (sim-
R ple_salesforce.tests.test_util.TestExceptionHandler
request (simple_salesforce.api.Salesforce attribute), 21 method), 16
request (simple_salesforce.api.SFType attribute), 18 test_resource_not_found() (sim-
restful() (simple_salesforce.api.Salesforce method), 21 ple_salesforce.tests.test_util.TestExceptionHandler
method), 16
S test_returns_valid_value() (sim-
Salesforce (class in simple_salesforce.api), 19 ple_salesforce.tests.test_util.TestXMLParser
SalesforceAPI (class in simple_salesforce.api), 21 method), 16
SalesforceAuthenticationFailed, 23 TestExceptionHandler (class in sim-
SalesforceError, 23 ple_salesforce.tests.test_util), 15
SalesforceExpiredSession, 23 TestXMLParser (class in sim-
SalesforceGeneralError, 24 ple_salesforce.tests.test_util), 16
SalesforceLogin() (in module simple_salesforce.login), total (simple_salesforce.api.PerAppUsage attribute), 16
24 total (simple_salesforce.api.Usage attribute), 22
SalesforceMalformedRequest, 24
SalesforceMoreThanOneRecord, 24 U
SalesforceRefusedRequest, 24 update() (simple_salesforce.api.SFType method), 18
SalesforceResourceNotFound, 24 update() (simple_salesforce.bulk.SFBulkType method),
search() (simple_salesforce.api.Salesforce method), 21 23
set_password() (simple_salesforce.api.Salesforce updated() (simple_salesforce.api.SFType method), 18
method), 21 upsert() (simple_salesforce.api.SFType method), 18
setPassword() (simple_salesforce.api.Salesforce method), upsert() (simple_salesforce.bulk.SFBulkType method),
21 23
Usage (class in simple_salesforce.api), 22
setUp() (simple_salesforce.tests.test_util.TestExceptionHandler
method), 15 used (simple_salesforce.api.PerAppUsage attribute), 16
SFBulkHandler (class in simple_salesforce.bulk), 22 used (simple_salesforce.api.Usage attribute), 22
SFBulkType (class in simple_salesforce.bulk), 22
SFType (class in simple_salesforce.api), 16
simple_salesforce (module), 25
simple_salesforce.api (module), 16
simple_salesforce.bulk (module), 22
simple_salesforce.exceptions (module), 23
simple_salesforce.login (module), 24
simple_salesforce.tests (module), 16
simple_salesforce.tests.test_util (module), 15
simple_salesforce.util (module), 25
T
test_date_to_iso8601() (sim-
ple_salesforce.tests.test_util.TestXMLParser
method), 16
test_expired_session() (sim-
ple_salesforce.tests.test_util.TestExceptionHandler
method), 15
36 Index