Sub topic 4
REST API: the default choice for record access
The REST API is the interface most Salesforce integrations start with. It exposes records as resources at URLs, uses standard HTTP methods, and exchanges JSON. This chapter assumes you can read HTTP requests and JSON, know what Salesforce objects, fields, and records are, and can write basic SOQL. It also assumes you already have an access token from the OAuth 2.0 chapter.
Why REST is the default
Most integrations need to read a record, create one, change a field, or run a query. REST handles all of these with little setup. Any language with an HTTP client can call it, and no generated client code is needed. You can test it with curl before writing application code.
Other APIs win in specific cases:
- Bulk API 2.0 is better for hundreds of thousands of records.
- Event APIs are better when Salesforce must push changes to you.
- Metadata API is better for deploying configuration.
REST is the baseline you compare them against.
Anatomy of a REST request
Every request is sent to your org's My Domain, followed by a fixed path that includes an API version:
https://MyDomain.my.salesforce.com/services/data/v60.0/<resource>Three parts matter here:
- The host is your My Domain URL, or the
instance_urlvalue returned with your token. Do not hard-codelogin.salesforce.comfor data calls. That host is only for authentication. - The version (
v60.0) pins the behavior of the API. A version stays available for years, so an integration does not break when Salesforce ships a new release. Newer fields and features appear only in newer versions. - The header
Authorization: Bearer <token>identifies the caller on every request.
You can list the resources your org supports by calling GET /services/data/v60.0/.
REST calls run as the authenticated user. Object permissions, field-level security, and sharing rules all apply. If an integration user cannot see a field, requests for that field fail or return nothing. This is a common reason an integration works in an admin's test and fails in production. Create a dedicated integration user and give it only the permissions it needs.
The main resources
| Task | Method and path | Success response |
|---|---|---|
| Read a record | `GET /sobjects/Account/{id}` | 200 with JSON |
| Create a record | `POST /sobjects/Account` | 201 with `id` and `success` |
| Update a record | `PATCH /sobjects/Account/{id}` | 204, no body |
| Delete a record | `DELETE /sobjects/Account/{id}` | 204, no body |
| Upsert by external ID | `PATCH /sobjects/Account/ExtId__c/{value}` | 201 if created, 204 if updated |
| Run a query | `GET /query?q=...` | 200 with `records` |
| Describe an object | `GET /sobjects/Account/describe` | 200 with field metadata |
Two points surprise newcomers. Updates use PATCH, not PUT, and send only the fields that change. Updates also return an empty 204 response. To see the new values, read the record again.
Querying
The query resource runs a SOQL statement. The query string must be URL-encoded, which is why the example uses --data-urlencode:
curl -G "https://MyDomain.my.salesforce.com/services/data/v60.0/query" \
--data-urlencode "q=SELECT Id, Name FROM Account WHERE Industry = 'Technology' LIMIT 5" \
-H "Authorization: Bearer $ACCESS_TOKEN"The response has this shape:
{
"totalSize": 5,
"done": true,
"records": [
{
"attributes": { "type": "Account", "url": "/services/data/v60.0/sobjects/Account/001..." },
"Id": "001...",
"Name": "Acme Corp"
}
]
}Each record includes an attributes object with its type and URL. Parent and child relationships come back as nested objects, so SELECT Name, Owner.Name FROM Account gives you Owner as an object inside each record.
queryAll works like query but also returns soft-deleted records and archived tasks and events. Use it when you must see what was deleted.
Pagination
A query returns up to 2,000 records per response by default. If more matches exist, done is false and the response includes nextRecordsUrl. You follow that URL until done is true. You can request a smaller batch with the Sforce-Query-Options: batchSize=200 header. The allowed range is 200 to 2,000.
import os
import requests
instance = os.environ["INSTANCE_URL"]
headers = {"Authorization": f"Bearer {os.environ['ACCESS_TOKEN']}"}
url = f"{instance}/services/data/v60.0/query"
params = {"q": "SELECT Id, Name FROM Account WHERE Industry = 'Technology'"}
while url:
resp = requests.get(url, headers=headers, params=params, timeout=30)
resp.raise_for_status()
body = resp.json()
for record in body["records"]:
print(record["Id"], record["Name"])
url = None if body["done"] else f"{instance}{body['nextRecordsUrl']}"
params = None # nextRecordsUrl already carries the query cursorThe nextRecordsUrl is a relative path, so the code prepends the instance URL. Do not send params again with it. The cursor already identifies the query.
Creating, updating, and deleting
Creating a record sends a JSON body of field names and values:
curl -X POST "https://MyDomain.my.salesforce.com/services/data/v60.0/sobjects/Account" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"Name": "Acme Corp", "Industry": "Technology"}'A successful response looks like {"id": "001...", "success": true, "errors": []}.
To change one field, send a PATCH with only that field. To clear a field, set it to null:
curl -X PATCH "https://MyDomain.my.salesforce.com/services/data/v60.0/sobjects/Account/$ACCOUNT_ID" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"Industry": "Finance", "Description": null}'A PATCH that includes Id in the body fails, because the ID belongs in the URL. A request that includes a read-only field, such as CreatedDate, fails too.
Upsert with an external ID
An upsert creates a record if it does not exist and updates it if it does. It needs an external ID field, which is a custom field marked as an external ID. Integrations use it to avoid storing Salesforce IDs on the other system:
curl -X PATCH "https://MyDomain.my.salesforce.com/services/data/v60.0/sobjects/Account/ERP_Id__c/A-1001" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"Name": "Acme Corp"}'The response is 201 when a record was created and 204 when one was updated. If two records share the same external ID value, Salesforce returns 300 Multiple Choices instead of guessing. Mark the field as unique to prevent this.
Reading less data
Fetching a whole record returns every field the user can see. That is slow and wastes bandwidth. Ask only for what you need:
- Use
GET /sobjects/Account/{id}?fields=Id,Name,Industryfor a single record. - List fields in a SOQL
SELECT. REST queries have noSELECT *. - Use
describeto discover field names and types at runtime, for example to build a form or a mapping tool. Cache the result, since object definitions change rarely.
Errors
REST uses HTTP status codes and returns details in a JSON array:
[
{
"message": "Required fields are missing: [Name]",
"errorCode": "REQUIRED_FIELD_MISSING",
"fields": ["Name"]
}
]Branch on the status code first, then on errorCode. Do not parse the message text, because wording can change.
| Status | Typical cause | What to do |
|---|---|---|
| 400 | Malformed JSON, invalid field, bad SOQL | Fix the request. Retrying will not help. |
| 401 | Expired or invalid token (`INVALID_SESSION_ID`) | Refresh the token, then retry once. |
| 403 | Missing permission, or `REQUEST_LIMIT_EXCEEDED` | Check the error code, then fix permissions or slow down. |
| 404 | Wrong ID, or the record is not visible to the user | Verify the ID and the user's access. |
| 300 | Several records match an external ID | Make the external ID unique. |
| 415 | Wrong or missing `Content-Type` | Send `application/json`. |
Retry only errors that can succeed later. That means 401 after a token refresh, and 5xx responses or limit errors with a growing delay between attempts. Never retry a 400 unchanged.
Every response also carries a Sforce-Limit-Info header such as api-usage=18/15000. It reports how many API calls the org has used in the current 24-hour window. Log it, because running out of calls blocks every integration in the org. The API limits chapter covers this in detail.
Where REST stops being the best fit
REST is the right default for interactive and low-volume work. Move away from it when:
- You need to write many records at once. Composite and Bulk API 2.0 do this more efficiently.
- You need near-real-time notification of changes. Polling with queries wastes calls and still lags. Use Change Data Capture or Platform Events.
- You need custom server-side logic in one atomic call. Use an Apex REST endpoint.
- You need to deploy fields, objects, or flows. That is the Metadata API.
Exercise
A nightly job updates the Industry field on 3,000 Accounts by sending one PATCH /sobjects/Account/{id} per record. The first request returns 204. Later, the job gets a 403 with REQUEST_LIMIT_EXCEEDED. What does the 204 tell you about the response body, and what is the likely cause of the 403 and the first change you would make?
Show answer
A 204 means the update succeeded and there is no response body, so the job must read the record again to see the new values. The 403 means the org's daily API request allocation is used up, because each single-record call counts as one request. The first change is to stop making one call per record. Group the updates with Composite resources, or use Bulk API 2.0 for larger volumes. Read Sforce-Limit-Info to confirm the usage.
Exercise
Your query returns "done": false and a nextRecordsUrl of /services/data/v60.0/query/01gXXXX-2000. How do you get the remaining records?
Show answer
Send a GET request to the instance URL plus the nextRecordsUrl path, with the same Authorization header and no query parameters. Repeat with each new nextRecordsUrl until a response has "done": true.