README.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. *****************
  2. Simple Salesforce
  3. *****************
  4. .. image:: https://api.travis-ci.org/simple-salesforce/simple-salesforce.svg?branch=master
  5. :target: https://travis-ci.org/simple-salesforce/simple-salesforce
  6. .. image:: https://readthedocs.org/projects/simple-salesforce/badge/?version=latest
  7. :target: http://simple-salesforce.readthedocs.io/en/latest/?badge=latest
  8. :alt: Documentation Status
  9. 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.
  10. You can find out more regarding the format of the results in the `Official Salesforce.com REST API Documentation`_
  11. .. _Official Salesforce.com REST API Documentation: http://www.salesforce.com/us/developer/docs/api_rest/index.htm
  12. Examples
  13. --------
  14. There are two ways to gain access to Salesforce
  15. The first is to simply pass the domain of your Salesforce instance and an access token straight to ``Salesforce()``
  16. For example:
  17. .. code-block:: python
  18. from simple_salesforce import Salesforce
  19. sf = Salesforce(instance='na1.salesforce.com', session_id='')
  20. 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``:
  21. .. code-block:: python
  22. from simple_salesforce import Salesforce
  23. sf = Salesforce(instance_url='https://na1.salesforce.com', session_id='')
  24. 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
  25. 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):
  26. .. code-block:: python
  27. from simple_salesforce import Salesforce
  28. sf = Salesforce(username='myemail@example.com', password='password', security_token='token')
  29. To login using IP-whitelist Organization ID method, simply use your Salesforce username, password and organizationId:
  30. .. code-block:: python
  31. from simple_salesforce import Salesforce
  32. sf = Salesforce(password='password', username='myemail@example.com', organizationId='OrgId')
  33. If you'd like to enter a sandbox, simply add ``domain='test'`` to your ``Salesforce()`` call.
  34. For example:
  35. .. code-block:: python
  36. from simple_salesforce import Salesforce
  37. sf = Salesforce(username='myemail@example.com.sandbox', password='password', security_token='token', domain='test')
  38. Note that specifying if you want to use a domain is only necessary if you are using the built-in username/password/security token authentication and is used exclusively during the authentication step.
  39. If you'd like to keep track where your API calls are coming from, simply add ``client_id='My App'`` to your ``Salesforce()`` call.
  40. .. code-block:: python
  41. from simple_salesforce import Salesforce
  42. sf = Salesforce(username='myemail@example.com.sandbox', password='password', security_token='token', client_id='My App', domain='test')
  43. If you view the API calls in your Salesforce instance by Client Id it will be prefixed with ``RestForce/``, for example ``RestForce/My App``.
  44. When instantiating a `Salesforce` object, it's also possible to include an
  45. instance of `requests.Session`. This is to allow for specialized
  46. session handling not otherwise exposed by simple_salesforce.
  47. For example:
  48. .. code-block:: python
  49. from simple_salesforce import Salesforce
  50. import requests
  51. session = requests.Session()
  52. # manipulate the session instance (optional)
  53. sf = Salesforce(
  54. username='user@example.com', password='password', organizationId='OrgId',
  55. session=session)
  56. Record Management
  57. -----------------
  58. To create a new 'Contact' in Salesforce:
  59. .. code-block:: python
  60. sf.Contact.create({'LastName':'Smith','Email':'example@example.com'})
  61. This will return a dictionary such as ``{u'errors': [], u'id': u'003e0000003GuNXAA0', u'success': True}``
  62. To get a dictionary with all the information regarding that record, use:
  63. .. code-block:: python
  64. contact = sf.Contact.get('003e0000003GuNXAA0')
  65. To get a dictionary with all the information regarding that record, using a **custom** field that was defined as External ID:
  66. .. code-block:: python
  67. contact = sf.Contact.get_by_custom_id('My_Custom_ID__c', '22')
  68. To change that contact's last name from 'Smith' to 'Jones' and add a first name of 'John' use:
  69. .. code-block:: python
  70. sf.Contact.update('003e0000003GuNXAA0',{'LastName': 'Jones', 'FirstName': 'John'})
  71. To delete the contact:
  72. .. code-block:: python
  73. sf.Contact.delete('003e0000003GuNXAA0')
  74. To retrieve a list of Contact records deleted over the past 10 days (datetimes are required to be in UTC):
  75. .. code-block:: python
  76. import pytz
  77. import datetime
  78. end = datetime.datetime.now(pytz.UTC) # we need to use UTC as salesforce API requires this!
  79. sf.Contact.deleted(end - datetime.timedelta(days=10), end)
  80. To retrieve a list of Contact records updated over the past 10 days (datetimes are required to be in UTC):
  81. .. code-block:: python
  82. import pytz
  83. import datetime
  84. end = datetime.datetime.now(pytz.UTC) # we need to use UTC as salesforce API requires this
  85. sf.Contact.updated(end - datetime.timedelta(days=10), end)
  86. Note that Update, Delete and Upsert actions return the associated `Salesforce HTTP Status Code`_
  87. Use the same format to create any record, including 'Account', 'Opportunity', and 'Lead'.
  88. 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.
  89. .. _Salesforce HTTP Status Code: http://www.salesforce.com/us/developer/docs/api_rest/Content/errorcodes.htm
  90. .. _Salesforce API: https://www.salesforce.com/developer/docs/api/
  91. Queries
  92. -------
  93. It's also possible to write select queries in Salesforce Object Query Language (SOQL) and search queries in Salesforce Object Search Language (SOSL).
  94. SOQL queries are done via:
  95. .. code-block:: python
  96. sf.query("SELECT Id, Email FROM Contact WHERE LastName = 'Jones'")
  97. 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)
  98. .. code-block:: python
  99. sf.query_more("01gD0000002HU6KIAW-2000")
  100. sf.query_more("/services/data/v26.0/query/01gD0000002HU6KIAW-2000", True)
  101. As a convenience, to retrieve all of the results in a single local method call use
  102. .. code-block:: python
  103. sf.query_all("SELECT Id, Email FROM Contact WHERE LastName = 'Jones'")
  104. SOSL queries are done via:
  105. .. code-block:: python
  106. sf.search("FIND {Jones}")
  107. There is also 'Quick Search', which inserts your query inside the {} in the SOSL syntax. Be careful, there is no escaping!
  108. .. code-block:: python
  109. sf.quick_search("Jones")
  110. Search and Quick Search return ``None`` if there are no records, otherwise they return a dictionary of search results.
  111. More details about syntax is available on the `Salesforce Query Language Documentation Developer Website`_
  112. .. _Salesforce Query Language Documentation Developer Website: http://www.salesforce.com/us/developer/docs/soql_sosl/index.htm
  113. Other Options
  114. -------------
  115. To insert or update (upsert) a record using an external ID, use:
  116. .. code-block:: python
  117. sf.Contact.upsert('customExtIdField__c/11999',{'LastName': 'Smith','Email': 'smith@example.com'})
  118. To retrieve basic metadata use:
  119. .. code-block:: python
  120. sf.Contact.metadata()
  121. To retrieve a description of the object, use:
  122. .. code-block:: python
  123. sf.Contact.describe()
  124. To retrieve a description of the record layout of an object by its record layout unique id, use:
  125. .. code-block:: python
  126. sf.Contact.describe_layout('39wmxcw9r23r492')
  127. To retrieve a list of top level description of instance metadata, user:
  128. .. code-block:: python
  129. sf.describe()
  130. for x in sf.describe()["sobjects"]:
  131. print x["label"]
  132. Using Bulk
  133. ----------
  134. You can use this library to access Bulk API functions.
  135. Create new records:
  136. .. code-block:: python
  137. data = [{'LastName':'Smith','Email':'example@example.com'}, {'LastName':'Jones','Email':'test@test.com'}]
  138. sf.bulk.Contact.insert(data)
  139. Update existing records:
  140. .. code-block:: python
  141. data = [{'Id': '0000000000AAAAA', 'Email': 'examplenew@example.com'}, {'Id': '0000000000BBBBB', 'Email': 'testnew@test.com'}]
  142. sf.bulk.Contact.update(data)
  143. Upsert records:
  144. .. code-block:: python
  145. data = [{'Id': '0000000000AAAAA', 'Email': 'examplenew2@example.com'}, {'Id': '', 'Email': 'foo@foo.com'}]
  146. sf.bulk.Contact.upsert(data, 'Id')
  147. Query records:
  148. .. code-block:: python
  149. query = 'SELECT Id, Name FROM Account LIMIT 10'
  150. sf.bulk.Account.query(query)
  151. Delete records (soft deletion):
  152. .. code-block:: python
  153. data = [{'Id': '0000000000AAAAA'}]
  154. sf.bulk.Contact.delete(data)
  155. Hard deletion:
  156. .. code-block:: python
  157. data = [{'Id': '0000000000BBBBB'}]
  158. sf.bulk.Contact.hard_delete(data)
  159. Using Apex
  160. ----------
  161. You can also use this library to call custom Apex methods:
  162. .. code-block:: python
  163. payload = {
  164. "activity": [
  165. {"user": "12345", "action": "update page", "time": "2014-04-21T13:00:15Z"}
  166. ]
  167. }
  168. result = sf.apexecute('User/Activity', method='POST', data=payload)
  169. This would call the endpoint ``https://<instance>.salesforce.com/services/apexrest/User/Activity`` with ``data=`` as
  170. the body content encoded with ``json.dumps``
  171. You can read more about Apex on the `Force.com Apex Code Developer's Guide`_
  172. .. _Force.com Apex Code Developer's Guide: http://www.salesforce.com/us/developer/docs/apexcode
  173. Additional Features
  174. -------------------
  175. There are a few helper classes that are used internally and available to you.
  176. 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.
  177. For example, to use SalesforceLogin for a sandbox account you'd use:
  178. .. code-block:: python
  179. from simple_salesforce import SalesforceLogin
  180. session_id, instance = SalesforceLogin(
  181. username='myemail@example.com.sandbox',
  182. password='password',
  183. security_token='token',
  184. domain='test')
  185. Simply leave off the final domain if you do not wish to use a sandbox.
  186. 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``
  187. To add a Contact using the default version of the API you'd use:
  188. .. code-block:: python
  189. from simple_salesforce import SFType
  190. contact = SFType('Contact','sesssionid','na1.salesforce.com')
  191. contact.create({'LastName':'Smith','Email':'example@example.com'})
  192. To use a proxy server between your client and the SalesForce endpoint, use the proxies argument when creating SalesForce object.
  193. The proxy argument is the same as what requests uses, a map of scheme to proxy URL:
  194. .. code-block:: python
  195. proxies = {
  196. "http": "http://10.10.1.10:3128",
  197. "https": "http://10.10.1.10:1080",
  198. }
  199. SalesForce(instance='na1.salesforce.com', session_id='', proxies=proxies)
  200. All results are returned as JSON converted OrderedDict to preserve order of keys from REST responses.
  201. Authors & License
  202. -----------------
  203. 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!
  204. Authentication mechanisms were adapted from Dave Wingate's `RestForce`_ and licensed under a MIT license
  205. The latest build status can be found at `Travis CI`_
  206. .. _Nick Catalano: https://github.com/nickcatal
  207. .. _community contributors: https://github.com/simple-salesforce/simple-salesforce/graphs/contributors
  208. .. _RestForce: http://pypi.python.org/pypi/RestForce/
  209. .. _GitHub Repo: https://github.com/simple-salesforce/simple-salesforce
  210. .. _Travis CI: https://travis-ci.org/simple-salesforce/simple-salesforce