Sub topic 5
Reading the composite response
This chapter assumes you can already send a composite request and know basic HTTP status codes and JSON. Here you will learn how to read what comes back. The main point is that a composite call can return HTTP 200 while some or all of its subrequests failed. Your code has to read the result of every subrequest.
Two levels of status
A composite call has two layers of results:
- The outer HTTP response is the status of the call to
/compositeitself. - Each entry in
compositeResponseis the status of one subrequest.
Salesforce returns HTTP 200 for the outer call whenever it could parse the request and run it. That holds even if every subrequest failed. The outer call fails only when something is wrong with the request as a whole:
| Outer status | Typical cause |
|---|---|
| 200 | The request was understood. Subrequests may still have failed. |
| 400 | The JSON is malformed, or a required property such as `compositeRequest` is missing. |
| 401 | The access token is expired or invalid. |
| 403 | The user lacks API access, or a request limit was exceeded. |
A client that checks only the outer status will report success when records were never saved. In Python, raise_for_status() is a good first check, but it is not enough on its own.
Shape of the response
The response body has one top-level property, compositeResponse. It is an array with one object per subrequest, in the same order as the request. Each object has four properties:
referenceIdis the value you gave the subrequest. Use it to match results to requests instead of relying on position.httpStatusCodeis the status of that subrequest, such as 201 or 400.httpHeadersholds headers for that subrequest, such asLocationafter a create, orETagon some reads.bodyholds the payload. Its type depends on the operation and the outcome.
Here is the response for a request like the Account, Contact, and read-back example from earlier chapters, when everything succeeds:
{
"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"
}
]
}What each kind of body looks like
The body property changes shape with the operation. Your parser should branch on the status code first, then on the operation.
| Operation | Success status | Success `body` |
|---|---|---|
| POST (create) | 201 | `{ "id": "...", "success": true, "errors": [] }` |
| GET (record) | 200 | The record, with an `attributes` object and the fields you asked for |
| GET (query) | 200 | `totalSize`, `done`, and a `records` array |
| PATCH (update) | 204 | `null` |
| DELETE | 204 | `null` |
A 204 subrequest has no content, so do not call body["id"] on it. If you need the ID after an update, you already have it from the URL.
Failed subrequests return an array of error objects as the body, not an object. Each error has errorCode and message, and some also have a fields list:
[
{
"message": "Required fields are missing: [LastName]",
"errorCode": "REQUIRED_FIELD_MISSING",
"fields": ["LastName"]
}
]So the same property can be an object, an array, or null. A safe check is isinstance(body, list) for errors and a status-code range check for success.
Reading a failed response
Suppose the request used allOrNone: true and the Contact in the middle was missing LastName. The response looks like this:
{
"compositeResponse": [
{
"body": [
{
"errorCode": "PROCESSING_HALTED",
"message": "The transaction was rolled back since another operation in the same transaction failed."
}
],
"httpHeaders": {},
"httpStatusCode": 400,
"referenceId": "newAccount"
},
{
"body": [
{
"message": "Required fields are missing: [LastName]",
"errorCode": "REQUIRED_FIELD_MISSING",
"fields": ["LastName"]
}
],
"httpHeaders": {},
"httpStatusCode": 400,
"referenceId": "newContact"
},
{
"body": [
{
"errorCode": "PROCESSING_HALTED",
"message": "The transaction was rolled back since another operation in the same transaction failed."
}
],
"httpHeaders": {},
"httpStatusCode": 400,
"referenceId": "readContact"
}
]
}Notice three things:
- The Account subrequest would have succeeded on its own, yet it shows 400. Rollback turned it into a failure.
- Only one entry carries the real cause,
REQUIRED_FIELD_MISSING. The others are collateral. - The subrequest after the failure also reports
PROCESSING_HALTEDbecause it never ran.
The practical rule is that PROCESSING_HALTED means "this subrequest was affected by another one". It never names the root cause. When you log or surface errors, find the entries whose errorCode is something else.
A reusable parser
The script below posts a request and sorts the results into succeeded, root-cause failures, and halted subrequests. It indexes results by referenceId, so later code can look up results["newContact"] without counting positions.
import os
import requests
HALTED = "PROCESSING_HALTED"
def post_composite(payload):
base = os.environ["INSTANCE_URL"]
headers = {"Authorization": "Bearer " + os.environ["ACCESS_TOKEN"]}
resp = requests.post(
base + "/services/data/v60.0/composite",
headers=headers,
json=payload,
timeout=30,
)
resp.raise_for_status() # outer failures: 400, 401, 403, 5xx
return resp.json()["compositeResponse"]
def classify(sub_responses):
ok, failed, halted = {}, {}, {}
for sub in sub_responses:
ref = sub["referenceId"]
status = sub["httpStatusCode"]
body = sub["body"]
if 200 <= status < 300:
ok[ref] = body # may be None for 204
elif isinstance(body, list) and all(e.get("errorCode") == HALTED for e in body):
halted[ref] = body
else:
failed[ref] = body
return ok, failed, halted
if __name__ == "__main__":
payload = {
"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": {"AccountId": "@{newAccount.id}"}, # LastName is missing on purpose
},
],
}
ok, failed, halted = classify(post_composite(payload))
for ref, errors in failed.items():
for err in errors:
print("FAILED", ref, err["errorCode"], err["message"])
for ref in halted:
print("HALTED", ref)
for ref, body in ok.items():
print("OK", ref, body)With the missing LastName, the script prints one FAILED newContact REQUIRED_FIELD_MISSING ... line and one HALTED newAccount line. Nothing is saved, because allOrNone is true.
Reading results to drive later logic
You often need values from the response, such as the new record IDs. Read them from body["id"] on 201 entries:
ok, failed, halted = classify(post_composite(payload))
if failed:
raise RuntimeError(f"Composite failed: {failed}")
account_id = ok["newAccount"]["id"]Check failed before reading IDs. In an all-or-nothing request, an ID in a halted entry does not exist, because there is none, and ok will not contain that key.
Edge cases to handle
- Order is preserved, but do not depend on it. Use
referenceIdas the key. Duplicate reference IDs are rejected, so the key is unique within one request. - Dependent subrequests when
allOrNoneisfalse. A subrequest that references a failed one cannot resolve its@{...}value, so it fails too. Independent subrequests still run and keep their results. Treat any 4xx entry as a failure and read itserrorCodeinstead of assuming a specific message. - Query results can be paged. A GET query subrequest returns
done: falseand anextRecordsUrlwhen more rows exist. Following that link takes a separate call. - Validation and Apex errors arrive as normal subrequest errors. A trigger or validation rule failure looks like any other 400 entry, with codes such as
FIELD_CUSTOM_VALIDATION_EXCEPTION. - Error
fieldscan be empty. Not every error is tied to a field, so use.get("fields", []).
Summary of rules
- Check the outer status first, then every subrequest.
- Match results by
referenceId. - Branch on
httpStatusCode, then on the body shape: object, array, ornull. - Treat
PROCESSING_HALTEDas a symptom and look for the other error code as the cause.
Exercise
A composite request with allOrNone set to true returns HTTP 200. The compositeResponse has three entries: the first is 400 with PROCESSINGHALTED, the second is 400 with REQUIREDFIELDMISSING, and the third is 400 with PROCESSINGHALTED. Was any record saved, and which entry should you report as the cause?
Show answer
No record was saved. Because allOrNone is true, the failure of the second subrequest rolled back the whole transaction, and the first entry shows PROCESSINGHALTED even though it would have succeeded alone. Report the second entry, since REQUIREDFIELD_MISSING is the root cause. The outer 200 only means Salesforce processed the request.
Exercise
Why does the Python function classify() check isinstance(body, list) before reading error codes, and what would break if it called body["id"] on every subrequest?
Show answer
Failed subrequests return a list of error objects, successful creates return an object with an id, and updates and deletes return a 204 with a null body. Calling body["id"] on every entry would raise a TypeError on lists and on None, and a KeyError on GET responses that did not request the Id field. Checking the status range and body type first avoids those errors.