Sub topic 2
Authenticating with an OAuth access token
Every call to the Salesforce REST API must prove who is calling. This chapter covers how that works and the errors you will see when it fails. It assumes you know basic HTTP (methods, headers, status codes), can read JSON, and can run curl or a short Python script. You also need a Salesforce org, such as a Developer Edition org.
How authentication works
The REST API uses OAuth 2.0. You do not send a username and password with each request. Instead, you obtain an access token, a string that represents a session for one user. You then send that token in the Authorization header of every request.
The header uses the Bearer scheme:
Authorization: Bearer <access token>Whoever holds the token can act as that user, within that user's permissions. Treat it like a password.
Getting a token
This tutorial does not cover every OAuth flow. You choose a flow based on your app. Common choices are:
| Flow | Typical use |
|---|---|
| Authorization code (with PKCE) | An app where a person logs in through a browser |
| Client credentials | A server-to-server integration with no person involved |
| JWT bearer | A server-to-server integration that signs a request with a certificate |
For learning, you can also get a token from the Salesforce CLI with sf org display, which prints an access token and the instance URL for an org you have logged in to. Either way, the token response includes two values you need:
access_token: the token to put in the header.instance_url: the base URL of your org, such ashttps://MyDomain.my.salesforce.com.
Always send requests to the instance_url returned with the token. The next chapter shows how it forms part of every resource URL.
Setting up your shell
The examples in this tutorial read the token from environment variables. Set them once per terminal session:
export SF_INSTANCE_URL="https://MyDomain.my.salesforce.com"
export SF_ACCESS_TOKEN="<access token>"
export SF_API_VERSION="v60.0"Now send a request that only needs authentication. The /services/data/ path on its own lists the API versions your org supports:
curl "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN"A 200 response with a JSON list of resources means your token works. The same header goes on every create, read, and update call in later chapters.
The same request in Python
With the requests library, keep the headers in one dictionary and reuse it:
import os
import requests
instance_url = os.environ["SF_INSTANCE_URL"]
token = os.environ["SF_ACCESS_TOKEN"]
version = os.environ.get("SF_API_VERSION", "v60.0")
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
response = requests.get(
f"{instance_url}/services/data/{version}/",
headers=headers,
timeout=30,
)
print(response.status_code)The request flow
Common authentication errors
Access tokens expire. When a token is no longer valid, Salesforce answers with status 401 and a JSON error body like this:
[
{
"message": "Session expired or invalid",
"errorCode": "INVALID_SESSION_ID"
}
]Check these causes in order:
- The token expired. Request a new one with your OAuth flow. If your flow issued a refresh token, exchange it for a new access token.
- The header is malformed. It must read
Authorization: Bearer <token>, with the wordBearerand one space. - You are calling the wrong host. A token from a sandbox does not work against a production URL, and the reverse is also true.
- The environment variable is empty or stale. Run
echo "$SF_ACCESS_TOKEN"to check.
A 403 response is different. It means the token is valid but the user lacks permission for that object or action. Getting a new token will not fix it. Change the user's permissions instead.
Exercise
A request returns 401 with the error code INVALIDSESSIONID. A colleague suggests giving the user more permissions on the Account object. Why is that the wrong fix, and what should you do?
Show answer
A 401 means Salesforce rejected the token itself, usually because it expired or is malformed. Permissions only matter for a 403, which is returned when the token is valid but the user may not perform the action. Get a fresh access token (for example with the refresh token), confirm the header reads "Authorization: Bearer <token>", and retry.