ProgramMatek: A Comprehensive Guide to Salesforce API in Python

Build Status

This article will guide you through using the Salesforce API in Python, providing you with an easy-to-use and highly flexible solution for communication. Whether you need to interact with Salesforce through its REST or SOAP API, we’ve got you covered.

Content

  • Simple Usage
  • Authentication
  • Record Management
  • Querying SObjects
  • Bulk
  • Tooling
  • Deploying
  • Retrieving
  • Additional Features

Simple Usage

Creating a new connection or client is a breeze:

from salesforce_api import Salesforce

client = Salesforce(
    username='test@example.com',
    password='my-password',
    security_token='password-token'
)

Authentication

To get started with authentication, you can simply follow these steps:

from salesforce_api import Salesforce

client = Salesforce(
    username='test@example.com',
    password='my-password',
    security_token='password-token'
)

If you’re connecting to a sandbox, make sure to specify it using the is_sandbox argument:

from salesforce_api import Salesforce

client = Salesforce(
    username='test@example.com',
    password='my-password',
    security_token='password-token',
    is_sandbox=True
)

If you need to connect to a different login URL, you can specify it using the domain argument:

from salesforce_api import Salesforce

client = Salesforce(
    username='test@example.com',
    password='my-password',
    security_token='password-token',
    domain='login.example.com'
)

If you prefer to authenticate using an app, it’s just as easy:

from salesforce_api import Salesforce

client = Salesforce(
    username='test@example.com',
    password='my-password',
    client_id='123',
    client_secret='my-secret'
)

If you already have an OAuth access token, you can create a new client effortlessly:

from salesforce_api import Salesforce

client = Salesforce(
    access_token='access-token-here',
    domain='access-token-domain'
)

You can also choose to explicitly use a specific authentication method:

from salesforce_api import Salesforce, login

client = Salesforce(
    login.oauth2(
        username='test@example.com',
        password='my-password',
        client_id='123',
        client_secret='my-secret'
    )
)

And if you want to specify a Salesforce API version, you can do so:

from salesforce_api import Salesforce

client = Salesforce(
    access_token='access-token-here',
    domain='access-token-domain',
    api_version='51.0'
)

Record Management

Working with records is seamless, thanks to the exposed SObject-related methods on the client:

# Insert Example
client.sobjects.Contact.insert({'LastName': 'Example', 'Email': 'test@example.com'})

# Get Example
client.sobjects.Contact.get('0031l000007rU3vAAE')

# Update Example
client.sobjects.Contact.update('0031l000007rU3vAAE', {'FirstName': 'Felix', 'LastName': 'Lindstrom'})

# Upsert Example
client.sobjects.Contact.upsert('customExtIdField__c', '11999', {'FirstName': 'Felix', 'LastName': 'Lindstrom'})

# Delete Example
client.sobjects.Contact.delete('0031l000007rU3vAAE')

# Metadata Example
client.sobjects.Contact.metadata()

# Describe Example
client.sobjects.Contact.describe()

Querying SObjects

The Salesforce API efficiently handles large data sets, automatically managing pagination for query results:

# Query Example
client.sobjects.query("SELECT Id, FirstName, LastName FROM Contact WHERE FirstName='Felix'")

Bulk

This module implements the Bulk V2 API, allowing you to do more with less effort:

# Bulk Insert Example
client.bulk.insert('Contact', [
    {'LastName': 'Lindstrom', 'Email': 'test@example.com'},
    {'LastName': 'Something else', 'Email': 'test@example.com'}
])

# Bulk Upsert Example
client.bulk.upsert('Contact', [
    {'LastName': 'Lindstrom', 'Email': 'test@example.com', 'MyId__c': 1},
    {'LastName': 'Something else', 'Email': 'test@example.com', 'MyId__c': 2}
], external_id_field='MyId__c')

# Bulk Update Example
client.bulk.update('Contact', [
    {'LastName': 'Lindstrom', 'Email': 'test@example.com'},
    {'LastName': 'Something else', 'Email': 'test@example.com'}
])

# Bulk Delete Example
client.bulk.delete('Contact', ['0031l000007rU5rAAE', '0031l000007rU5sAAE'])

Tooling

The Salesforce API in Python also supports executing Apex code using the Tooling API:

# Execute Apex Example
client.tooling.execute_apex("System.debug('Test');")

Deploying

Deploying with the Salesforce API is straightforward:

from salesforce_api.models.deploy import Options

# Deploying an existing package
deployment = client.deploy.deploy('/path/to/file.zip')
deployment.wait()
result = deployment.get_status()

# Only validating
deployment = client.deploy.deploy('/path/to/file.zip', Options(checkOnly=True))
deployment.wait()
result = deployment.get_status()

# Validating running specific tests
deployment = client.deploy.deploy('/path/to/file.zip', Options(
    checkOnly=True,
    testLevel='RunSpecifiedTests',
    runTests=[
        'TesterIntegrationApplicationTest',
        'TesterIntegrationProcessTest'
    ]
))
deployment.wait()
result = deployment.get_status()

# Cancelling a deployment
deployment = client.deploy.deploy('/path/to/file.zip', Options(checkOnly=True))
while not deployment.is_done():
    if deployment.has_failed():
        deployment.cancel()
        break

Retrieving

The Salesforce API simplifies retrieving data using the Retrieve API:

from salesforce_api.models.shared import Type

types = [
    Type('ApexTrigger'),
    Type('ApexClass', ['MyMainClass', 'AnotherClass'])
]

retrieval = client.retrieve.retrieve(types)
retrieval.wait()
open('retrieve.zip', 'wb').write(retrieval.get_zip_file().read())

Additional Features

If you need to customize the way the client communicates with Salesforce, you have the flexibility to do so:

import requests
from salesforce_api import Salesforce

session = requests.Session()
session.proxies.update({'https': 'https://my-proxy.com/'})
session.headers.update({'User-Agent': 'My-User-Agent'})

client = Salesforce(
    username='test@example.com',
    password='my-password',
    security_token='password-token',
    session=session
)

For more information and detailed documentation, visit ProgramMatek. Enjoy exploring the Salesforce API in Python!

See also  Find Files Faster with Filepursuit API Key