Developers / Data

A Step-by-Step Guide to Salesforce Integration with Python

By Nancy Al Kalach

Whether you’re automating a daily sync, building custom reports, or managing records at scale, combining Python with Salesforce provides you with a flexible and efficient approach to get the job done. With the simple-salesforce Python library, you are able to connect to your org directly and perform multiple operations such as querying, updating, and upserting data, all from your Python script.

In this guide, I will walk through how to use Python to connect to a Salesforce org, run SOQL queries, and perform CRUD operations (Create, Read, Update, Delete). In addition, I will discuss a few extra steps that can contribute to a smoother and more powerful data workflow.

Why Should You Use Python?

Python regularly shows up at the top of surveys and studies that look at programming language adoption. Its popularity grew initially due to its emphasis on readability. It also has a vibrant ecosystem of libraries and extensions. Most recently, it has grown its user base due to its popularity with data science and machine learning, revolving around some of the most popular data and machine learning libraries such as Pandas, TensorFlow, Keras, PyTorch, sci-kitlearn, and Polars. 

If you want to work with your Salesforce data with best-in-class data libraries, Python is a great option. Let’s take a look at the steps you need to take to get started with Python!

Step 1: Set up your Python Environment

Let’s start by setting up your tools.

  1. Install Python and Set up your Virtual Environment.
  • If you don’t have Python 3.x installed yet, download it from python.org

To create and activate a virtual environment, run the commands below. (note, because of differences in file systems, the commands are specific to the operating system in this case):

Linux/Unix/Mac

python -m venv venv
source venv/bin/activate  

Windows CMD/PowerShell

python -m venv venv
venv\Scripts\activate

The above commands create an isolated Python environment called venv and activates it. This allows for the neat organization of your project’s dependencies.

  1. Install Required Packages

Python uses the pip package manager utility for installing packages from the PyPI package registry. We will need the following Python libraries with pip:

  • simple-salesforce: Handles API connections and requests for interacting with the Salesforce REST API.
  • pandas: Helps with easier data handling, analysis, and manipulation.
  • python-dotenv: Allows the secure storage of credentials in environment variables.

To install them, run the following command in your terminal:

pip install simple-salesforce pandas python-dotenv

Step 2: Securely Store Your Credentials

  1. Create a .env File

To avoid hard-coding your Salesforce credentials into the script, we’ll use environment variables. This keeps sensitive data out of your source code and version control.

In your project folder, create a file called .env with the following contents:

SF_USERNAME=your_email@example.com
SF_PASSWORD=your_password
SF_TOKEN=your_security_token_from_email

The above code stores your Salesforce login information in a file that you can exclude from your version control and load it into your script using environment variables.

You can log in using your Salesforce username, password, and a security token. If you don’t have your security token, check out how to reset and get your Salesforce security token here.

  1. Load Environment Variables in Python

Now, in your Python script (e.g., main.py), load these credentials using the python-dotenv library:

from dotenv import load_dotenv
import os
load_dotenv()
username = os.getenv("SF_USERNAME")
password = os.getenv("SF_PASSWORD")
token = os.getenv("SF_TOKEN")

This loads the values from your .env file and assigns them to Python variables. This helps keep sensitive info out of your source code.

Step 3: Connect to Salesforce

After completing step 2 and loading your credentials, you can establish a connection to Salesforce. Add the following code snippet at the bottom of your Python file:

from simple_salesforce import Salesforce

sf = Salesforce(
username=username,
password=password,
security_token=token

)

This authenticates the Python script with your Salesforce org and stores the session in the sf object, which you can then use to perform CRUD operations.

Step 4: Perform CRUD Operations in Salesforce with Python

In this section, I will walk you through how to perform CRUD (Create, Read, Update, and Delete) operations using the simple-salesforce library. Continue to add this code at the bottom of the Python file.

  1.  Create a New Record, running this:

new_contact_record = {
"FirstName": "Jane",
"LastName": "Doe",
"Email": "jane.doe@example.com"

}

result = sf.Contact.create(new_contact_record)
print("New Contact Id:", result["id"])

This creates a new Contact record in Salesforce, and prints the newly created Salesforce record Id for visibility.

Note: We are using Jane Doe in this example. Her cousin John was busy being a placeholder in every other database in the world, so she took one for the team.

  1. Add the code below to read a Single Record by Id. Copy the record Id that was output from above and replace the string “003XXX” with the actual record id:

contact = sf.Contact.get("003XXXX")
print(contact['FirstName'], contact['LastName'])

This fetches a Contact record by its unique Salesforce Id, and prints the contact fields values.

  1. Update an Existing Record (again, replacing the dummy Id below):

sf.Contact.update("003XXXX", {
"Email": "updated.email@example.com"
})

This updates the Email field on a Contact record using their record Id. 

Note: You only need to pass the record Id and the fields you want to update.

  1. Delete a Record by running this:

sf.Contact.delete("003XXXX")

This deletes a Contact from Salesforce using their record Id. 

  1. Upsert a Record Using an external Id. In order for this code to work, you’ll need to have a field on the Contact object set as an external Id. 

sf.Contact.upsert("External_ID__c/123", {
"FirstName": "Dan",
"LastName": "Smith",
"Email": "dan.smith@example.com"
})

This performs an upsert operation using a custom external Id field. If a record with that value exists, it’s updated. Otherwise, a new record is created.

Step 5: Run a Bulk SOQL Query

If you want to read data in bulk, you can run a SOQL query that returns a larger set of data:

results = sf.query("SELECT Name FROM Account LIMIT 100")

for record in results['records']:

print(record['Name'])

Bonus: Handling Large Query Results

results = sf.query_all("SELECT Id, Name FROM Account")

print("Total Records:", len(results["records"]))

Note: The above code bypasses the 2,000 record limit of .query() by using .query_all(), which retrieves all paginated results and returns them in a single structure.

Final Thoughts

With a few lines of code in Python, you are able to integrate with other systems, perform CRUD operations, and extract meaningful data

The simple-salesforce library makes it easy to bridge the gap between your codebase and your Salesforce org.

The Author

Nancy Al Kalach

Nancy Al Kalach is a Senior Salesforce Developer based in San Francisco, currently working at Illumina. Nancy holds multiple certifications, including Salesforce Agentforce Specialist and OmniStudio Developer.

Leave a Reply