Sub topic 12
Upsert by External ID in an HTTP API
This chapter assumes you have read the earlier chapters on external IDs, unique constraints, and SQL upserts with ON CONFLICT. You should also know basic HTTP: methods, status codes, headers, and JSON bodies. Here the same idea moves from a database statement to a web request. The client names the external ID, and the server decides whether to create or update.
From SQL to an HTTP request
In SQL, the match key goes in the ON CONFLICT clause. In an API, the key goes in the URL. Some APIs let you address a record by an external ID field instead of the server's internal ID. A single request then means "make this record exist with these values", and the server does the insert-or-update.
Without this feature, a client has to do the work itself:
- Send a query to look for a record with this external ID.
- If one exists, send an update to its internal ID.
- If none exists, send a create request.
That is two requests, and a race window between them. Two clients running these steps at once can both see "not found" and both create a record. The server-side upsert removes the gap, in the same way that ON CONFLICT removes the gap between a SELECT and an INSERT.
The Salesforce pattern
The Salesforce REST API is a well-known example. You mark a custom field on an object as an external ID field. Then you send a PATCH request to a URL that contains the field name and the value:
PATCH /services/data/<api-version>/sobjects/Account/External_Id__c/C-1001
Content-Type: application/json
{"Name": "Ada Lovelace"}The URL has these parts:
sobjects/Accountis the object type, like the table name.External_Id__cis the field that holds the identifier from the other system.C-1001is the value to match.
The body holds only the fields you want to set. Replace <api-version> with a real version such as v60.0, and add an Authorization: Bearer <token> header when you send it.
The status code tells you what happened:
| Status | Meaning |
|---|---|
| 201 Created | No record matched, so the server inserted one. The response body includes the new internal ID. |
| 204 No Content | A record matched and the server updated it. The body is empty. |
| 300 Multiple Choices | More than one record has this external ID value. The server refuses to guess. |
| 4xx other | The request was rejected, for example for a bad field name, a validation failure, or an expired token. |
The 300 case happens when the external ID field is not marked unique in the target system. That is the same problem as a missing unique constraint in SQL: without uniqueness, the match is not reliable.
Why PATCH and not POST
The HTTP method matters for retries. POST usually means "create something new", and repeating it can create a second record. PUT and PATCH are defined as idempotent when the target resource is the same each time. That means sending the request twice leaves the server in the same state as sending it once.
Here the target is identified by the external ID in the URL. If the first request created the record, the second finds it and updates it. The final state is the same. This is the HTTP version of the idempotent load from earlier chapters.
The practical benefit is simple retry logic. If a request times out, you do not know whether the server applied it. With an upsert by external ID you can send it again without checking first.
Two caveats:
- Idempotent does not mean "same response". The first call may return 201 and the retry 204. Your client must treat both as success.
- A retry can still overwrite a newer change made in between, by you or by someone else. See the section on stale data below.
PUT versus PATCH in other APIs
Not every API uses Salesforce's conventions. Many designs use PUT /customers/{source_system}/{external_id} instead. The difference in meaning is:
PUTreplaces the whole record. Any field you leave out may be reset to its default or null.PATCHchanges only the fields you send.
Read the API documentation to find out which one it implements. This is the HTTP form of the "which fields does an update overwrite" decision. If a client sends a partial body with PUT to an API that replaces, it silently erases data.
Also check how the API reports create versus update. Some return 201 and 200, some return 201 and 204, and some return 200 for both with a flag in the body. Do not assume the Salesforce codes everywhere.
A client in Python
This function sends the request and reports what the server did. It uses the requests library, which you can install with pip install requests.
import os
from urllib.parse import quote
import requests
def upsert_account(external_id: str, fields: dict) -> str:
instance_url = os.environ["SF_INSTANCE_URL"] # for example https://example.my.salesforce.com
token = os.environ["SF_ACCESS_TOKEN"]
api_version = os.environ.get("SF_API_VERSION", "v60.0")
# Encode the value: external IDs can contain "/", "?", spaces, and so on.
safe_id = quote(external_id, safe="")
url = (
f"{instance_url}/services/data/{api_version}"
f"/sobjects/Account/External_Id__c/{safe_id}"
)
response = requests.patch(
url,
json=fields,
headers={"Authorization": f"Bearer {token}"},
timeout=30,
)
if response.status_code == 201:
return "created"
if response.status_code == 204:
return "updated"
if response.status_code == 300:
raise RuntimeError(
f"External ID {external_id!r} matches several records; "
"the field is probably not unique"
)
response.raise_for_status()
raise RuntimeError(f"Unexpected status {response.status_code}")
if __name__ == "__main__":
print(upsert_account("C-1001", {"Name": "Ada Lovelace"}))Running it twice in a row against an empty org prints created, then updated. The second run changes nothing, which is the idempotence you want.
Three details in this code are common sources of bugs:
quote(external_id, safe="")escapes every reserved character. Without it, an ID such asA/7changes the URL path and the request goes to the wrong place.- A
timeoutis set. A request with no timeout can hang forever, and a retry policy needs a timeout to trigger. - Only 201 and 204 count as success. Anything else is surfaced instead of being swallowed.
Normalize before you send
The earlier chapter on normalizing external IDs applies here too. The server compares the value in your URL to the stored value. If one system sends c-1001 and another sends C-1001, the server may treat them as different records, or it may treat them as the same, depending on how the field is configured. Salesforce, for example, can treat case differently depending on the field's setting. Trim whitespace, fix the case, and keep one format in your own client before the request goes out. Then you do not depend on the server's matching rules.
What can go wrong
- The external ID field is not unique. The server may return 300 or may behave unpredictably. Mark the field unique in the target system, just as you add a
UNIQUEconstraint in SQL. - Rate limits and partial failure. If you send thousands of single requests, some will fail. Because each request is idempotent, you can rerun the whole list. Log which external IDs failed so you can also retry only those.
- Stale data. A retry or a late-arriving message can overwrite a newer value. If the API supports a conditional header such as
If-Unmodified-Since, or you can send asource_updated_atfield and have the server compare it, use that. If it does not, you may need to filter stale records on your side before sending. - Read-only and system fields. Some fields cannot be written. A request that includes one is rejected with a 4xx error. Send only fields you are allowed to set.
- Reading the wrong status. A client that treats only 200 as success will report errors for every create and every update here.
Checking your work
To verify an API upsert, follow the same approach as for SQL:
- Send the same request twice and confirm the first response is a create and the second is an update.
- Query the target system for the external ID and confirm exactly one record comes back.
- Run your whole batch twice and compare record counts before and after the second run. The count should not change.
Exercise
A client sends PATCH /sobjects/Account/ExternalId_c/C-1001 and receives 201. It does not see the response (the connection drops), so it sends the identical request again. What status should it expect on the second request, and is the retry safe?
Show answer
It should expect 204 No Content, because the record created by the first request now matches the external ID, so the server updates it instead of creating another. The retry is safe because the request is idempotent: the final state is one record with those values. The client must treat both 201 and 204 as success.
Exercise
Why must the Python client call quote(external_id, safe="") before building the URL?
Show answer
The external ID is placed in the URL path. If it contains characters such as "/" or "?", they change the path or start a query string, so the request addresses a different resource or the wrong record. Percent-encoding every reserved character keeps the value as a single path segment.
Exercise
An upsert request returns 300 Multiple Choices. What does it mean, and how do you prevent it?
Show answer
More than one record in the target system has that external ID value, so the server cannot choose which one to update. Prevent it by marking the external ID field unique in the target system, and clean up any existing duplicates.