Sub topic 6
Calling the REST API with the access token
Every flow in this tutorial ends the same way. You hold an access token and an instance_url, and you use them to call the Salesforce REST API. This chapter covers building that request, reading the response, and handling the failures you will meet in practice.
This chapter assumes you know basic HTTP (methods, headers, status codes), can read short Python snippets, and have a token response from one of the flows. The token response fields were covered in the previous chapter.
What a REST API call needs
A call needs three things:
- The host. Use the
instance_urlfrom the token response, such ashttps://MyDomainName.my.salesforce.com. Do not hard-codelogin.salesforce.comfor API calls. That host issues tokens and does not serve data. - A versioned path. REST resources live under
/services/data/vNN.N/, for example/services/data/v60.0/limits. The version in the path fixes the behavior of the resource, so your integration does not change when Salesforce ships a new release. - The token in an
Authorizationheader. The scheme isBearer, followed by a space and the access token.
curl https://MyDomainName.my.salesforce.com/services/data/v60.0/limits \
-H "Authorization: Bearer <ACCESS_TOKEN>"The limits resource is a good first call. It is cheap, it needs no object permissions, and it fails clearly if the token is bad.
The request lifecycle
The diagram shows the usual sequence, including the case where the token has expired.
Discovering API versions
GET /services/data/ returns the list of versions the org supports, each with a version and a url. Use it to confirm which version a given org offers. Pick one version and pin it in your configuration. Raise it deliberately after testing.
Querying records
SOQL queries go through the query resource. URL-encode the query text in the q parameter.
curl "https://MyDomainName.my.salesforce.com/services/data/v60.0/query?q=SELECT+Id,Name+FROM+Account+LIMIT+3" \
-H "Authorization: Bearer <ACCESS_TOKEN>" \
-H "Accept: application/json"A successful response looks like this:
{
"totalSize": 3,
"done": true,
"records": [
{
"attributes": {
"type": "Account",
"url": "/services/data/v60.0/sobjects/Account/001000000000001AAA"
},
"Id": "001000000000001AAA",
"Name": "Acme"
}
]
}If done is false, the result is split across pages. The response then includes nextRecordsUrl, a path relative to the instance. Request that path with the same header until done is true.
A reusable client in Python
The script below calls an endpoint, follows query pages, and refreshes the token once if it gets a 401. It uses the refresh token grant from the web server flow. For JWT bearer or client credentials, replace refresh_access_token with a function that repeats that flow's token request.
import os
import requests
LOGIN_URL = os.environ.get("SF_LOGIN_URL", "https://login.salesforce.com")
API_VERSION = "v60.0"
class SalesforceClient:
def __init__(self, instance_url, access_token, refresh_token,
client_id, client_secret):
self.instance_url = instance_url.rstrip("/")
self.access_token = access_token
self.refresh_token = refresh_token
self.client_id = client_id
self.client_secret = client_secret
def refresh_access_token(self):
resp = requests.post(
f"{LOGIN_URL}/services/oauth2/token",
data={
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
"client_id": self.client_id,
"client_secret": self.client_secret,
},
timeout=30,
)
resp.raise_for_status()
body = resp.json()
self.access_token = body["access_token"]
# instance_url can be returned again; keep the latest value.
self.instance_url = body.get("instance_url", self.instance_url)
def get(self, path, params=None):
url = path if path.startswith("http") else self.instance_url + path
for attempt in range(2):
resp = requests.get(
url,
params=params,
headers={"Authorization": f"Bearer {self.access_token}"},
timeout=30,
)
if resp.status_code == 401 and attempt == 0:
self.refresh_access_token()
continue
resp.raise_for_status()
return resp
raise RuntimeError("unreachable")
def query(self, soql):
path = f"/services/data/{API_VERSION}/query"
resp = self.get(path, params={"q": soql})
data = resp.json()
records = list(data["records"])
while not data["done"]:
data = self.get(data["nextRecordsUrl"]).json()
records.extend(data["records"])
return records
if __name__ == "__main__":
client = SalesforceClient(
instance_url=os.environ["SF_INSTANCE_URL"],
access_token=os.environ["SF_ACCESS_TOKEN"],
refresh_token=os.environ["SF_REFRESH_TOKEN"],
client_id=os.environ["SF_CLIENT_ID"],
client_secret=os.environ["SF_CLIENT_SECRET"],
)
for row in client.query("SELECT Id, Name FROM Account LIMIT 5"):
print(row["Id"], row["Name"])Two details in this code matter. The retry runs once only, so a revoked refresh token raises an error instead of looping. The requests library passes params through URL encoding for you, so you do not hand-encode the SOQL.
Reading the error responses
Salesforce REST errors return a JSON array, each element with message and errorCode.
| Status | `errorCode` | Usual cause | What to do |
|---|---|---|---|
| 401 | `INVALID_SESSION_ID` | Token expired, revoked, or sent to the wrong instance | Get a new token, then retry once. Check the host if it persists. |
| 403 | `INSUFFICIENT_ACCESS` or `API_DISABLED_FOR_ORG` | The user lacks the permission, or the API is not enabled | Fix the user's profile or permission sets. Retrying does not help. |
| 403 | `REQUEST_LIMIT_EXCEEDED` | The org has used its API allowance | Back off and reduce call volume. |
| 400 | `MALFORMED_QUERY` | SOQL syntax error | Fix the query. |
| 404 | `NOT_FOUND` | Wrong path, version, or record ID | Check the URL. |
A 401 and a 403 mean different things. A 401 says the token is not accepted, so you refresh it. A 403 says the token is valid but the user is not allowed, so a new token will not change the result.
Two things that decide what the call can do
The token does not grant access by itself. A call succeeds only when both of these hold:
- The scope allows API access. The connected app must grant the
apiscope. A token with onlyopenidcan read identity data and nothing else. - The user has the data permissions. The token acts as a specific user. In the web server flow that is the person who logged in, in the JWT bearer flow it is the user named in
sub, and in the client credentials flow it is the run-as user. Object, field, and record access follow that user's profile and permission sets.
Watching API usage
Each response carries a Sforce-Limit-Info header such as api-usage=18/15000. This reports calls used against the org's 24-hour allowance. Log it in long-running integrations so you see the limit approaching before REQUEST_LIMIT_EXCEEDED appears. The limits resource returns the same information for many other limits in one call.
Exercise
Your integration gets a 401 with INVALID_SESSION_ID from https://login.salesforce.com/services/data/v60.0/limits, even though the token was issued seconds ago. What is the most likely cause, and what do you change?
Show answer
The request went to the login host instead of the org's instance. login.salesforce.com issues tokens and does not serve REST data, so it does not recognize the session. Send the call to the instance_url from the token response, for example https://MyDomainName.my.salesforce.com/services/data/v60.0/limits, with the same Authorization: Bearer header.
Exercise
A query returns "done": false and a nextRecordsUrl. How do you get the remaining records, and how do you authenticate that request?
Show answer
Send a GET to the instance URL plus nextRecordsUrl with the same Authorization: Bearer <ACCESS_TOKEN> header. Repeat until a response has "done": true, and combine the records arrays from every page.