Sub topic 12
Upserting Records by External ID
This chapter assumes you can already create records with POST, read them with GET, and update them with PATCH. It also assumes you have an access token and know the instance URL and API version for your org. An upsert combines create and update in one call, so you don't have to check whether a record exists first.
Why upsert exists
Suppose you sync customers from an ERP system into Salesforce. Each customer has a number in the ERP, but Salesforce doesn't know your ERP number. It knows only its own 18-character record IDs. Without upsert, each sync run would have to:
- Query Salesforce for an Account with that customer number.
- If one exists, PATCH it by Salesforce ID.
- If none exists, POST a new one.
That is two round trips, and a race condition if two jobs run at once. Both jobs can see "no match" and both can create a record. An upsert does the lookup and the write in one request, using a field you control as the key.
What an external ID field is
An external ID field is a custom field with the External ID attribute enabled. Text, number, and email fields can have it. You configure it in Setup under Object Manager, in the field's definition. Two other attributes matter:
- Unique makes Salesforce reject a second record with the same value. Turn this on for upsert keys.
- Case sensitive controls whether
abc-1andABC-1count as the same value. It applies only when Unique is on.
The examples below use a custom text field named Customer_Number__c on Account, marked as External ID and Unique.
The request
An upsert is a PATCH to a URL that names the field and the value:
PATCH /services/data/v60.0/sobjects/{SObjectName}/{ExternalIdFieldName}/{value}The body contains the fields to set, in the same JSON format as a normal create or update.
export SF_INSTANCE_URL="https://MyDomain.my.salesforce.com"
export SF_ACCESS_TOKEN="<access token>"
export SF_API_VERSION="v60.0"
curl -X PATCH "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/sobjects/Account/Customer_Number__c/C-1001" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"Name": "Acme Corp", "Industry": "Technology"}' \
-iThe -i flag prints the status line and headers, which you need here because the status code tells you what happened.
Reading the result
The status code tells you which branch Salesforce took.
| Status | Meaning | Body |
|---|---|---|
| 201 Created | No record matched, so Salesforce inserted one | JSON with `id`, `success`, and `errors` |
| 204 No Content | One record matched, so Salesforce updated it | Empty |
| 300 Multiple Choices | More than one record matched the value | List of URLs for the matching records |
| 400 Bad Request | The body was invalid, for example a missing required field on insert | Error array |
| 404 Not Found | The sObject or field name in the URL doesn't exist, or the field isn't an external ID | Error array |
On a 201, the body looks like a normal create response:
{
"id": "001xx000003DGb2AAG",
"success": true,
"errors": []
}On a 204, the body is empty and the Salesforce ID is not returned. If you need the ID after an update, make a GET or a SOQL query. Many sync jobs don't need the ID, because the external ID is the key they use from then on.
Insert and update rules differ
The same PATCH call can create or update, and the validation rules follow whichever branch runs.
- On the insert branch, required fields must be in the body. If
Nameis missing and the value is new, you get a 400 withREQUIRED_FIELD_MISSING. The same request would succeed if the record already existed, because updates don't need required fields that are already set. - On the update branch, only the fields in the body change. Fields you omit keep their values.
- On the insert branch, Salesforce sets the external ID field from the URL value. You don't need to repeat it in the body.
This means a payload can pass in testing against existing data and then fail the first time it meets a new key. Test both branches with a value that exists and one that doesn't.
What to keep out of the body
Keep the record Id out of the body. Salesforce rejects it, because the external ID in the URL already identifies the record. Keep the external ID field itself out of the body as well. Its value is in the URL, so repeating it adds nothing and can cause conflicts.
Non-ASCII characters, spaces, slashes, and other special characters in the external ID value must be URL-encoded in the path. A value such as EU/2024 001 would break the URL if you pasted it in raw. In Python, use urllib.parse.quote(value, safe="").
Handling the 300 response
A 300 happens when the field isn't marked Unique and two or more records share the value. Salesforce won't guess which one you meant. The body is a JSON array of record URLs:
[
"/services/data/v60.0/sobjects/Account/001xx000003DGb2AAG",
"/services/data/v60.0/sobjects/Account/001xx000003DGb3AAG"
]You can't resolve this by retrying. The data has a duplicate, and someone has to merge or fix it. The best prevention is enabling Unique on the field. Then Salesforce rejects the second record when it's created, rather than leaving the problem for a later upsert.
A complete Python example
This script upserts one Account and reports which branch ran. It handles 201, 204, and 300 explicitly and raises on any other failure.
import os
from urllib.parse import quote
import requests
instance_url = os.environ["SF_INSTANCE_URL"]
token = os.environ["SF_ACCESS_TOKEN"]
version = os.environ.get("SF_API_VERSION", "v60.0")
base = f"{instance_url}/services/data/{version}"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
def upsert_account(customer_number, fields):
"""Create or update an Account keyed on Customer_Number__c.
Returns ("created", record_id) or ("updated", None).
"""
url = (
f"{base}/sobjects/Account/Customer_Number__c/"
f"{quote(customer_number, safe='')}"
)
response = requests.patch(url, headers=headers, json=fields, timeout=30)
if response.status_code == 201:
return "created", response.json()["id"]
if response.status_code == 204:
return "updated", None
if response.status_code == 300:
raise RuntimeError(
f"Duplicate external ID {customer_number!r}: {response.text}"
)
raise RuntimeError(f"{response.status_code}: {response.text}")
for _ in range(2):
outcome, record_id = upsert_account(
"C-1001", {"Name": "Acme Corp", "Industry": "Technology"}
)
print(outcome, record_id)On a fresh org, the first iteration prints created followed by an ID. The second prints updated None. Running the script again prints updated None both times. That repeatable behavior is what makes upsert good for sync jobs.
Idempotency and retries
An upsert is idempotent in effect. Sending the same request twice leaves one record with the same field values. This makes retries after a network timeout safe. If the first request created the record but the response was lost, the retry takes the update branch and changes nothing. A POST create has no such protection, and a blind retry can create a duplicate.
Idempotent here describes the data, not the status code. Your retry logic should accept either 201 or 204 as success.
Upsert across relationships
You can also set a lookup field by the parent's external ID instead of its Salesforce ID. To link a Contact to an Account without querying for the Account ID, nest the parent's external ID in the body:
{
"LastName": "Rivera",
"Account": {
"Customer_Number__c": "C-1001"
}
}Send this as a PATCH upsert on Contact, keyed by an external ID field on Contact. Salesforce resolves the parent from the nested value. If no Account has that number, the call fails, so load parents before children.
Common errors
- 404 on the first call. The field API name is probably wrong. Custom field names end in
__c, and the name is case-sensitive in some contexts. Also check that the field has External ID enabled. - 400
REQUIRED_FIELD_MISSINGonly for some rows. Those rows hit the insert branch. Add the required fields to every payload. - 400 with an Id in the body. Remove it.
- 300 for a value you thought was unique. The field isn't marked Unique, or the data predates that setting. Query for the duplicates, merge them, then enable Unique.
- A 204 you read as "nothing happened". A 204 means the update was applied. Verify with a GET if you want to be sure.
Exercise
You send PATCH .../sobjects/Account/CustomerNumber_c/C-2002 with the body {"Industry": "Banking"}. No Account has that customer number, and Name is a required field. What status code and error do you expect, and how do you fix the request?
Show answer
Salesforce takes the insert branch because nothing matches, and the insert fails validation. You get 400 Bad Request with errorCode REQUIREDFIELDMISSING for Name. Add "Name" to the body, for example {"Name": "Example Bank", "Industry": "Banking"}. The call then returns 201 with the new record ID. If a record with C-2002 had existed, the original request would have returned 204.
Exercise
A nightly job upserts Accounts and gets a 300 response for customer number C-3003. Why does this happen, can you fix it by retrying, and what should you change?
Show answer
More than one Account has C-3003 in CustomerNumber_c, which is possible when the field isn't marked Unique. Salesforce can't choose which record to update, so it returns the list of matching record URLs. Retrying returns the same 300. Someone has to merge or correct the duplicate records, and then the field should be marked Unique so duplicates can't be created again.