Simple-Salesforce

1.12.9 · active · verified Sun Mar 29

Simple-Salesforce is a basic Salesforce.com REST API client built for Python 3.9 and newer versions. It provides a low-level interface to the Salesforce REST Resource and APEX API, returning JSON responses as Python dictionaries. The library facilitates common operations like authentication, CRUD operations on Salesforce objects, SOQL/SOSL queries, and interaction with Bulk and Metadata APIs. It's actively maintained with regular bug fixes and feature enhancements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to authenticate with Salesforce using username, password, and security token, then perform a simple SOQL query, create an account, and delete it. It emphasizes using environment variables for sensitive credentials.

import os
from simple_salesforce import Salesforce

# It's highly recommended to use environment variables for credentials
USERNAME = os.environ.get('SF_USERNAME', 'your_username@example.com')
PASSWORD = os.environ.get('SF_PASSWORD', 'your_password')
SECURITY_TOKEN = os.environ.get('SF_SECURITY_TOKEN', 'your_security_token')

# Optional: for sandbox use domain='test'
# For specific API versions, use sf_version='X.Y'

try:
    sf = Salesforce(
        username=USERNAME,
        password=PASSWORD,
        security_token=SECURITY_TOKEN,
        # domain='test' # Uncomment for sandbox
        # sf_version='59.0' # Uncomment for a specific API version
    )
    print(f"Successfully connected to Salesforce instance: {sf.instance_url}")

    # Example: Query Account records
    query_result = sf.query("SELECT Id, Name FROM Account LIMIT 5")
    print("\nFirst 5 Account Names:")
    for record in query_result['records']:
        print(f"  - {record['Name']} (Id: {record['Id']})")

    # Example: Create a new Account (replace with unique name for testing)
    new_account_name = "Test Account from simple-salesforce_" + str(os.urandom(4).hex())
    new_account = {'Name': new_account_name}
    create_result = sf.Account.create(new_account)
    print(f"\nCreated Account: {new_account_name} with Id: {create_result['id']}")

    # Example: Delete the created Account (cleanup)
    delete_result = sf.Account.delete(create_result['id'])
    print(f"Deleted Account with Id: {create_result['id']}")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Please ensure your SF_USERNAME, SF_PASSWORD, and SF_SECURITY_TOKEN environment variables are set correctly.")

view raw JSON →