Sub topic 13
Choosing the right composite resource
This chapter assumes you can build a /composite request, chain subrequests with @{referenceId.field}, and read a compositeResponse. It also assumes you know what allOrNone does and the 25-subrequest limit. Here you will compare the five resources side by side and pick one for a given task.
The five resources at a glance
All five let you send several operations in one HTTP call, and a call counts once against your API request limit. They differ in four ways:
- Whether subrequests can use each other's results.
- Whether the operations commit together or separately.
- How many operations fit in one call.
- What kind of operations are allowed.
| Resource | Endpoint | Can reference earlier results | Transaction behavior | Typical size limit |
|---|---|---|---|---|
| Composite | `/composite` | Yes, `@{referenceId.field}` | Controlled by `allOrNone` | 25 subrequests |
| Composite Batch | `/composite/batch` | No | Each subrequest is independent | 25 subrequests |
| sObject Tree | `/composite/tree/{sObject}` | Within the tree, by nesting | All or nothing | 200 records |
| sObject Collections | `/composite/sobjects` | No | Controlled by `allOrNone` (default `false`) | 200 records |
| Composite Graph | `/composite/graph` | Yes, inside one graph | One transaction per graph | Higher than Composite |
Treat the limits as a guide and confirm them against the API version you target. They are the figures most likely to change between releases.
Decision questions
Work through these questions in order. Most tasks are settled by the first or second one.
1. Do later operations need data from earlier ones?
If yes, you need a resource that supports references: Composite, sObject Tree, or Composite Graph. If every operation stands alone, Composite Batch or sObject Collections is simpler.
Composite Batch cannot pass results between subrequests. A batch that creates an Account and then a Contact needs the Account's ID before it runs, and it does not have that ID.
2. Must the operations succeed or fail together?
Composite with allOrNone: true rolls back everything if one subrequest fails. Composite Batch has no such guarantee. It offers only haltOnError, which stops later subrequests after a failure but does not undo the ones that already committed.
For all-or-nothing creation of a parent and its children, sObject Tree gives you that behavior without any extra flag.
3. Is it the same operation on many records?
If you are inserting, updating, deleting, or retrieving up to 200 records of one kind, use sObject Collections. It sends a single array in one subrequest slot. A Composite request spends one of its 25 slots on every record, so it can touch at most 25 records.
4. Is the work larger than one Composite request, and does it split into groups?
Composite Graph fits when you have several independent groups of dependent operations. Each group is a graph with its own reference IDs, and each graph commits or rolls back on its own. One failing graph does not undo the others.
Choosing by scenario
Create an account, a contact, and an opportunity linked together
Use Composite with allOrNone: true. The contact and opportunity each need the new Account ID, and a partial result (an Account with no contacts) is usually unwanted.
If the structure is strictly parent and child, such as one Account with several Contacts, sObject Tree is shorter. You nest the children inside the parent and skip the reference syntax:
{
"records": [
{
"attributes": { "type": "Account", "referenceId": "acct1" },
"Name": "Tree Account",
"Contacts": {
"records": [
{
"attributes": { "type": "Contact", "referenceId": "contact1" },
"LastName": "Nguyen"
}
]
}
}
]
}Post this to /services/data/v60.0/composite/tree/Account. Tree cannot read records back or mix in other operations, so use Composite when you also need a follow-up GET.
Update 150 accounts with the same field change
Use sObject Collections. Send one PATCH to /composite/sobjects with a records array. Each record needs its Id and an attributes.type:
{
"allOrNone": false,
"records": [
{ "attributes": { "type": "Account" }, "Id": "001000000000001AAA", "Rating": "Hot" },
{ "attributes": { "type": "Account" }, "Id": "001000000000002AAA", "Rating": "Hot" }
]
}With allOrNone set to false, records that pass validation are saved and the failures are reported per record. Set it to true if the batch is meaningless unless every record changes.
Run unrelated reads and writes in one trip
Use Composite Batch. A common case is a dashboard that fetches a describe result, a few record lookups, and a limits check. None of them depend on each other, so a failure in one should not block the rest:
{
"batchRequests": [
{ "method": "GET", "url": "v60.0/limits" },
{ "method": "GET", "url": "v60.0/sobjects/Account/describe" }
],
"haltOnError": false
}Note the URL style. Batch subrequest URLs start with the version (v60.0/...), with no leading /services/data/. Composite subrequests use the full path. The same body works in neither place if you mix them up. Batch also takes its data under richInput, where Composite uses body.
Load several independent parent-child groups in one call
Use Composite Graph. Each graph can hold its own chain of references, and a failure in one graph does not undo another. The following body creates one group:
{
"graphs": [
{
"graphId": "graph1",
"compositeRequest": [
{
"method": "POST",
"url": "/services/data/v60.0/sobjects/Account",
"referenceId": "acct",
"body": { "Name": "Graph Account" }
},
{
"method": "POST",
"url": "/services/data/v60.0/sobjects/Contact",
"referenceId": "cont",
"body": { "LastName": "Okafor", "AccountId": "@{acct.id}" }
}
]
}
]
}Adding a second graph with its own graphId makes it independent of the first. A reference ID in one graph cannot point into another.
A flow for the decision
Checking results differs by resource
Each resource reports success in a different shape, and code that handles one will misread another.
- Composite: the outer call returns HTTP 200 even when subrequests fail. Read
httpStatusCodeon every item incompositeResponse. A subrequest halted by an earlier failure underallOrNoneappears with status 400 and aPROCESSING_HALTEDerror code. - Composite Batch: the response has a top-level
hasErrorsboolean and aresultsarray in request order. Each item has its ownstatusCodeandresult. - sObject Tree: the response has a top-level
hasErrorsflag. On failure, theresultsentries carry thereferenceIdof the failing record, so your reference IDs are what let you find it. - sObject Collections: the response is an array, one entry per record, in request order, each with
successand anerrorslist. - Composite Graph: each graph in the response has its own
isSuccessfulflag and its owngraphResponse. Check every graph.
The Python below handles the Batch shape. It prints each subrequest's status and exits with an error if any failed:
import os
import sys
import requests
base = os.environ['INSTANCE_URL']
headers = {'Authorization': 'Bearer ' + os.environ['ACCESS_TOKEN']}
payload = {
'batchRequests': [
{'method': 'GET', 'url': 'v60.0/limits'},
{'method': 'GET', 'url': 'v60.0/sobjects/Account/describe'},
],
'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']):
print(index, item['statusCode'])
if body['hasErrors']:
sys.exit('at least one subrequest failed')Common mistakes
- Using Composite for 100 record inserts. You hit the 25-subrequest limit. Use sObject Collections.
- Using Composite Batch when later calls need an ID. The
@{...}syntax does not work there. Switch to Composite or Tree. - Assuming Batch is transactional. Each subrequest commits on its own. If one fails, earlier successes stay.
- Forgetting that Collections defaults to
allOrNone: false. A request that fails validation on some records still saves the rest unless you set the flag. - Treating HTTP 200 as success. For Composite, Batch, and Graph, the outer status reports only that Salesforce processed the envelope.
- Using Tree for non-hierarchical data. If two records are siblings that must reference each other, Tree cannot express it.
Exercises
Exercise
You must insert 180 Contact records that share no relationships with each other, and you want valid records saved even if a few fail validation. Which resource do you use, and which allOrNone value?
Show answer
sObject Collections, with allOrNone set to false. Collections accepts up to 200 records in one subrequest, so 180 fits. Composite would need 180 subrequest slots, and its limit is 25. With false, valid records are saved and the failures are reported per record in the response.
Exercise
A request creates an Account, then a Contact linked to it, then reads the Contact back. The business rule says no Account may exist without its Contact. Which resource and settings do you choose, and why not Composite Batch or sObject Tree?
Show answer
Composite with allOrNone: true. The Contact needs @{newAccount.id}, and the read-back needs the new Contact ID. Composite Batch cannot reference earlier results and does not roll back committed subrequests. sObject Tree can create the Account and Contact atomically, but it cannot perform the follow-up GET.
Exercise
You have 10 independent customer onboarding groups, each with an Account and Contacts linked to it. One failing group must not undo the other nine. Which resource fits?
Show answer
Composite Graph, with one graph per customer. Each graph has its own reference IDs and commits or rolls back on its own. Check isSuccessful on each graph in the response to find the failures.