Tired of setting up a Connected App for every script? Here’s a shortcut for developers using the Salesforce CLI.
Snippets: Skip OAuth — Use Salesforce CLI for Quick API Calls
Tired of setting up a Connected App for every script? Here’s a shortcut for developers using the Salesforce CLI.
If you work with Salesforce, you’ve probably been there: you need to connect to an org via API for a quick, one-off task. Maybe it’s to run a quick analysis, explore a data model, or pull a small report.
Best approach is to follow the usual: set up a Connected App or ECA, manage OAuth scopes, and handle the credentials securely. And for any long-term, automated integration, that is absolutely the correct and most secure path.
Recently, however, I had a task that was strictly temporary and isolated. The usual setup felt like overkill. As I was thinking it through, I realized I was already authenticated to the org on my local machine through the Salesforce CLI. That led to a simple question: “Can I just use this existing session?”
It turns out, you can. It saved me a good bit of setup time, and I wanted to share it. It’s a handy shortcut for a developer’s toolkit, as long as its specific use case and limitations are respected. Here’s a look at how you can leverage your existing CLI configuration for temporary API access.

A Word of Caution: When (and When Not) to Use This
Before we dive into the code, let’s be clear. This method is NOT a replacement for a properly configured Connected App or the new External Client Apps for production integrations.
Think of this as a developer productivity hack for specific scenarios:
- Temporary Analysis: You need to quickly query some data for a one-time report.
- Org Evaluation: You’re assessing a new or unfamiliar org and want to explore its schema or data programmatically.
- Isolated Scripts: You’re running a local script on your machine for a short-lived task.
This approach is unsuitable for:
- Automated, recurring production jobs.
- Integrations running on servers or shared environments.
- Distributing to non-technical users.
- Any situation where you need fine-grained control over permissions and scopes, which Connected Apps provide.
The security of this method is tied to the security of your local machine and your CLI session. The access token you generate will have the exact same permissions as the user you used to log in with the CLI.
The “How-To”: Leveraging the Salesforce CLI with Python
The solution is a simple Salesforce CLI command: sf org display --json
. When you run this against an authenticated org, it outputs a JSON structure containing all the connection details, including the instanceUrl
and, most importantly, a valid accessToken
.
Let’s build a Python script to use this.
Step 1: Get the Access Token from the CLI
First, we need a function to execute the CLI command and parse its JSON output. This function will be our gateway to receiving a fresh access token whenever we need one.
import subprocess
import json
import requests
# --- Configuration ---
# The alias for your target org.
# Use 'sf org list' to see your authenticated orgs.
SF_ORG_ALIAS = "my-scratch-org"
def get_salesforce_session(org_alias):
"""
Executes the 'sf org display' command to get session details.
Args:
org_alias (str): The alias of the target Salesforce org.
Returns:
tuple: A tuple containing the access token and instance URL,
or (None, None) if an error occurs.
"""
print(f"Attempting to get a new session for org: {org_alias}...")
try:
# Command to get org details including the access token in JSON format
command = [
"sf", "org", "display",
"--target-org", org_alias,
"--json"
]
# Execute the command
process = subprocess.run(command, capture_output=True, text=True, check=True)
# Parse the JSON output
org_details = json.loads(process.stdout)
# Extract the required details
access_token = org_details.get("result", {}).get("accessToken")
instance_url = org_details.get("result", {}).get("instanceUrl")
if not access_token or not instance_url:
print("Error: Could not find accessToken or instanceUrl in CLI output.")
return None, None
print("Successfully obtained new session details.")
return access_token, instance_url
except subprocess.CalledProcessError as e:
print(f"Error executing Salesforce CLI command: {e}")
print(f"Stderr: {e.stderr}")
return None, None
except json.JSONDecodeError:
print("Error: Failed to parse JSON from CLI output.")
return None, None
except FileNotFoundError:
print("Error: 'sf' command not found. Is the Salesforce CLI installed and in your PATH?")
return None, None
Step 2: Query Salesforce Using the Token
With the access token and instance URL, we can now make authenticated REST API calls. Here’s a function to run a simple SOQL query.
def query_accounts(access_token, instance_url):
"""
Queries for five Account records from Salesforce using the REST API.
Args:
access_token (str): The active Salesforce session token.
instance_url (str): The URL of the Salesforce instance.
Returns:
requests.Response: The response object from the API call.
"""
soql_query = "SELECT Id, Name, CreatedDate FROM Account ORDER BY CreatedDate DESC LIMIT 5"
# The REST API endpoint for SOQL queries
query_url = f"{instance_url}/services/data/v59.0/query"
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json"
}
params = {
"q": soql_query
}
print("Executing SOQL query...")
response = requests.get(query_url, headers=headers, params=params)
return response
Step 3: Putting It All Together & Handling Expiration
The access token from the CLI is temporary. If your script runs for a while, the token will expire, and your API calls will fail with a 401 Unauthorized
status code. Our script needs to handle this gracefully by getting a new token and retrying the request.
This main function orchestrates the entire process.
def main():
"""
Main function to demonstrate the CLI session usage.
"""
print("--- Starting Salesforce API script using CLI session ---")
# 1. Get initial session details
access_token, instance_url = get_salesforce_session(SF_ORG_ALIAS)
if not access_token:
print("Could not establish a Salesforce session. Exiting.")
return
# 2. Make the initial API call
response = query_accounts(access_token, instance_url)
# 3. Check if the token was expired and retry if necessary
if response.status_code == 401:
print("Access token appears to be expired. Refreshing session...")
access_token, instance_url = get_salesforce_session(SF_ORG_ALIAS)
if not access_token:
print("Could not refresh the Salesforce session. Exiting.")
return
# Retry the query with the new token
print("Retrying SOQL query with new token...")
response = query_accounts(access_token, instance_url)
# 4. Process the final response
if response.ok:
results = response.json()
print("\n--- Query Successful! Found Accounts: ---")
for record in results.get("records", []):
print(f" ID: {record['Id']}, Name: {record['Name']}")
print("----------------------------------------")
else:
print(f"\n--- Query Failed! ---")
print(f"Status Code: {response.status_code}")
print(f"Response: {response.text}")
print("-----------------------")
if __name__ == "__main__":
# IMPORTANT: Before running, make sure you have an active CLI session.
# Run this in your terminal: `sf org login web -a my-scratch-org`
# replacing 'my-scratch-org' with your desired alias.
main()
Final Thoughts and Security Reminders
This CLI shortcut is a great example of how our development tools can sometimes offer clever workarounds. It can certainly streamline ad-hoc tasks and help you avoid the ceremony of a full integration setup when it’s not needed.
However, always remember the security implications:
- Secure Your Machine: Since the script leverages your local CLI session, anyone with access to your user account on your machine could potentially run it. Maintain good local system security.
- Principle of Least Privilege: The script operates with your full user permissions. Be mindful of this when running scripts that perform data manipulation (DML).
- No Hardcoding: Notice the script doesn’t contain any secrets. It dynamically fetches them, which is a major security advantage over hardcoding credentials.
- Audit and Log: CLI commands and API calls made this way are still auditable within Salesforce Setup Audit Trail, associated with your user account.
It’s a useful technique for the right context. I hope you find it helpful in your own Salesforce development and analysis work.