A basic Salesforce.com REST API client for Python applications.
—
Comprehensive authentication support for various Salesforce deployment scenarios, including traditional password authentication, modern OAuth 2.0 flows, JWT bearer tokens for server-to-server integration, and direct session access for specialized use cases.
Primary authentication function that handles multiple authentication methods and returns session credentials for Salesforce API access.
def SalesforceLogin(
username=None,
password=None,
security_token=None,
organizationId=None,
sf_version="59.0",
proxies=None,
session=None,
client_id=None,
domain=None,
instance_url=None,
consumer_key=None,
consumer_secret=None,
privatekey_file=None,
privatekey=None,
scratch_url=None
):
"""
Authenticate with Salesforce using various methods.
Parameters:
- username: Salesforce username
- password: Salesforce password
- security_token: Security token (required for password auth outside trusted IP ranges)
- organizationId: Organization ID for IP filtering authentication
- sf_version: Salesforce API version (default: "59.0")
- proxies: HTTP proxy configuration
- session: Custom requests.Session object
- client_id: Connected App client ID
- domain: Salesforce domain (login.salesforce.com, test.salesforce.com, etc.)
- instance_url: Direct Salesforce instance URL
- consumer_key: OAuth Consumer Key for Connected Apps
- consumer_secret: OAuth Consumer Secret for Connected Apps
- privatekey_file: Path to private key file for JWT authentication
- privatekey: Private key content for JWT authentication
- scratch_url: Scratch org URL for development
Returns:
Tuple[str, str]: (session_id, sf_instance) for authenticated session
"""The Salesforce class constructor supports all authentication methods through its parameters, automatically selecting the appropriate authentication flow based on provided credentials.
class Salesforce:
def __init__(
self,
username=None,
password=None,
security_token=None,
session_id=None,
instance=None,
instance_url=None,
organizationId=None,
version="59.0",
proxies=None,
session=None,
client_id=None,
domain=None,
consumer_key=None,
consumer_secret=None,
privatekey_file=None,
privatekey=None,
parse_float=None,
object_pairs_hook=dict
):
"""
Initialize Salesforce client with authentication.
Parameters:
- username: Salesforce username
- password: Salesforce password
- security_token: Security token for password authentication
- session_id: Existing session ID for direct access
- instance: Salesforce instance domain (e.g., 'na1', 'eu0')
- instance_url: Complete instance URL
- organizationId: Organization ID for IP filtering
- version: API version string (default: "59.0")
- proxies: HTTP proxy configuration dictionary
- session: Custom requests.Session object
- client_id: Connected App client identifier
- domain: Authentication domain (login.salesforce.com, test.salesforce.com)
- consumer_key: OAuth Consumer Key for Connected Apps
- consumer_secret: OAuth Consumer Secret for Connected Apps
- privatekey_file: Path to private key file for JWT flows
- privatekey: Private key content string for JWT flows
- parse_float: Custom JSON float parser
- object_pairs_hook: Custom JSON object hook (default: dict)
"""Traditional username/password authentication with security token, suitable for interactive applications and development environments.
from simple_salesforce import Salesforce
# Basic password authentication
sf = Salesforce(
username='user@example.com',
password='mypassword',
security_token='mytoken'
)
# With custom domain (for sandbox/custom domains)
sf = Salesforce(
username='user@example.com',
password='mypassword',
security_token='mytoken',
domain='test.salesforce.com' # For sandbox
)
# With organization ID (for IP filtering)
sf = Salesforce(
username='user@example.com',
password='mypassword',
organizationId='00D000000000000'
)OAuth authentication using Connected App credentials, supporting both password grant and client credentials flows.
from simple_salesforce import Salesforce
# OAuth with username/password grant
sf = Salesforce(
username='user@example.com',
password='mypassword',
consumer_key='3MVG9PhR6g6B7ps6...',
consumer_secret='1234567890123456789'
)
# Client credentials flow (no user context)
sf = Salesforce(
consumer_key='3MVG9PhR6g6B7ps6...',
consumer_secret='1234567890123456789',
domain='login.salesforce.com'
)Server-to-server authentication using JWT tokens, ideal for automated systems and CI/CD pipelines.
from simple_salesforce import Salesforce
# JWT with private key file
sf = Salesforce(
username='user@example.com',
consumer_key='3MVG9PhR6g6B7ps6...',
privatekey_file='/path/to/private.key'
)
# JWT with inline private key
private_key_content = '''-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA...
-----END RSA PRIVATE KEY-----'''
sf = Salesforce(
username='user@example.com',
consumer_key='3MVG9PhR6g6B7ps6...',
privatekey=private_key_content
)Authentication using existing session ID and instance, useful for applications that manage authentication separately.
from simple_salesforce import Salesforce
# With session ID and instance domain
sf = Salesforce(
session_id='00D50000000IehZ!AQcAQH0dMHZfz972dbC_XM5',
instance='na1'
)
# With session ID and full instance URL
sf = Salesforce(
session_id='00D50000000IehZ!AQcAQH0dMHZfz972dbC_XM5',
instance_url='https://na1.salesforce.com'
)Using the SalesforceLogin function directly for custom authentication workflows.
from simple_salesforce import SalesforceLogin, Salesforce
# Separate authentication step
session_id, instance = SalesforceLogin(
username='user@example.com',
password='mypassword',
security_token='mytoken'
)
# Use credentials to create client
sf = Salesforce(
session_id=session_id,
instance=instance
)import requests
from simple_salesforce import Salesforce
# Custom session with specific configuration
custom_session = requests.Session()
custom_session.headers.update({'User-Agent': 'MyApp/1.0'})
sf = Salesforce(
username='user@example.com',
password='mypassword',
security_token='mytoken',
session=custom_session
)from simple_salesforce import Salesforce
# HTTP proxy configuration
proxies = {
'http': 'http://proxy.company.com:8080',
'https': 'https://proxy.company.com:8080'
}
sf = Salesforce(
username='user@example.com',
password='mypassword',
security_token='mytoken',
proxies=proxies
)from simple_salesforce import Salesforce
# Specify API version
sf = Salesforce(
username='user@example.com',
password='mypassword',
security_token='mytoken',
version='58.0' # Use specific API version
)After successful authentication, the Salesforce client provides access to session information:
# Session details
print(f"Session ID: {sf.session_id}")
print(f"Instance: {sf.sf_instance}")
print(f"API Version: {sf.sf_version}")
print(f"Base URL: {sf.base_url}")
# API endpoint URLs
print(f"Bulk API URL: {sf.bulk_url}")
print(f"Bulk 2.0 API URL: {sf.bulk2_url}")
print(f"Metadata API URL: {sf.metadata_url}")
print(f"Tooling API URL: {sf.tooling_url}")
# Check if sandbox
is_sandbox = sf.is_sandbox()
print(f"Is Sandbox: {is_sandbox}")Authentication methods raise specific exceptions for different failure scenarios:
from simple_salesforce import (
Salesforce,
SalesforceAuthenticationFailed,
SalesforceGeneralError
)
try:
sf = Salesforce(
username='invalid@example.com',
password='wrongpassword',
security_token='badtoken'
)
except SalesforceAuthenticationFailed as e:
print(f"Authentication failed: {e}")
except SalesforceGeneralError as e:
print(f"General error: {e}")Low-level SOAP-based authentication function used internally by password authentication.
def soap_login(
soap_url,
request_body,
headers,
proxies,
session=None
):
"""
Perform SOAP-based login to Salesforce.
Parameters:
- soap_url: SOAP API endpoint URL
- request_body: SOAP request body XML
- headers: HTTP headers dictionary
- proxies: Proxy configuration
- session: Optional requests.Session object
Returns:
Tuple[str, str]: (session_id, server_url)
"""Low-level OAuth token-based authentication function used internally by OAuth flows.
def token_login(
token_url,
token_data,
domain,
consumer_key,
headers,
proxies,
session=None
):
"""
Perform OAuth token-based login to Salesforce.
Parameters:
- token_url: OAuth token endpoint URL
- token_data: OAuth request parameters
- domain: Salesforce domain
- consumer_key: OAuth consumer key
- headers: HTTP headers dictionary
- proxies: Proxy configuration
- session: Optional requests.Session object
Returns:
Tuple[str, str]: (session_id, instance_url)
"""Install with Tessl CLI
npx tessl i tessl/pypi-simple-salesforce