Sub topic 13
Creating and updating many records with Composite sObjects
This chapter assumes you can already create, read, and update single records with POST, GET, and PATCH. It also assumes you can authenticate with a bearer token and read a Salesforce error body. Everything here builds on those calls.
Why single-record calls stop scaling
Creating one record takes one HTTP request. Loading 1,000 accounts that way takes 1,000 requests. Each request pays for network latency, TLS, and authentication, and each counts against your org's daily API request allocation.
The Composite sObjects resources address this. A single request carries up to 200 records for create, update, upsert, and delete. The whole batch counts as one API call, and the response lists one result per record.
The resource sits next to the single-record resource:
| Operation | Single record | Composite sObjects |
|---|---|---|
| Create | `POST /sobjects/Account` | `POST /composite/sobjects` |
| Update | `PATCH /sobjects/Account/{id}` | `PATCH /composite/sobjects` |
| Upsert | `PATCH /sobjects/Account/{extField}/{value}` | `PATCH /composite/sobjects/Account/{extField}` |
| Read | `GET /sobjects/Account/{id}` | `GET /composite/sobjects/Account?ids=...&fields=...` |
| Delete | `DELETE /sobjects/Account/{id}` | `DELETE /composite/sobjects?ids=...` |
All paths start with /services/data/{version}. Your instance URL and token work exactly as before.
The request body
Create and update use the same body shape. It has two top-level keys:
allOrNoneis a boolean. It controls what happens when some records fail.recordsis an array of record objects.
Every record object needs an attributes object that names the sObject type. This is the main difference from single-record calls. The type is no longer in the URL, so each record carries its own.
curl -X POST "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/composite/sobjects" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"allOrNone": false,
"records": [
{"attributes": {"type": "Account"}, "Name": "Acme Corp", "Industry": "Technology"},
{"attributes": {"type": "Account"}, "Name": "Globex", "Industry": "Banking"},
{"attributes": {"type": "Account"}, "Industry": "Energy"}
]
}'The third record has no Name, so it will fail. That is deliberate, and it shows how results are reported.
Because the type is set per record, one request can mix object types, such as Accounts and Contacts. Salesforce caps how many distinct types one request may contain, so check the current limit in the API documentation before relying on mixed batches.
Reading the response
The response is a JSON array with one entry per input record, in the same order as the input:
[
{"id": "001xx000003DGb2AAG", "success": true, "errors": []},
{"id": "001xx000003DGb3AAG", "success": true, "errors": []},
{
"success": false,
"errors": [
{
"statusCode": "REQUIRED_FIELD_MISSING",
"message": "Required fields are missing: [Name]",
"fields": ["Name"]
}
]
}
]Three details matter here:
- Order is the only link between input and result. A failed entry has no
id, so you match results to inputs by array position. - The HTTP status is 200 even when records fail. The status code says the batch was processed. It does not say every record succeeded. You must inspect each entry's
successflag. - Error entries use
statusCode, noterrorCode. The top-level error array from single-record calls useserrorCode. Inside composite results the key isstatusCode. A shared error handler has to cope with both names.
A request-level failure is different. An expired token returns 401 with the usual error array, and malformed JSON returns 400. In those cases no records were processed.
Choosing allOrNone
allOrNone decides whether the batch is a transaction.
| Setting | Behavior on a failure | Use when |
|---|---|---|
| `false` (default) | Valid records are saved. Failed records are reported individually. | Records are independent and you can retry the failures. |
| `true` | Nothing is saved. Every entry reports failure. | The records only make sense together. |
With allOrNone: true, the records that were valid are rolled back. Their entries carry the error code ALL_OR_NONE_OPERATION_ROLLED_BACK. Only the entry with a different error code is the real cause, so look for it when you debug.
[
{
"success": false,
"errors": [
{
"statusCode": "ALL_OR_NONE_OPERATION_ROLLED_BACK",
"message": "Record rolled back because not all records were valid and the request was made with allOrNone header",
"fields": []
}
]
},
{
"success": false,
"errors": [
{
"statusCode": "REQUIRED_FIELD_MISSING",
"message": "Required fields are missing: [Name]",
"fields": ["Name"]
}
]
}
]The first record was fine. The second one caused the rollback.
Updating many records
Update uses PATCH on the collection URL. There is no record ID in the path, so each record carries its own Id in the body, along with attributes.type. Send only the fields you want to change.
curl -X PATCH "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/composite/sobjects" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"allOrNone": false,
"records": [
{"attributes": {"type": "Account"}, "id": "001xx000003DGb2AAG", "Industry": "Banking"},
{"attributes": {"type": "Account"}, "id": "001xx000003DGb3AAG", "Industry": "Energy"}
]
}'Unlike a single-record PATCH, which returns 204 with an empty body, the composite update returns 200 with a result array. Each successful entry contains the id and success: true.
Retrieving and deleting in bulk
A bulk read names the type in the URL and lists IDs in the query string. The fields parameter is required here:
curl -G "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/composite/sobjects/Account" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN" \
--data-urlencode "ids=001xx000003DGb2AAG,001xx000003DGb3AAG" \
--data-urlencode "fields=Name,Industry"A record that does not exist comes back as null at its position in the array. Read results are also positional. A long ID list can exceed URL length limits. In that case use POST to the same path with ids and fields as JSON arrays in the body.
Bulk delete is DELETE /composite/sobjects?ids=...&allOrNone=false. Treat it with the same care as any delete. Test the ID list on a sandbox first.
Upserting in bulk
If your records have an external ID field, you can upsert a whole batch. The field name goes in the URL, and each record carries its value in the body:
curl -X PATCH "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/composite/sobjects/Account/ExternalId__c" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"allOrNone": false,
"records": [
{"attributes": {"type": "Account"}, "ExternalId__c": "ERP-1001", "Name": "Acme Corp"},
{"attributes": {"type": "Account"}, "ExternalId__c": "ERP-1002", "Name": "Globex"}
]
}'Each result entry includes a created flag. It is true for a new record and false for an update to an existing one. ExternalId__c is a placeholder name. Use the API name of your own external ID field.
A batching client in Python
The 200-record limit means larger sets must be split into chunks. This script does that and collects failures by their position in the original list, so you can retry or log them.
import os
import requests
instance_url = os.environ["SF_INSTANCE_URL"]
token = os.environ["SF_ACCESS_TOKEN"]
version = os.environ.get("SF_API_VERSION", "v60.0")
url = f"{instance_url}/services/data/{version}/composite/sobjects"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
CHUNK = 200
def create_many(sobject_type, rows, all_or_none=False):
"""Create rows in chunks. Returns (created_ids, failures)."""
created_ids = []
failures = [] # (index in rows, errors)
for start in range(0, len(rows), CHUNK):
chunk = rows[start:start + CHUNK]
records = [{"attributes": {"type": sobject_type}, **row} for row in chunk]
response = requests.post(
url,
headers=headers,
json={"allOrNone": all_or_none, "records": records},
timeout=60,
)
if not response.ok:
# Request-level failure: nothing in this chunk was processed
raise RuntimeError(f"{response.status_code}: {response.text}")
for offset, result in enumerate(response.json()):
if result["success"]:
created_ids.append(result["id"])
else:
failures.append((start + offset, result["errors"]))
return created_ids, failures
if __name__ == "__main__":
rows = [{"Name": f"Test Account {n}", "Industry": "Technology"} for n in range(450)]
rows.append({"Industry": "Energy"}) # missing Name, will fail
ids, failures = create_many("Account", rows)
print(f"created {len(ids)}, failed {len(failures)}")
for index, errors in failures:
print(index, errors[0]["statusCode"], errors[0]["message"])This sends three requests for 451 rows (200, 200, and 51). The last row fails and is reported with its index, 450.
Choosing between single and composite calls
Common errors and gotchas
- Missing
attributes.type. Without it the record is rejected. A typical message names the missing type. - More than 200 records. The request is rejected as a whole. Chunk before sending.
- Treating 200 as success. With
allOrNone: false, always scan every entry. - Assuming records run in parallel. Triggers, flows, and validation rules still run for every record. A large batch can hit per-transaction governor limits and fail with errors such as
CPU_TIME_LIMIT_EXCEEDED. If that happens, use smaller chunks. - Missing
idon update. Each update record needs its own ID in the body.
When Composite sObjects is the wrong tool
Composite sObjects suits up to a few thousand records. For tens of thousands or more, Bulk API 2.0 processes data asynchronously, with its own job limits. If you need to chain dependent calls, for example creating an Account and then a Contact that references its new ID, the separate Composite resource (/composite) lets later subrequests use earlier results. Composite sObjects cannot do that, because every record in the batch is independent of the others' outputs.
Exercise
You send 3 records to POST /composite/sobjects with allOrNone set to true. Record 2 is missing a required field. The response is HTTP 200. What do the three result entries contain, and how do you find the real cause?
Show answer
All three entries have success false, and nothing is saved. Records 1 and 3 report ALLORNONEOPERATIONROLLEDBACK. Record 2 reports the actual error, REQUIREDFIELD_MISSING. Find the cause by looking for the entry whose statusCode is not the rollback code.
Exercise
You need to update 1,250 Accounts and want valid records saved even if some fail. How many requests do you send, and what body keys and per-record keys must each request include?
Show answer
Six requests (five chunks of 200 and one of 50), using PATCH on /composite/sobjects. Each body has allOrNone set to false and a records array. Each record has attributes.type set to Account, an id, and the fields to change.