Sub topic 10
Independent subrequests with Composite Batch
This chapter assumes you can already send an authenticated request to the Salesforce REST API and read a standard /composite response. It covers the /composite/batch resource, which bundles up to 25 unrelated requests into one HTTP call. You will see how it differs from /composite, how to read its response, and when it is the wrong tool.
What Composite Batch does
Composite Batch executes a list of subrequests in a single HTTP call. Unlike the Composite resource from earlier chapters, the subrequests have no relationship to each other:
- A subrequest cannot read the result of another subrequest. There is no
referenceIdand no@{...}syntax. - There is no
allOrNoneflag. Each subrequest is its own transaction and commits or fails on its own. - Subrequests run one after another in the order you list them, but nothing carries over from one to the next.
Use it when you want to save round trips for work that is logically separate. Typical cases are fetching a describe for one object, running a query, and creating an unrelated record, all at the start of a screen load or sync job.
The endpoint is:
POST /services/data/v60.0/composite/batchRequest anatomy
The body is a JSON object with a batchRequests array and an optional haltOnError flag.
{
"batchRequests": [
{
"method": "GET",
"url": "v60.0/sobjects/Account/describe"
},
{
"method": "POST",
"url": "v60.0/sobjects/Account",
"richInput": { "Name": "Batch Account" }
}
],
"haltOnError": false
}Three details differ from /composite:
| Aspect | Composite (`/composite`) | Composite Batch (`/composite/batch`) |
|---|---|---|
| Array name | `compositeRequest` | `batchRequests` |
| Request data | `body` | `richInput` |
| `url` format | Starts with `/services/data/vXX.X/...` | Starts with the version, such as `v60.0/...` |
| Cross-references | `@{referenceId.field}` | Not supported |
| Rollback control | `allOrNone` | None. Only `haltOnError` |
| Subrequest identifier | `referenceId` (required, unique) | None. Identified by position |
Each subrequest accepts these properties:
method:GET,POST,PATCH,PUT, orDELETE.url: the relative resource path, beginning with the API version.richInput: the JSON body forPOST,PATCH, andPUT.binaryPartNameandbinaryPartNameAlias: used only when a subrequest uploads a binary file as a multipart request.
The most common mistake when moving from /composite is copying body and a full /services/data/... URL into a batch request. Use richInput and the short version-first URL instead.
Sending the request
Save the JSON above as batch.json and send it with the same authentication you use for any REST call.
curl -X POST "$INSTANCE_URL/services/data/v60.0/composite/batch" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d @batch.jsonThe same API version should appear in the endpoint and in the subrequest URLs, unless you have a specific reason to mix them.
How execution flows
The order is a processing order, not a dependency chain. If subrequest 2 creates an Account, subrequest 3 cannot use its ID. If you need that, use /composite with a reference ID.
Reading the response
The response has a top-level hasErrors flag and a results array. The array has one entry per subrequest, in the same order as the request.
{
"hasErrors": true,
"results": [
{
"statusCode": 200,
"result": { "name": "Account", "label": "Account" }
},
{
"statusCode": 400,
"result": [
{
"message": "Required fields are missing: [Name]",
"errorCode": "REQUIRED_FIELD_MISSING",
"fields": ["Name"]
}
]
}
]
}Notes on reading it:
- The outer HTTP status is normally
200even when individual subrequests fail. Always checkhasErrorsor eachstatusCode. - A successful subrequest has a
resultshaped like the response of the matching standalone call. A failed one usually hasresultas an array of error objects witherrorCodeandmessage. - Entries have no identifier. You match a result to its request by index, so keep your own list of what you sent.
hasErrors: falsemeans every subrequest returned a success status. It does not mean the work was meaningful, so inspect results that you depend on.
A defensive Python client looks like this:
import os
import requests
base = os.environ['INSTANCE_URL']
headers = {'Authorization': 'Bearer ' + os.environ['ACCESS_TOKEN']}
requests_list = [
{'method': 'GET', 'url': 'v60.0/limits'},
{'method': 'GET', 'url': 'v60.0/query?q=SELECT+Id,Name+FROM+Account+LIMIT+3'},
{'method': 'POST', 'url': 'v60.0/sobjects/Account', 'richInput': {'Name': 'Batch Account'}},
]
payload = {'batchRequests': requests_list, 'haltOnError': False}
resp = requests.post(
base + '/services/data/v60.0/composite/batch',
headers=headers,
json=payload,
timeout=30,
)
resp.raise_for_status()
body = resp.json()
for index, item in enumerate(body['results']):
sent = requests_list[index]
status = item['statusCode']
print(index, sent['method'], sent['url'], status)
if status >= 400:
for error in item['result']:
print(' ', error['errorCode'], error['message'])raise_for_status() only catches problems with the whole call, such as an expired token or a malformed body. The loop is what catches subrequest failures.
haltOnError
haltOnError controls what happens after a failure. It defaults to false.
false: every subrequest runs, whatever happens to the others. Use this when the subrequests are truly unrelated, such as several reads.true: if a subrequest returns an error status (4xx or 5xx), Salesforce stops processing. The remaining subrequests are not run and come back with status412(Precondition Failed).
Setting haltOnError to true does not roll anything back. Subrequests that finished before the failure stay committed. Suppose you send a POST that creates an Account, then a POST that fails validation, then a DELETE. With haltOnError: true, the Account stays, the second request returns an error, and the DELETE returns 412 and never runs.
A 412 entry in the results means "not attempted", not "attempted and rejected". Treat those entries as work you still need to retry.
Limits and constraints
- A batch holds at most 25 subrequests. A larger list is rejected, so split it into chunks of 25.
- At most 5 of those 25 may be
queryorqueryAlloperations. Check the current limits in the REST API Developer Guide, since these numbers can change between releases. - The batch counts as a single API call against your daily REST API limit, while each subrequest still runs its normal governor-limited work. Batching saves round trips and API calls, but it does not make heavy operations cheaper on the server.
- Subrequests run serially. A batch of 25 slow queries takes about the sum of their times, not the longest one.
- Response size matters. A batch with several large describes or queries can produce a very large single response, so keep reads narrow with
fields=andLIMIT.
When Composite Batch is the right choice
Choose Composite Batch when all of these are true:
- The subrequests do not need each other's output.
- A failure in one should not undo the others.
- You mainly want fewer round trips.
Good examples are loading metadata for several objects at once, running a handful of small independent queries, or applying a few unrelated updates.
Choose something else in these cases:
- Later requests depend on earlier IDs: use
/compositewith@{referenceId.field}. - You are creating the same type of record in volume: use sObject Collections, which handles up to 200 records of the same operation in one subrequest.
- You are creating a parent and its children from one nested payload: use sObject Tree.
- You need rollback across a set of writes: use
/compositewithallOrNone: trueor Composite Graph.
Common errors
INVALID_FIELDor missing data on POST. The body was sent asbodyinstead ofrichInput, so Salesforce received no fields.NOT_FOUNDon a subrequest URL. The URL began with/services/data/v60.0/.... In batch, begin withv60.0/....- A rejected request with more than 25 entries. Chunk the list.
- Using
@{...}references. The text is passed through literally and will fail as an invalid ID or value. Batch cannot chain results. - Assuming rollback. An earlier success remains committed after a later failure, with either
haltOnErrorsetting. - Mismatched results. Results are positional. If you build the request list dynamically, store it alongside the response before you zip them together.
Exercise
You send a Composite Batch request with haltOnError: true and four subrequests: (1) a POST that creates an Account, (2) a GET that reads Account describe, (3) a POST that creates a Contact with no LastName, (4) a DELETE of an unrelated Task. What is the outcome of each subrequest, and is the Account from subrequest 1 still in the org?
Show answer
Subrequests 1 and 2 succeed (for example 201 and 200). Subrequest 3 fails with a 400 error (REQUIREDFIELDMISSING). Because haltOnError is true, subrequest 4 is not executed and returns 412. The Account from subrequest 1 is still in the org, because Composite Batch does not roll back earlier subrequests. The top-level HTTP status is still 200, and hasErrors is true.
Exercise
A teammate converts a working /composite request to /composite/batch by renaming compositeRequest to batchRequests. The second subrequest, a Contact POST that uses "AccountId": "@{newAccount.id}", now fails. Name two reasons it fails and what to do instead.
Show answer
First, batch subrequests use richInput, not body, so the Contact fields are never read (and the URLs must start with the version, not /services/data/). Second, Composite Batch does not support reference IDs, so the @{newAccount.id} text is not resolved and is treated as a literal value. Because the Contact depends on the Account, the work should stay in /composite with referenceId values, or use sObject Tree or Composite Graph.