Sub topic 12
Upsert by External ID in an HTTP API
This chapter assumes you know basic SQL upserts, have seen a unique constraint on an external ID, and can read a simple HTTP request. Earlier chapters built the upsert inside the database. Here the same idea is exposed through an HTTP API, so a client can sync records without querying for them first.
Why an API offers upsert by external ID
Without upsert, a client that syncs from another system has to follow a risky sequence:
- Search for a record with this external ID.
- If found, send an update using the API's internal ID.
- If not found, send a create request.
Two workers can both search, both find nothing, and both create a record. A crash between steps also leaves the client unsure what happened. An upsert endpoint moves the match into the server, where a unique constraint backs it, so the client makes one call.
The request shape
The external ID goes in the URL, and the body carries only the field values. In the Salesforce REST API, a PATCH addressed by an external ID field looks like this:
PATCH /services/data/<api-version>/sobjects/Account/External_Id__c/C-1001
Content-Type: application/json
{"Name": "Ada Lovelace"}The parts of the URL are:
Accountis the object type, the equivalent of the table.External_Id__cis the field that holds the external ID. It must be marked as an external ID field, which also makes it unique if you configure it that way.C-1001is the value to match.
PATCH fits because the call changes only the fields you send. The ID is part of the address, so the same request sent twice addresses the same record. That is what makes retries safe.
Create versus update in the response
The client usually needs to know which branch ran. This API reports it in the status code:
| Outcome | Typical status | Meaning |
|---|---|---|
| Record created | 201 Created | No record matched, so a new one was inserted. |
| Record updated | 204 No Content | A record matched and its fields were changed. |
| Multiple matches | 300 Multiple Choices | The ID is not unique, so the server refuses to choose. |
Check the documentation of the API you use, because other services choose different codes. Some return 200 for both cases and put a flag such as created: true in the body.
The 300 case matters. It happens when the external ID field has no uniqueness guarantee. This is the same lesson as the unique constraint chapter, now seen from the client side.
A client that retries safely
The Python sketch below sends the upsert and treats both success codes as success. It assumes the requests library, and the base URL and token are placeholders you must replace.
import requests
BASE = "https://example.my.salesforce.com/services/data/v60.0"
TOKEN = "replace-with-a-real-access-token"
def upsert_account(external_id: str, fields: dict) -> str:
url = f"{BASE}/sobjects/Account/External_Id__c/{external_id}"
resp = requests.patch(
url,
json=fields,
headers={"Authorization": f"Bearer {TOKEN}"},
timeout=30,
)
if resp.status_code == 201:
return "created"
if resp.status_code == 204:
return "updated"
resp.raise_for_status()
raise RuntimeError(f"Unexpected status {resp.status_code}")
print(upsert_account("C-1001", {"Name": "Ada Lovelace"}))If a network timeout happens, the client cannot tell whether the server applied the request. It can simply send the same request again. The first attempt either created the record, so the retry updates it, or never arrived, so the retry creates it. Either way you end with one record.
Limits to remember
- Fields you omit from the body are normally left unchanged, so a
PATCHupsert is a partial update. Decide deliberately which fields to send. - The API does not know about your stale-data rule. If source data can arrive out of order, check timestamps on your side or use a conditional header if the API supports one.
- Not every API supports this. When one does not, you need the search-then-write sequence and must handle the race yourself.
Exercise
A client sends the same upsert PATCH twice because the first response timed out. The first request had reached the server. What status codes would you expect, and how many records exist afterward?
Show answer
The first request returns 201 Created because no record matched. The retry matches the new record and returns 204 No Content. One record exists afterward, because both requests address the same external ID.
Exercise
Why does the API return 300 Multiple Choices in some cases, and what is the fix?
Show answer
More than one record has the same external ID value, so the server cannot pick one to update. The fix is to remove the duplicates and make the external ID field unique so the situation cannot recur.