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 a single call. It assumes you can send authenticated REST requests (OAuth access token and instance URL), read JSON, and know basic Salesforce object relationships such as Account to Contact.
What sObject Tree does
sObject Tree is a REST resource that creates one or more record trees. A tree is a root record with nested child records, and those children can have children of their own. You send one JSON body, and Salesforce creates every record and links the children to their parent for you.
The endpoint takes the root object type in the path:
POST /services/data/v60.0/composite/tree/AccountUnlike a general composite request, you do not write @{referenceId.id} references. The nesting in the JSON expresses the parent-child link.
Anatomy of a tree request
Each record needs an attributes object with its type and a referenceId. The referenceId is a label you choose, and it must be unique within the request. Children go inside a property named after the child relationship name, wrapped in a records array. For Contacts under an Account, that name is Contacts.
{
"records": [
{
"attributes": { "type": "Account", "referenceId": "acct1" },
"Name": "Tree Account",
"Contacts": {
"records": [
{
"attributes": { "type": "Contact", "referenceId": "contact1" },
"LastName": "Nguyen"
}
]
}
}
]
}Save this as tree.json and send it:
curl -X POST "$INSTANCE_URL/services/data/v60.0/composite/tree/Account" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d @tree.jsonReading the response
On success, the response lists each referenceId with the new record ID:
{
"hasErrors": false,
"results": [
{ "referenceId": "acct1", "id": "001..." },
{ "referenceId": "contact1", "id": "003..." }
]
}Match your own records to new IDs through referenceId. This is why each one must be unique.
All or nothing
The tree call is transactional. If any record in the request fails, nothing is saved. In that case hasErrors is true, and each error entry names the referenceId that failed along with a status code, message, and fields. Failed requests usually return HTTP 400. Check hasErrors before you trust the results array.
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,
)
body = resp.json()
if body.get('hasErrors'):
for item in body['results']:
for err in item.get('errors', []):
print(item['referenceId'], err['statusCode'], err['message'])
else:
for item in body['results']:
print(item['referenceId'], item['id'])Limits and common errors
Check the current REST API Developer Guide for exact numbers, since limits can change between versions. The documented constraints are:
- A request can hold up to 200 records in total, counting parents and children.
- A tree can be at most five levels deep, from root to deepest child.
- A request can contain records of only one root type, though trees may include several child object types.
- Every
referenceIdmust be unique within the request.
Common mistakes:
- Using the child object name instead of the relationship name. Use
Contacts, notContact. Custom relationships end in__r. - Omitting
attributes.typeon a nested record. - Reusing a
referenceId. - Expecting partial success. A single bad record rolls back the whole tree.
When to choose it
Use sObject Tree when you are creating a new hierarchy from scratch and want the simplest body. If you need to mix operations, read results, or reuse a generated ID in several places, use a general composite request. If you need many unrelated records without nesting, sObject Collections fits better.
Exercise
You send a tree request with one Account and three Contacts. The third Contact is missing the required LastName field. What is the outcome, and how do you find which record failed?
Show answer
Nothing is saved, because sObject Tree is all or nothing. The response has hasErrors set to true, and the error entry for the failing record carries the referenceId of the third Contact with a status code and message, so you can identify it and fix it.
Exercise
What property name holds the children of an Account in a tree request, and what structure does it contain?
Show answer
The child relationship name, Contacts for Contact records. It holds an object with a records array, and each element needs an attributes object with type and a unique referenceId.