Sub topic 1
Combining Requests with the Salesforce Composite API
Prerequisites
This chapter assumes you understand HTTP methods such as GET and POST, HTTP status codes, JSON request bodies, Salesforce object fields, and record IDs. You also need an OAuth access token and your Salesforce org’s instance URL.
REST API refresher: endpoints, versions, and authentication
A Salesforce REST endpoint identifies the API resource and version. A typical sObject endpoint is:
/services/data/v60.0/sobjects/AccountThe version is part of the URL, so choose a version supported by your org and client. A request must include an OAuth bearer token and usually a JSON content type:
curl "$INSTANCE_URL/services/data/v60.0/sobjects/Account/describe" \
-H "Authorization: Bearer $ACCESS_TOKEN"The instance URL identifies the Salesforce host. Keep the access token outside source code, such as in an environment variable.
Why combine requests
Separate HTTP calls create network round trips. They also consume API calls and make dependent operations harder to coordinate. The Composite API lets one HTTP request contain several related subrequests. Salesforce executes those subrequests and returns an individual result for each one.
A composite request is useful when a client must create a record, use its new ID, and then query or create a related record.
Anatomy of a composite request
Send a POST request to /services/data/v60.0/composite. The body contains compositeRequest, an array of subrequests. Each subrequest has an HTTP method, a relative REST URL, a unique referenceId, and an optional body.
{
"allOrNone": true,
"compositeRequest": [
{
"method": "POST",
"url": "/services/data/v60.0/sobjects/Account",
"referenceId": "newAccount",
"body": { "Name": "Acme Corp" }
},
{
"method": "GET",
"url": "/services/data/v60.0/sobjects/Account/@{newAccount.id}",
"referenceId": "readAccount"
}
]
}The outer HTTP response contains compositeResponse. Each entry includes the matching referenceId, an HTTP status code, headers, and a body. Check these subresponses individually. A successful outer call does not guarantee that every subrequest succeeded.
Chaining subrequests with reference IDs
A later subrequest can use a previous result with @{referenceId.field}. In the example, @{newAccount.id} resolves to the ID returned by the Account creation. Reference IDs must be unique, and dependent subrequests must appear after the subrequest that produces their values.
Exercise
Which expression reads the ID returned by a subrequest whose referenceId is newAccount?
Show answer
@{newAccount.id}