How Can We Help?
< All Topics

Authenticate with the Salesforce REST API in Python

Here’s an example of how to authenticate with the Salesforce REST API in Python using the OAuth 2.0 Web Server Flow (also known as the Username and Password Flow) with a client ID and client secret. This example uses the requests library to make HTTP requests:

import requests
import json

# Salesforce OAuth endpoint and your credentials
oauth_url = ''  # Use the appropriate URL for your Salesforce instance (e.g., for production)
client_id = 'your_client_id'  # Your Salesforce connected app's client ID
client_secret = 'your_client_secret'  # Your Salesforce connected app's client secret
username = 'your_username'  # Your Salesforce username
password = 'your_password'  # Your Salesforce password
security_token = 'your_security_token'  # Your Salesforce security token

# Define the request payload
data = {
    'grant_type': 'password',
    'client_id': client_id,
    'client_secret': client_secret,
    'username': username,
    'password': password + security_token  # Append the security token to your password

# Make a POST request to authenticate
response =, data=data)

# Check the response status
if response.status_code == 200:
    # Authentication successful, parse the response JSON to get the access token
    response_data = json.loads(response.text)
    access_token = response_data['access_token']

    # You can now use the access token to make authenticated API requests
    # For example, let's query some data from Salesforce
    query_url = ',Name+FROM+Account+LIMIT+5'  # Replace 'your-instance' with your Salesforce instance
    headers = {'Authorization': 'Bearer ' + access_token}
    query_response = requests.get(query_url, headers=headers)

    if query_response.status_code == 200:
        query_data = json.loads(query_response.text)
        for record in query_data['records']:
            print(f"Account ID: {record['Id']}, Name: {record['Name']}")
        print(f"Query failed with status code: {query_response.status_code}")
    print(f"Authentication failed with status code: {response.status_code}")
    print(f"Response content: {response.text}")

In this code:

  • Replace 'your_client_id', 'your_client_secret', 'your_username', 'your_password', and 'your_security_token' with your actual Salesforce credentials.
  • Update the oauth_url to match your Salesforce environment (e.g., '' for a sandbox).
  • Modify the query_url to match the specific API endpoint you want to access in your Salesforce instance.

Remember that storing sensitive information like your client secret in code is not recommended for production applications. You should use a more secure OAuth flow, and securely manage your credentials.

Please suggest edits or add your comments.

Your email address will not be published. Required fields are marked *

Scroll to Top