Sub topic 12
Upserting records by external ID
This chapter assumes you can already create records with POST and update them with PATCH, as in the earlier chapters. You also need an access token and the instance URL and API version variables used so far.
What an upsert does
An upsert is a single call that updates a record if it exists and creates it if it doesn't. You identify the record by an external ID instead of the Salesforce record ID.
An external ID is a custom field marked External ID in its field definition. It usually holds the key from another system, such as an ERP customer number. Syncing data from that system then needs no lookup of Salesforce IDs and no check for an existing record.
The request
Put the field's API name and the value in the URL, after the object name:
PATCH /services/data/v60.0/sobjects/Account/Billing_Ref__c/ACME-001This example assumes Billing_Ref__c is an External ID field on Account.
curl -X PATCH "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/sobjects/Account/Billing_Ref__c/ACME-001" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"Name": "Acme Corp", "Industry": "Technology"}' \
-iThe body holds the other fields to set. The external ID value comes from the URL, so leave that field out of the body.
How Salesforce decides what to do
| Matches | Status | Body |
|---|---|---|
| None | 201 Created | `id`, `success`, `errors` |
| One | 204 No Content | Empty |
| Several | 300 Multiple Choices | List of matching record URLs |
A successful create returns the same shape as a normal POST:
{
"id": "001xx000003DGb2AAG",
"success": true,
"errors": []
}Handling the response in Python
Because one call can mean two outcomes, check the status code to learn which one happened.
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}/sobjects/Account/Billing_Ref__c/ACME-001"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
response = requests.patch(
url,
headers=headers,
json={"Name": "Acme Corp", "Industry": "Technology"},
timeout=30,
)
if response.status_code == 201:
print("Created", response.json()["id"])
elif response.status_code == 204:
print("Updated existing record")
elif response.status_code == 300:
print("Ambiguous external ID:", response.text)
else:
raise RuntimeError(f"{response.status_code}: {response.text}")Running the script twice shows both paths. The first run prints "Created" and the second prints "Updated existing record".
Common errors
- 404 NOT_FOUND on the URL. The field name is misspelled, or the field isn't marked External ID. Check the field's API name, including the
__csuffix. - 300 Multiple Choices. The external ID field isn't marked Unique, and more than one record has the value. Nothing is changed. Fix the duplicate data, or mark the field Unique so duplicates can't be saved.
- REQUIREDFIELDMISSING. If the call ends up creating a record, the body must contain every required field. An upsert that would have only updated can still fail on a first run for this reason.
- Special characters in the value. URL-encode values that contain spaces, slashes, or other reserved characters. In Python, use
urllib.parse.quote(value, safe="").
When to use it
Use an upsert when records come from another system that has its own keys. Use plain POST and PATCH when you already hold Salesforce IDs. An upsert also removes the "query first, then create or update" pattern, which saves one API call per record.
Exercise
You send PATCH .../sobjects/Account/BillingRef_c/ACME-002 and receive 204 No Content with an empty body. What happened, and how would you get the record's Salesforce ID?
Show answer
A record with BillingRefc = ACME-002 already existed and was updated, because 201 would mean a new record was created. The 204 response has no body, so no ID is returned. To get the ID, send a GET to the same URL, or run a SOQL query such as SELECT Id FROM Account WHERE BillingRef__c = 'ACME-002'.