Sub topic 9
Bulk operations with sObject Collections
This chapter assumes you can send authenticated REST calls to a Salesforce org with an OAuth access token and instance URL. It also assumes you know basic sObject endpoints, JSON bodies, and HTTP status codes. Earlier chapters covered /composite and reference IDs. Here you will use a different resource, sObject Collections, to work on many records of the same kind at once.
What sObject Collections does
The /composite/sobjects resource creates, updates, upserts, retrieves, or deletes up to 200 records in one HTTP request. Without it, saving 200 Accounts takes 200 calls to /sobjects/Account. Each call is one round trip and counts against your org's API request limit. With Collections, the same work is one round trip and one API call.
The resource differs from the general /composite endpoint in a few ways:
- Every record gets the same operation. You cannot mix a create and a delete in one request.
- Records cannot refer to each other. There are no reference IDs, so you cannot link a new Contact to a new Account in the same call.
- The response is a flat array of per-record results, not a
compositeResponseof subrequests.
If you need records linked to each other, use sObject Tree or /composite instead. This chapter is about volume.
Endpoints at a glance
| Operation | Method and path | Where the data goes | Record limit |
|---|---|---|---|
| Create | `POST /composite/sobjects` | JSON body with `records` | 200 |
| Update | `PATCH /composite/sobjects` | JSON body with `records`, each with an `Id` | 200 |
| Upsert | `PATCH /composite/sobjects/{sObject}/{externalIdField}` | JSON body with `records` | 200 |
| Delete | `DELETE /composite/sobjects?ids=...` | Query string | 200 |
| Retrieve | `GET /composite/sobjects/{sObject}?ids=...&fields=...` | Query string | 2,000 |
Retrieve also accepts a POST with ids and fields in the body. Use that form when a long list of IDs would make the URL too long. All paths start with /services/data/v60.0.
Creating records
A create request has two top-level keys. allOrNone is a boolean, and records is an array. Each record needs an attributes object that names its type, because one request can carry different sObject types. The other keys are field values.
{
"allOrNone": false,
"records": [
{ "attributes": { "type": "Account" }, "Name": "Bulk Account 1" },
{ "attributes": { "type": "Account" }, "Name": "Bulk Account 2" }
]
}Send it to POST /services/data/v60.0/composite/sobjects. A typical response looks like this:
[
{ "id": "001xx000003DGb1AAG", "success": true, "errors": [] },
{ "id": "001xx000003DGb2AAG", "success": true, "errors": [] }
]The response array has the same length and order as the request's records array. Result 0 belongs to record 0. The response does not echo any of your input, so this ordering is the only way to match results to inputs.
Updating and upserting
An update uses PATCH on the same path. Each record must include its Id, plus the fields to change. Fields you leave out are not touched.
{
"allOrNone": false,
"records": [
{ "attributes": { "type": "Account" }, "Id": "001xx000003DGb1AAG", "Industry": "Retail" },
{ "attributes": { "type": "Account" }, "Id": "001xx000003DGb2AAG", "Industry": "Energy" }
]
}An upsert inserts a record or updates it, depending on whether a record with the same external ID value already exists. You send it to PATCH /composite/sobjects/Account/External_Key__c, where External_Key__c is a field marked as an external ID on the object. The records in the body carry that field's value. The body's attributes still names the type, and every record must be of the type in the URL. Each upsert result adds a created flag. It is true for an insert and false for an update.
Deleting and retrieving
Delete and retrieve put their data in the query string, so there is no body.
curl -X DELETE \
"$INSTANCE_URL/services/data/v60.0/composite/sobjects?ids=001xx000003DGb1AAG,001xx000003DGb2AAG&allOrNone=false" \
-H "Authorization: Bearer $ACCESS_TOKEN"The delete response has the same per-record shape as create. Retrieve returns an array of full records instead, and you choose the columns with fields:
curl -G "$INSTANCE_URL/services/data/v60.0/composite/sobjects/Account" \
--data-urlencode "ids=001xx000003DGb1AAG,001xx000003DGb2AAG" \
--data-urlencode "fields=Id,Name,Industry" \
-H "Authorization: Bearer $ACCESS_TOKEN"An ID that matches no record, or one the user cannot see, comes back as null at that position in the array. It does not cause an error. Retrieve is the only operation here that is not capped at 200 records.
The allOrNone flag in Collections
The flag works as it does in /composite, but its default is different. For create, update, upsert, and delete, allOrNone defaults to false. On the delete endpoint it is a query parameter instead of a body field.
| `allOrNone` | One record fails validation | Result |
|---|---|---|
| `false` | The other records still save. | Mixed `success` values in the array. |
| `true` | The whole request rolls back. | No record is saved or changed. |
With true, the failing record reports its real error. The records that would have succeeded report success: false with the status code ALL_OR_NONE_OPERATION_ROLLED_BACK. When you scan the errors, look for the entry whose code is something else. That entry is the cause.
With false, you get partial success. Salesforce commits the good records, and your code must find the bad ones and decide what to do with them.
HTTP 200 does not mean every record saved
This is the most common mistake with Collections. The request as a whole can succeed, with status 200, while individual records fail. The HTTP status tells you only that Salesforce processed the request. A bad request, such as malformed JSON, an invalid session, or more than 200 records, fails with a 4xx status and an error body instead of a results array.
So you must always inspect the per-record results:
import os
import requests
base = os.environ["INSTANCE_URL"]
headers = {"Authorization": "Bearer " + os.environ["ACCESS_TOKEN"]}
names = ["Bulk Account 1", "Bulk Account 2", ""] # the empty name will fail
records = [{"attributes": {"type": "Account"}, "Name": n} for n in names]
resp = requests.post(
base + "/services/data/v60.0/composite/sobjects",
headers=headers,
json={"allOrNone": False, "records": records},
timeout=30,
)
resp.raise_for_status()
failed = []
for record, result in zip(records, resp.json()):
if result["success"]:
print("created", result["id"])
else:
messages = [e["message"] for e in result["errors"]]
print("failed ", record["Name"] or "(blank)", messages)
failed.append(record)
print(len(failed), "record(s) need attention")The zip call pairs each input with its result by position. The raise_for_status call catches request-level failures, and the loop catches record-level ones. The failed list is what you would fix and resend, or write to a log.
Processing more than 200 records
The limit is per request, so a larger job needs several requests. Split the list into chunks of 200 and send each chunk. Chunking has a consequence for allOrNone. The flag covers only one request, so with allOrNone: true a failure rolls back that chunk and not the earlier ones. If the whole job must be atomic, Collections cannot give you that. Keep the job under 200 records, or design the operation so it can be safely retried.
def chunks(items, size=200):
for start in range(0, len(items), size):
yield items[start:start + size]Each chunk is one API call, so 1,000 records cost 5 calls, not 1,000. For very large volumes in the tens of thousands or more, Bulk API 2.0 is the better tool. Collections suits interactive and mid-sized work.
Side effects to expect
Collections runs the same save logic as any other write. Validation rules, triggers, flows, and duplicate rules all fire. Governor limits apply too. A trigger that runs a SOQL query per record can hit its limit when 200 records arrive together, even though it works fine for single saves. If a Collections request fails with a limit error, test the same records with a smaller chunk size such as 50 to find out whether automation is the cause.
Choosing Collections
The diagram shows how to pick between Collections and the other resources, using the questions from this chapter.
Common errors
- Forgetting
attributes.type. A create or update without it is rejected. The type is needed on every record, even when all records are the same type. - Missing
Idon update. Each updated record needs itsId. Without it, that record fails. - Sending 201 records. The whole request is rejected, and no record is processed.
- Matching results by ID. Failed creates have no ID. Match by position.
- Assuming
allOrNonedefaults to true. In/compositeand in Collections, check which default applies before you rely on rollback.
Exercises
Exercise
You send a create request with 150 Accounts and allOrNone set to false. Salesforce returns HTTP 200, and 3 of the 150 results have success: false. How many Accounts were saved, and how do you find which input records failed?
Show answer
147 Accounts were saved, because with allOrNone: false the valid records are committed. The response array has the same order as the request's records array, so the index of each success: false result is the index of the failed input record. Read its errors array for the reason.
Exercise
You send 100 records with allOrNone: true, and record 42 fails a validation rule. What do the other 99 results look like, and how do you find the real cause?
Show answer
Nothing is saved. The other 99 results have success: false with the status code ALL_OR_NONE_OPERATION_ROLLED_BACK. The real cause is the one result whose error code is something else, which is record 42's validation error.
Exercise
You need to create 450 Contacts and each must either succeed or fail on its own. Describe the request plan and the number of API calls.
Show answer
Split the records into three chunks of 200, 200, and 50. Send each chunk as a POST /composite/sobjects request with allOrNone: false, and check every result's success flag. This uses 3 API calls. Collect the failed records from all three responses for correction and retry.