Sub topic 3
Anatomy of a composite request
This chapter assumes you can send an authenticated REST call to a Salesforce org, with an OAuth access token and the instance URL. It also assumes you know HTTP methods, status codes, JSON bodies, and the sObject endpoints such as /sobjects/Account. Here you will learn what a composite request body contains and how Salesforce processes it. Chaining results with reference IDs, rollback behavior, and failure handling each get their own chapter, so this one only introduces them.
The endpoint and the envelope
The Composite resource accepts one POST request:
POST /services/data/v60.0/compositeThe path includes an API version, v60.0 in these examples. The request is authenticated once, with the usual Authorization: Bearer header. The body is a JSON object, the envelope, that carries a list of ordinary REST calls. Each of those calls is a subrequest.
The envelope has three top-level properties:
| Property | Required | Meaning |
|---|---|---|
| `compositeRequest` | Yes | An ordered array of subrequests. |
| `allOrNone` | No, defaults to `false` | If `true`, any failed subrequest rolls back the whole request. |
| `collateSubrequests` | No, defaults to `false` | If `true`, Salesforce may process independent subrequests together as a group to improve performance. |
You can leave out allOrNone and collateSubrequests and still send a valid request. Most requests set allOrNone on purpose, because the default means that subrequests that succeed stay saved even when others fail.
Anatomy of a subrequest
Each element of compositeRequest describes one REST call. It has these properties:
| Property | Required | Meaning |
|---|---|---|
| `method` | Yes | The HTTP method: `GET`, `POST`, `PATCH`, or `DELETE`. |
| `url` | Yes | The full resource path, starting with `/services/data/vXX.X/`. |
| `referenceId` | Yes | A label that is unique within this request. |
| `body` | For `POST` and `PATCH` | The JSON payload, the same one you would send to the standalone endpoint. |
| `httpHeaders` | No | Headers for this subrequest only, such as `Sforce-Auto-Assign`. |
Three details cause most beginner mistakes.
- The
urlis a path, not a full URL. Do not include the instance host. Do include the version segment, even though the outer call already has one. - Reads put their parameters in the query string of the
url, as in?fields=Id,LastName. AGEThas nobody. - The
referenceIdis your name for the subrequest. It becomes the key you use to find its result in the response, and later subrequests use it to refer to earlier results.
A complete request
This request creates an Account, creates a Contact that belongs to it, and reads the Contact back.
{
"allOrNone": true,
"compositeRequest": [
{
"method": "POST",
"url": "/services/data/v60.0/sobjects/Account",
"referenceId": "newAccount",
"body": { "Name": "Acme Corp" }
},
{
"method": "POST",
"url": "/services/data/v60.0/sobjects/Contact",
"referenceId": "newContact",
"body": { "LastName": "Rivera", "AccountId": "@{newAccount.id}" }
},
{
"method": "GET",
"url": "/services/data/v60.0/sobjects/Contact/@{newContact.id}?fields=Id,LastName,AccountId",
"referenceId": "readContact"
}
]
}The text @{newAccount.id} is a reference. Before Salesforce runs the second subrequest, it replaces the reference with the id returned by the subrequest labeled newAccount. The third subrequest does the same with newContact. You never see the new Account ID on the client side, so the whole chain needs one round trip instead of three. The next chapter covers the reference syntax in full.
Save the body as composite.json and send it:
curl -X POST "$INSTANCE_URL/services/data/v60.0/composite" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d @composite.jsonWhat Salesforce does with it
The processing model has four rules.
- Subrequests run in the order you list them. A subrequest can only reference results from subrequests above it. A reference to a later one fails.
- Each subrequest behaves like its standalone call. Validation rules, triggers, and field-level security all apply as usual. The same
bodythat works forPOST /sobjects/Accountworks here. - The whole envelope counts as one API call against your org's API request limits, however many subrequests it holds. This saving is the main reason to use the resource. Governor limits inside each operation, such as trigger limits, still apply per subrequest.
- The outer call returns quickly with its own status. A
200on the outer call means Salesforce processed the envelope. It does not mean every subrequest worked.
The shape of the response
The response body has a single property, compositeResponse. It is an array with one entry for each subrequest, in the same order as the request. For the request above, a successful response looks like this:
{
"compositeResponse": [
{
"body": { "id": "001xx000003DGb2AAG", "success": true, "errors": [] },
"httpHeaders": {
"Location": "/services/data/v60.0/sobjects/Account/001xx000003DGb2AAG"
},
"httpStatusCode": 201,
"referenceId": "newAccount"
},
{
"body": { "id": "003xx000004TmiQAAS", "success": true, "errors": [] },
"httpHeaders": {
"Location": "/services/data/v60.0/sobjects/Contact/003xx000004TmiQAAS"
},
"httpStatusCode": 201,
"referenceId": "newContact"
},
{
"body": {
"attributes": {
"type": "Contact",
"url": "/services/data/v60.0/sobjects/Contact/003xx000004TmiQAAS"
},
"Id": "003xx000004TmiQAAS",
"LastName": "Rivera",
"AccountId": "001xx000003DGb2AAG"
},
"httpHeaders": {},
"httpStatusCode": 200,
"referenceId": "readContact"
}
]
}Each entry has four properties.
referenceIdechoes the label you chose, so you can match results by name instead of by position.httpStatusCodeis the status the standalone call would have returned:201for a create,200for a read,204for a successful update or delete.bodyis the payload the standalone call would have returned. For a failure it is an array of error objects instead.httpHeadersholds response headers for that subrequest, such asLocationon a create.
Checking every subrequest from code
A short client loop makes the per-subrequest check routine. This script sends a one-subrequest request and prints each subrequest's label and status. It expects INSTANCE_URL and ACCESS_TOKEN in the environment.
import os
import requests
base = os.environ['INSTANCE_URL']
headers = {'Authorization': 'Bearer ' + os.environ['ACCESS_TOKEN']}
payload = {
'allOrNone': True,
'compositeRequest': [
{
'method': 'POST',
'url': '/services/data/v60.0/sobjects/Account',
'referenceId': 'newAccount',
'body': {'Name': 'Acme Corp'},
}
],
}
resp = requests.post(base + '/services/data/v60.0/composite', headers=headers, json=payload, timeout=30)
resp.raise_for_status()
for sub in resp.json()['compositeResponse']:
print(sub['referenceId'], sub['httpStatusCode'])raise_for_status() only catches problems with the outer call, such as an expired token or a malformed envelope. Per-subrequest failures appear only in the loop. Later chapters build on this loop to handle errors properly.
Common mistakes
- Duplicate
referenceIdvalues. Each label must be unique across the request. Reusing one makes the request invalid, and references become ambiguous. - Leaving the version or the leading slash out of
url. Use/services/data/v60.0/sobjects/Account, notsobjects/Account. Composite Batch uses a different convention, with no leading slash and a bare version such asv60.0/.... Do not mix the two styles. - Referencing a later subrequest. Order matters. If the Contact needs the Account ID, the Account
POSTmust come first. - Assuming
allOrNoneis on. It is off by default, so a failed subrequest does not undo earlier successful ones unless you set the flag. - Putting a body on a
GETorDELETE. These methods take their parameters from the URL. - Exceeding the subrequest cap. A single request holds at most 25 subrequests. The limits chapter covers this and the stricter cap on queries.
Summary of the model
A composite request is an ordered list of ordinary REST calls inside one authenticated POST. Each call has a method, a path, a unique label, and an optional body. Salesforce runs the calls in order, substitutes earlier results into later calls, and returns one array of per-call results in the same order. The outer status describes the envelope, and the inner statuses describe the work.
Exercise
A composite request contains a POST that creates an Account with referenceId "acct" and a second subrequest whose url is "sobjects/Contact". The outer call returns HTTP 200, but the Contact was not created. Name two things you should check, and explain why the 200 does not settle the matter.
Show answer
First, check the Contact subrequest's own entry in compositeResponse for its httpStatusCode and error body. The outer 200 only means Salesforce processed the envelope, not that each subrequest succeeded. Second, check the url. It must be a full path that starts with a slash and includes the version, such as "/services/data/v60.0/sobjects/Contact". A relative path like "sobjects/Contact" is invalid in a composite request. Also note that with allOrNone unset, the Account may have been saved even though the Contact failed.