Sub topic 1
REST API refresher: endpoints, versions, and authentication
Every composite request in this tutorial is an ordinary REST call to a Salesforce endpoint. It carries the same authentication and follows the same versioning rules as a single-record call. This chapter reviews those fundamentals so the later chapters can focus on composite behavior.
Prerequisites
This chapter assumes you already have the following:
- Basic REST concepts: HTTP methods, status codes, and JSON bodies.
- Familiarity with Salesforce objects, fields, and 15- or 18-character record IDs.
- A Salesforce org you can log in to, such as a Developer Edition org or a sandbox, and permission to create a Connected App or External Client App.
- Basic SOQL, and a rough idea of what the
/sobjectsand/queryendpoints do. curland Python 3 with therequestspackage installed, if you want to run the examples.
The shape of a REST URL
A Salesforce REST URL has three parts: the instance URL, a path prefix that includes the API version, and a resource.
https://MyDomain.my.salesforce.com/services/data/v60.0/sobjects/Account/001xx000003DGb2AAG
|------------ instance URL ----------| |-- prefix --|version|------ resource -------------|- Instance URL. This is the host of your org, usually your My Domain URL. Do not hard-code
login.salesforce.comor a guessed host such asna45.salesforce.com. The token response tells you the correct host in itsinstance_urlfield, and your client should use that value. - Prefix.
/services/data/is the root of the REST API for data. Other roots exist, such as/services/oauth2/for authentication and/services/apexrest/for custom Apex REST classes. - Version.
v60.0pins the API version. Field availability, response shapes, and some limits can differ between versions. - Resource. The rest of the path names the thing you are working with.
These resources appear most often in the chapters that follow:
| Resource | Typical use |
|---|---|
| `/sobjects/Account` | Create a record with POST |
| `/sobjects/Account/{id}` | Read, update, or delete one record |
| `/sobjects/Account/describe` | Get object metadata |
| `/query?q=...` | Run a SOQL query |
| `/limits` | Check org API usage |
| `/composite` | Run several dependent subrequests in one call |
The HTTP method sets the action. GET reads, POST creates, PATCH updates, and DELETE removes. A successful create returns 201 Created with the new ID in the body. A successful update or delete returns 204 No Content with no body. You will see these exact codes inside composite responses later, so it helps to recognize them now.
Choosing an API version
Every call names a version, and Salesforce keeps older versions available so existing integrations keep working. You can list the versions your org supports without authenticating:
curl "$INSTANCE_URL/services/data/"The response is a JSON array. Each element has label, url, and version fields. The last element is the newest version.
Follow these practices when you pick a version:
- Pin one version in a single constant or environment variable so every URL in your client uses it.
- Use the same version inside composite subrequests that you use for the outer call. A subrequest URL contains its own
/services/data/vXX.X/prefix, so a mismatch is easy to introduce by accident. - Test before you raise the version. A newer version can add fields to responses or change behavior, and your parsing code should tolerate that.
The examples in this tutorial use v60.0. Composite resources need a reasonably recent version, and your org must support the one you choose. If a call to a version-pinned URL returns a 404 with NOT_FOUND, check that the version appears in the /services/data/ list.
Authentication with OAuth 2.0
The REST API does not accept a username and password on each request. Instead, your client obtains an access token through an OAuth 2.0 flow and sends it in the Authorization header.
Getting a token
You need a Connected App or External Client App in the org. It supplies the client ID and client secret that identify your integration. The right flow depends on who is acting:
| Flow | When to use it |
|---|---|
| Authorization code (web server) | A user signs in through a browser and your app acts on their behalf |
| JWT bearer | A server-to-server integration that signs a token with a private key and acts as a pre-approved user |
| Client credentials | A server-to-server integration that acts as one designated run-as user, with no user interaction |
The username-password flow still works in some orgs, but Salesforce discourages it, and many orgs disable it. Avoid it in new code.
The sequence below shows how a token request and a later API call fit together:
Here is a client credentials request in Python. It assumes you have set MY_DOMAIN_URL, CLIENT_ID, and CLIENT_SECRET in the environment:
import os
import requests
token_url = os.environ['MY_DOMAIN_URL'] + '/services/oauth2/token'
resp = requests.post(
token_url,
data={
'grant_type': 'client_credentials',
'client_id': os.environ['CLIENT_ID'],
'client_secret': os.environ['CLIENT_SECRET'],
},
timeout=30,
)
resp.raise_for_status()
token = resp.json()
print('Instance URL:', token['instance_url'])
print('Token received:', bool(token['access_token']))The token endpoint must be your My Domain URL for the client credentials flow. The response contains access_token and instance_url, along with other fields. Store the access token in a variable or secret store and never print it, as the script above deliberately does not. The later examples in this tutorial read both values from the ACCESS_TOKEN and INSTANCE_URL environment variables.
Sending the token
Send the token on every request in an Authorization header with the Bearer scheme:
curl "$INSTANCE_URL/services/data/v60.0/sobjects/Account/describe" \
-H "Authorization: Bearer $ACCESS_TOKEN"Requests that send a body also need Content-Type: application/json. Composite requests always send a body, so you will include both headers every time.
Token expiry
An access token lasts only as long as the session timeout configured for the org or the Connected App. When the token expires, the API returns 401 Unauthorized with an error body like this:
[
{
"message": "Session expired or invalid",
"errorCode": "INVALID_SESSION_ID"
}
]A robust client treats this response as a signal to fetch a new token and retry the call once. It does not retry in a loop, because a repeated 401 usually means a configuration problem such as a revoked app or a disabled user.
Two related errors are worth keeping apart. A 401 means the token itself is not valid. A 403 means the token is valid but the running user lacks permission, for example because they have no access to the object or field. A 403 with the REQUEST_LIMIT_EXCEEDED error code means the org has used up its API allowance. Re-authenticating will not fix either 403.
Errors and the shape of failures
Most REST errors return a JSON array of objects. Each has a message and an errorCode, and field-validation failures also include a fields array. The HTTP status code gives the category, and errorCode gives the specific cause. Here is how to read the common ones:
| Status | Typical `errorCode` | Meaning |
|---|---|---|
| 400 | `MALFORMED_QUERY`, `REQUIRED_FIELD_MISSING` | The request is invalid |
| 401 | `INVALID_SESSION_ID` | The token is missing, expired, or revoked |
| 403 | `INSUFFICIENT_ACCESS`, `REQUEST_LIMIT_EXCEEDED` | The user lacks access or the org is over its limit |
| 404 | `NOT_FOUND` | The URL or record does not exist |
Keep this error format in mind. Inside a composite response, each failed subrequest returns the same array of error objects in its own body, next to its own httpStatusCode.
API limits and the cost of a call
Every REST call counts against the org's rolling 24-hour API request allowance, which depends on the edition and license count. Making many small calls therefore costs more than the time spent waiting on the network. It also uses up the allowance shared by every integration in the org.
You can check where you stand with the /limits resource. The following script prints the remaining daily requests:
import os
import requests
base = os.environ['INSTANCE_URL']
headers = {'Authorization': 'Bearer ' + os.environ['ACCESS_TOKEN']}
resp = requests.get(base + '/services/data/v60.0/limits', headers=headers, timeout=30)
resp.raise_for_status()
daily = resp.json()['DailyApiRequests']
print(daily['Remaining'], 'of', daily['Max'], 'API requests remaining')Normal REST responses also include a Sforce-Limit-Info header, such as api-usage=25/15000, which gives the same information without an extra call. Reading that header is a cheap way to monitor usage.
The next chapter picks up from here. It explains why one HTTP call carrying several operations saves both round trips and allowance, and then shows how a composite request is built.
Exercise
Your integration works for an hour, then every call fails with 401 and the error code INVALIDSESSIONID. A colleague proposes retrying each failed call up to 10 times. What should the client do instead, and why is a 403 different?
Show answer
The access token has expired, so the client should request a new token from the token endpoint and retry the failed call once. Retrying with the same token cannot succeed, and a repeated 401 after re-authenticating points to a configuration problem such as a revoked app or a disabled user. A 403 means the token is valid but the running user lacks permission, or the org has exceeded its API limit (REQUESTLIMITEXCEEDED), so getting a new token would not help.
Exercise
A client builds the URL "https://na45.salesforce.com/services/data/v60.0/sobjects/Account" by hand and later starts getting failures after the org moves to a different instance. Which value should the client have used for the host, and where does it come from?
Show answer
It should use the instance_url value from the OAuth token response (or the My Domain URL) instead of a hard-coded host. The token response names the correct host for the org.