Sub topic 6
Calling the REST API with the access token
This chapter assumes you can read curl commands and JSON, and that you already know how to get a token response from one of the three flows. Every flow ends here. The access token is only useful once you send it to the REST API.
The two values you need
A token response contains many fields, but a call to the REST API needs only two:
access_token: the credential that proves your app is authorized.instance_url: the base URL of the org that issued the token.
Build every API URL from instance_url. Do not hard-code login.salesforce.com or a guessed host. The login host issues tokens, and the instance host serves data.
The request pattern
Send the token in an Authorization header with the Bearer scheme. Then add the path to the resource you want.
curl https://MyDomainName.my.salesforce.com/services/data/v60.0/limits \
-H "Authorization: Bearer <ACCESS_TOKEN>"The URL has three parts:
instance_url, for examplehttps://MyDomainName.my.salesforce.com./services/data/, the root of the REST API.v60.0, the API version. Pin a version so that your integration behaves the same over time.
The limits resource is a good first test. It is a small, read-only call that shows your org's API usage. A JSON reply means the token works.
Putting it together in Python
This script reads the two fields from a token response and makes the same call. It assumes token is the parsed JSON from one of the earlier flows.
import requests
def get_limits(token: dict) -> dict:
url = f"{token['instance_url']}/services/data/v60.0/limits"
headers = {"Authorization": f"Bearer {token['access_token']}"}
resp = requests.get(url, headers=headers, timeout=30)
resp.raise_for_status()
return resp.json()Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `401` with `INVALID_SESSION_ID` | The access token expired or was revoked. | Refresh the token, or repeat the JWT or client credentials request. Then retry once. |
| `403` with `INSUFFICIENT_ACCESS` or an API-not-enabled message | The user lacks API access, or the scope was not granted. | Check the `api` scope and the user's profile or permission set. |
| Connection or redirect errors | The URL was built from the login host. | Use `instance_url` from the token response. |
A 401 is not a reason to ask the user to log in again. Where a refresh token exists, use it. For JWT bearer and client credentials, which issue no refresh token, request a new access token.
Exercise
Your app receives a token response with instance_url set to https://acme.my.salesforce.com. A call to https://login.salesforce.com/services/data/v60.0/limits with the bearer token fails. What do you change, and where does the new URL come from?
Show answer
Send the call to https://acme.my.salesforce.com/services/data/v60.0/limits. The base URL comes from the instance_url field of the token response, because the login host only issues tokens and does not serve REST API data.