Sub topic 11
Creating Record Hierarchies with sObject Tree
This chapter covers the sObject Tree resource, which creates a parent record and its children in one call. It assumes you can send authenticated REST requests with an OAuth access token and instance URL. It also assumes you know Salesforce relationships such as Account to Contact. If you have read the earlier chapters on composite requests and reference IDs, you will recognize the referenceId idea. Here it works differently.
What sObject Tree does
The sObject Tree resource inserts one or more root records together with nested child records. You send a JSON tree. Salesforce creates the parents first, fills in the lookup or master-detail field on each child, and creates the children.
The endpoint is:
POST /services/data/v60.0/composite/tree/{SObjectName}{SObjectName} is the type of the root records, for example Account. The resource only creates records. It cannot update, upsert, delete, or query.
Compare this with a standard composite request. There, you create the Account, read its ID through @{newAccount.id}, and put that ID in the Contact. With sObject Tree you skip that step. You describe the relationship by nesting, and Salesforce sets the foreign key.
Request structure
The request body has one top-level key, records. It is an array of root records. Each record has these parts:
- An
attributesobject withtype(the sObject API name) andreferenceId(a label you choose). - The field values for the record, written as ordinary JSON properties.
- Optionally, one or more child relationship names, each holding an object with its own
recordsarray.
The child key is the child relationship name, not the object name. For Account to Contact it is Contacts. For Account to Opportunity it is Opportunities. For a custom relationship it usually ends in __r. You can find the exact name in the childRelationships section of the parent's describe result.
Here is a request that creates one Account and one child Contact:
{
"records": [
{
"attributes": { "type": "Account", "referenceId": "acct1" },
"Name": "Tree Account",
"Contacts": {
"records": [
{
"attributes": { "type": "Contact", "referenceId": "contact1" },
"LastName": "Nguyen"
}
]
}
}
]
}Notice that the Contact has no AccountId. Salesforce fills it in because the Contact sits inside the Account's Contacts list.
Sending the request
Save the body as tree.json and send it with curl:
curl -X POST "$INSTANCE_URL/services/data/v60.0/composite/tree/Account" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d @tree.jsonThe same call in Python looks like this:
import os
import requests
base = os.environ['INSTANCE_URL']
headers = {'Authorization': 'Bearer ' + os.environ['ACCESS_TOKEN']}
payload = {
'records': [
{
'attributes': {'type': 'Account', 'referenceId': 'acct1'},
'Name': 'Tree Account',
'Contacts': {
'records': [
{
'attributes': {'type': 'Contact', 'referenceId': 'contact1'},
'LastName': 'Nguyen',
}
]
},
}
]
}
resp = requests.post(
base + '/services/data/v60.0/composite/tree/Account',
headers=headers,
json=payload,
timeout=30,
)
print(resp.status_code)
print(resp.json())Reading the response
On success, the HTTP status is 201 Created. The body reports hasErrors as false and lists a results entry for every record, in which each referenceId is paired with the new id:
{
"hasErrors": false,
"results": [
{ "referenceId": "acct1", "id": "001xx000003DGb2AAG" },
{ "referenceId": "contact1", "id": "003xx000004TmiQAAS" }
]
}Use the referenceId values to match results to the records you sent. Do not rely on the order of the results array.
The referenceId here is only a label for matching. You cannot write @{acct1.id} in another field of the same tree. Nesting is the only way to link records in this resource. If you need to reference IDs in arbitrary fields, use a regular composite request.
Failure behavior
An sObject Tree request is all or nothing. If any record in the request fails, the whole request is rolled back and nothing is saved. There is no allOrNone flag to change this, which sets it apart from sObject Collections.
When that happens, the status is 400 Bad Request and hasErrors is true. Each failing record appears in results with an errors array. The referenceId tells you which record caused the failure.
{
"hasErrors": true,
"results": [
{
"referenceId": "contact1",
"errors": [
{
"statusCode": "REQUIRED_FIELD_MISSING",
"message": "Required fields are missing: [LastName]",
"fields": ["LastName"]
}
]
}
]
}Records that were not at fault may not appear in this list, so do not expect one result per input record on failure. Check hasErrors first, then read the entries that contain errors.
A failure response from this resource has a different shape than a compositeResponse. Do not reuse code that reads compositeResponse and httpStatusCode for this endpoint. Here you read hasErrors and results.
Limits
The documented constraints for sObject Tree are:
| Constraint | Limit |
|---|---|
| Total records in one request | 200 |
| Records of different types in one request | Up to 5 types |
| Depth of the tree | 5 levels, counting the root as level 1 |
| Operations | Insert only |
The 200-record limit counts every record in the tree: roots, children, and grandchildren. A request with 10 Accounts, each with 20 Contacts, has 210 records and is rejected. The type limit counts distinct sObject types, so a tree of Account, Contact, Opportunity, and Case uses four.
Check the current limits for your API version in the Salesforce REST API Developer Guide, because these values can change.
Apart from these, the usual rules apply. Triggers, flows, validation rules, and duplicate rules run as they do for any other insert. A required field you leave out still fails the request. Each call also counts as one API request against your org's daily limit, no matter how many records it creates.
Common mistakes
- Using the object name as the child key. Writing
"Contact": {...}instead of"Contacts": {...}fails. Use the child relationship name fromdescribe. - Forgetting
attributeson a child. Every record at every level needsattributes.typeandattributes.referenceId. - Reusing a
referenceId. Each must be unique within the request, and each can be at most 80 characters, using only letters, numbers, and underscores in typical use. - Expecting partial success. One bad record rolls back the whole tree. If you want valid records to save even when others fail, use sObject Collections with
allOrNoneset tofalse. - Treating
201as the only success signal in code. Always checkhasErrorsin the body too. - Trying to link to an existing parent. To add Contacts to an Account that already exists, set
AccountIdin a Collections or standard composite request. Tree creates new roots only.
When to choose sObject Tree
Choose sObject Tree when you are inserting new records that form a hierarchy and you do not need to read the new IDs mid-request. A common case is importing an order and its line items, or an Account with its Contacts, from an external system.
Choose a regular composite request when later steps need values from earlier ones in fields other than the relationship, or when you mix creates with updates and queries. Choose sObject Collections when records are unrelated and you want partial success. The final chapter compares all five resources side by side.
Exercise
You send a tree with 1 Account, 150 Contacts, and 60 Opportunities to /composite/tree/Account. All fields are valid. What happens, and how would you change the request?
Show answer
The request is rejected because it holds 211 records, which is over the 200-record limit, and nothing is saved. Split the data into two or more requests, each with at most 200 records. Keep each Account together with its own children in the same request, so that the nesting still sets the foreign keys.
Exercise
A tree request returns HTTP 400 with hasErrors set to true, and one result for referenceId "contact1" lists REQUIREDFIELDMISSING. Were the Account and the other Contacts saved? Which resource would you use if you wanted the valid records saved anyway?
Show answer
No. sObject Tree rolls back the whole request when any record fails, so nothing was saved. To let valid records save, use sObject Collections with allOrNone set to false, setting AccountId yourself for any children whose parent already exists.
Exercise
Why does the Contact in the example tree have no AccountId field, and what key holds the Contacts inside the Account?
Show answer
Salesforce sets AccountId automatically from the nesting. The Contacts sit in the Account's child relationship key, "Contacts", inside an object with a "records" array.