Sub topic 4
Chaining Subrequests with Reference IDs
This chapter assumes you can send an authenticated request to the Salesforce REST API and read its JSON responses. It also assumes you know the basic shape of a composite request: a compositeRequest array of subrequests, each with a method, a url, and an optional body. The chapter covers how one subrequest uses the result of an earlier one, and what goes wrong when it can't.
What a reference ID is
Every subrequest in a composite request carries a referenceId. It is a label you choose, and it does two jobs:
- It tags the matching entry in
compositeResponse, so you can find the result of each subrequest by name instead of by position. - It lets later subrequests read values from that result.
The second job is what makes the Composite resource more than a batching trick. Without it, creating a Contact under a new Account takes two calls, because the Contact needs the Account's ID and that ID doesn't exist until the first call finishes. With a reference, Salesforce makes the substitution itself, in the same request.
Reference IDs must be unique within one composite request. Use short, descriptive names such as newAccount or findContact. Letters, digits, and underscores are the safest choice.
The reference syntax
A reference is written @{referenceId.path}. The referenceId names an earlier subrequest, and the path selects a value in that subrequest's response body. Salesforce evaluates the reference on the server and substitutes the value before running the subrequest that contains it.
| Reference | What it reads |
|---|---|
| `@{newAccount.id}` | The `id` field of a create response |
| `@{readAccount.Name}` | A field of a record returned by a GET |
| `@{findAccount.records[0].Id}` | The `Id` of the first record in a query result |
| `@{findAccount.totalSize}` | The `totalSize` value of a query result |
The path uses dot notation for fields and square brackets with a zero-based index for arrays. It reads the response body only. It does not read headers or the status code.
A worked example
The request below creates an Account, creates a Contact that belongs to it, and reads the Contact back. The second subrequest uses @{newAccount.id} in its body, and the third uses @{newContact.id} in its URL.
{
"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"
}
]
}Save it as composite.json and send it to the /composite endpoint:
curl -X POST "$INSTANCE_URL/services/data/v60.0/composite" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d @composite.jsonSalesforce runs the subrequests in the order you listed them. The create response for the Account looks like {"id":"001...","success":true,"errors":[]}. When the Contact subrequest runs, Salesforce replaces @{newAccount.id} with 001.... The diagram shows the flow of values.
Referencing query results
References also work with query responses. This is how you chain a lookup into a later write:
{
"allOrNone": true,
"compositeRequest": [
{
"method": "GET",
"url": "/services/data/v60.0/query?q=SELECT+Id+FROM+Account+WHERE+Name%3D%27Acme+Corp%27+LIMIT+1",
"referenceId": "findAccount"
},
{
"method": "POST",
"url": "/services/data/v60.0/sobjects/Contact",
"referenceId": "newContact",
"body": { "LastName": "Silva", "AccountId": "@{findAccount.records[0].Id}" }
}
]
}A query response has this shape: {"totalSize":1,"done":true,"records":[{"attributes":{...},"Id":"001..."}]}. The path records[0].Id therefore reaches the first row's Id.
The query returns successfully even when it finds nothing. In that case records is an empty array, records[0].Id has no value, and the Contact subrequest fails. A successful lookup does not guarantee a usable reference.
Where references can go
A reference is text substitution on the server. It can appear in two places:
- The
urlof a later subrequest, for example/sobjects/Contact/@{newContact.id}. - The
bodyof a later subrequest, as the value of a field.
Some rules apply to every reference:
- Order matters. The referenced subrequest must come earlier in the array. A reference to a later subrequest cannot be resolved.
- The referenced subrequest must have produced a body. A successful PATCH or DELETE returns status 204 with no body, so there is nothing to read from it. If you need data from an update, follow it with a GET.
- Only names in the same request exist. You cannot reference a result from a previous HTTP call. Pass those values in as ordinary literals.
When the referenced subrequest fails
A reference only works if the subrequest it points to succeeded. What happens when it didn't depends on allOrNone.
With "allOrNone": true, any failure rolls back the whole request. The failing subrequest reports its own error. Subrequests that didn't run, or whose work was rolled back, return status 400 with the error code PROCESSING_HALTED. The dependent subrequests therefore never execute against a missing value.
With "allOrNone": false, each subrequest is committed on its own. If newAccount fails, the Contact subrequest still runs, but its reference can't be resolved. It returns a 400 error and you must read the message to learn why. Subrequests that don't depend on the failed one are unaffected and can still succeed.
The next chapters cover allOrNone and partial failure in full. For this chapter, remember that chained subrequests only make sense when you handle the failure case. A dependent record can't be created without its parent.
Reading chained results in code
The outer HTTP call can return 200 while individual subrequests fail, so a script has to inspect each entry. This script sends the Account-and-Contact chain and checks the Contact result by its referenceId:
import os
import requests
base = os.environ["INSTANCE_URL"]
headers = {"Authorization": "Bearer " + os.environ["ACCESS_TOKEN"]}
api = "/services/data/v60.0"
payload = {
"allOrNone": True,
"compositeRequest": [
{
"method": "POST",
"url": api + "/sobjects/Account",
"referenceId": "newAccount",
"body": {"Name": "Acme Corp"},
},
{
"method": "POST",
"url": api + "/sobjects/Contact",
"referenceId": "newContact",
"body": {"LastName": "Rivera", "AccountId": "@{newAccount.id}"},
},
],
}
resp = requests.post(base + api + "/composite", headers=headers, json=payload, timeout=30)
resp.raise_for_status()
results = {sub["referenceId"]: sub for sub in resp.json()["compositeResponse"]}
contact = results["newContact"]
if contact["httpStatusCode"] == 201:
print("Created contact", contact["body"]["id"])
else:
print("Contact failed:", contact["httpStatusCode"], contact["body"])Indexing the response by referenceId means the code does not depend on array position, which is the main reason to choose meaningful names. A successful create returns status 201. A subrequest that was halted returns 400, and its body is a list of error objects.
Common errors
- Duplicate
referenceIdvalues. Two subrequests with the same label are ambiguous, and the request is rejected. Give each one a distinct name. - A reference to a name that doesn't exist. A typo such as
@{newAcount.id}cannot be resolved. Compare the name inside@{...}with thereferenceIdit is meant to point at. - A reference to a later subrequest. Move the referenced subrequest above the one that uses it.
- Wrong path. For a create response the field is lowercase
id. For a GET on a record, the field isIdor whatever the API name is. Query results needrecords[n]first. Look at an actual response body before writing the path. - Reading a 204 response. PATCH and DELETE leave nothing to reference.
- An empty query result.
records[0]fails when the query matched no rows. Plan for this case, or use an ID you already know. - Assuming the outer 200 means success. Always check each
httpStatusCode.
Limits on chaining
A reference does not add an extra call. Each chained subrequest still counts against the per-request subrequest cap, which the limits chapter covers. Long chains of dependent subrequests grow quickly, so check the cap before designing a deep chain.
Exercise
A composite request has a PATCH subrequest with referenceId updateAccount, followed by a POST subrequest whose body contains "Description": "@{updateAccount.Name}". Why does the POST fail, and what would you change?
Show answer
A successful PATCH returns status 204 with no response body, so there is no Name value to read. Add a GET subrequest after the PATCH (for example with referenceId readAccount) and reference @{readAccount.Name} in the POST. Or skip the reference and send the name as a literal if you already know it.
Exercise
You send a composite request with allOrNone set to true. Subrequest 1 (newAccount) fails with a validation error. Subrequest 2 (newContact) uses @{newAccount.id}. What does the Contact subrequest return, and was a Contact created?
Show answer
The Contact subrequest returns status 400 with the error code PROCESSING_HALTED, because it was not run to completion after the failure. No Contact was created, since allOrNone true rolls back the whole request. The error detail for the root cause appears in the newAccount entry of compositeResponse.
Exercise
Write the reference that reads the Id of the second record returned by a query subrequest named topAccounts.
Show answer
@{topAccounts.records[1].Id}. Array indexes start at 0, so the second record is index 1.