Sub topic 8
Updating a Record with PATCH
This chapter covers how to change an existing Salesforce record with an HTTP PATCH request. It assumes you can already build a resource URL, send a bearer token, and create and read a record, as covered in earlier chapters. You should also be comfortable with curl or Python's requests library and with reading JSON.
How an update works
To update a record, send a PATCH request to the record's sObject URL. The body is a JSON object that lists only the fields you want to change. Salesforce leaves every other field as it is.
The URL has the same shape you used for reading:
{instance_url}/services/data/{version}/sobjects/{SObjectName}/{recordId}A successful update returns 204 No Content with an empty body. The record is not echoed back. If you need the new values, send a GET afterward.
The following diagram shows the exchange.
A first update with curl
This example reuses the environment variables from the create chapter. It changes the Industry field of the account created earlier. Replace the record ID with your own.
curl -X PATCH "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/sobjects/Account/001xx000003DGb2AAG" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"Industry": "Banking"}' \
-iThe -i flag prints the response headers. A body-less success is easy to mistake for a failure when curl prints nothing, so the status line is how you confirm it worked. You should see a line like this:
HTTP/1.1 204 No ContentWithout -i, curl prints nothing at all on success. Use -i while you are learning, or -w "%{http_code}\n" -o /dev/null in scripts.
What belongs in the request body
The body follows a few rules.
- Send only the changed fields. Including unchanged fields is allowed but wasteful. It can also trigger validation rules or field-level checks on values you did not mean to touch.
- Use field API names. Write
Industry,AnnualRevenue, orCustom_Field__c. Do not use the labels shown in the user interface. - Match the field type. Strings are quoted, numbers are not, booleans are
trueorfalse, and dates use ISO 8601 (2026-12-01). Date-times use2026-12-01T08:19:10.000+0000. - Do not send the
Idfield. The ID is in the URL. SendingIdin the body causes an error, even when it matches. - Do not send read-only fields. System fields such as
CreatedDate,LastModifiedDate, and formula fields cannot be written. - Do not send an
attributesblock. That block belongs to other endpoints, such as Composite sObjects. A single-record PATCH does not use it.
To clear a field, set it to null:
curl -X PATCH "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/sobjects/Account/001xx000003DGb2AAG" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"Description": null}' \
-iSalesforce rejects null for required fields. An empty string typically does the same thing as null for text fields, but null states the intent more clearly.
Updating with Python
The script below updates several fields at once, then verifies the change by reading the record back. It uses the same check helper idea as the earlier chapters: raise an error that includes the response body when a call fails.
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")
account_id = os.environ["SF_ACCOUNT_ID"]
base = f"{instance_url}/services/data/{version}"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
def check(response):
if not response.ok:
raise RuntimeError(f"{response.status_code}: {response.text}")
return response
changes = {"Industry": "Banking", "Description": "Updated through the REST API"}
response = check(requests.patch(
f"{base}/sobjects/Account/{account_id}",
headers=headers,
json=changes,
timeout=30,
))
# A successful PATCH returns 204 and an empty body.
assert response.status_code == 204
assert response.text == ""
# Read the record back to confirm the new values.
account = check(requests.get(
f"{base}/sobjects/Account/{account_id}",
headers=headers,
params={"fields": "Name,Industry,Description"},
timeout=30,
)).json()
print(account["Name"], account["Industry"], account["Description"])Set SF_ACCOUNT_ID to the ID returned when you created the account. Do not call response.json() on the PATCH response. The body is empty, so parsing it raises a JSONDecodeError.
Common errors
Updates fail for a small set of predictable reasons. Salesforce returns a JSON array of error objects, as described in the error handling chapter. The errorCode value tells you what went wrong.
| Status | `errorCode` | Typical cause | Fix |
|---|---|---|---|
| 400 | `INVALID_FIELD` | A field name is misspelled, or the field does not exist on the object | Check the API name with the describe resource |
| 400 | `REQUIRED_FIELD_MISSING` | The update sets a required field to `null` | Provide a value |
| 400 | `MALFORMED_QUERY` or `JSON_PARSER_ERROR` | The JSON body is invalid, such as a trailing comma or single quotes | Validate the JSON |
| 400 | `INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST` | The value is not in a restricted picklist | Use a listed value |
| 400 | `FIELD_CUSTOM_VALIDATION_EXCEPTION` | A validation rule rejected the new values | Read the message and satisfy the rule |
| 400 | `STRING_TOO_LONG` | A text value exceeds the field length | Shorten the value |
| 401 | `INVALID_SESSION_ID` | The access token is expired or invalid | Get a new token and retry |
| 403 | `INSUFFICIENT_ACCESS_OR_READONLY` | The user lacks edit access to the record | Check sharing and permissions |
| 404 | `NOT_FOUND` | The ID does not exist or the object name in the URL is wrong | Check the ID and URL |
| 415 | `UNSUPPORTED_MEDIA_TYPE` | The `Content-Type` header is missing or wrong | Send `application/json` |
A few of these deserve more detail.
Wrong object name with a valid ID
A record ID begins with a three-character prefix that identifies the object type. The prefix 001 means Account. If you send a Contact ID (prefix 003) to the Account URL, Salesforce returns a 404 or an error saying the ID does not match the object. When an update returns NOT_FOUND and you are sure the record exists, compare the prefix with the object name in the URL.
Validation rules and triggers
The REST API runs the same server-side logic as the user interface: validation rules, required fields, and Apex triggers. An update can pass your field checks and still fail because of an org rule. The error message names the rule, so log the full response body, not just the status code.
Expired tokens
A 401 with INVALID_SESSION_ID means the token is no longer valid. Refresh the token, then repeat the request. Repeating a PATCH is safe, because applying the same field values twice leaves the record in the same state. Triggers or automation that fire on every save can still run twice, though.
Update behavior to know about
- Concurrent edits. PATCH does not check whether someone else changed the record since you read it. The last write to each field wins. If two clients edit different fields, both changes survive, because each request touches only its own fields. If they edit the same field, the later one overwrites the earlier one.
- Conditional updates. Salesforce supports
If-Unmodified-Sinceon record requests. If the record changed after the date you give, the update is rejected with412 Precondition Failed. Use it when lost updates matter. - Side effects. Updating a record changes
LastModifiedDateandLastModifiedById, even when the new values equal the old ones. Workflow rules, flows, and triggers may run. - Updating by ID only. A plain PATCH needs the Salesforce record ID. To update by an ID from another system, use upsert with an external ID, which is covered in a later chapter.
- One record per call. Each PATCH changes one record and counts as one API call. For many records, use the Composite sObjects endpoints.
Here is a conditional update:
curl -X PATCH "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/sobjects/Account/001xx000003DGb2AAG" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-H "If-Unmodified-Since: Tue, 01 Dec 2026 08:00:00 GMT" \
-d '{"Industry": "Banking"}' \
-iIf the account was modified after 08:00 GMT, the response is 412 Precondition Failed and nothing is changed.
A reliable update routine
A dependable update function has four parts: build the URL, send only changed fields, treat 204 as success, and surface the error body on failure. This version also refreshes the token once on a 401. The get_new_token function is a placeholder for your own OAuth refresh logic.
import os
import requests
def get_new_token():
# Replace with your OAuth refresh or re-authentication call.
return os.environ["SF_ACCESS_TOKEN"]
def update_record(sobject, record_id, changes, token=None):
instance_url = os.environ["SF_INSTANCE_URL"]
version = os.environ.get("SF_API_VERSION", "v60.0")
url = f"{instance_url}/services/data/{version}/sobjects/{sobject}/{record_id}"
token = token or os.environ["SF_ACCESS_TOKEN"]
for attempt in range(2):
response = requests.patch(
url,
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
},
json=changes,
timeout=30,
)
if response.status_code == 204:
return
if response.status_code == 401 and attempt == 0:
token = get_new_token()
continue
raise RuntimeError(f"{response.status_code}: {response.text}")
update_record("Account", os.environ["SF_ACCOUNT_ID"], {"Industry": "Banking"})
print("Updated")Summary
- Update with
PATCHon/sobjects/{SObject}/{id}, sending a JSON object of only the changed fields. - Success is
204 No Contentwith an empty body. Read the record again if you need the new values. - Use field API names, matching types, and
nullto clear a field. OmitIdand read-only fields. - Expect 400 for bad data or validation failures, 401 for expired tokens, and 404 for a wrong ID or object name.
- PATCH is partial, so omitted fields are untouched, and last write wins unless you use
If-Unmodified-Since.
Exercise
You send a PATCH to update an Account with the body {"Id": "001xx000003DGb2AAG", "Industry": "Banking"}, and the request fails with a 400 error. In a second attempt, the PATCH returns 204, but your code then crashes with a JSONDecodeError. What caused each problem, and how do you fix both?
Show answer
The first failure comes from including Id in the body. The record ID belongs only in the URL, so remove it and send {"Industry": "Banking"}. The second failure comes from calling response.json() on the 204 response. A successful PATCH has an empty body, so there is nothing to parse. Check response.status_code == 204 instead, and send a GET if you need the updated values.
Exercise
Two clients read the same Account. Client A sends PATCH {"Industry": "Banking"}. Later Client B sends PATCH {"Description": "VIP"}. What does the record contain afterward, and how would you prevent Client B from overwriting a change it never saw?
Show answer
The record has both changes: Industry is Banking and Description is VIP, because each PATCH touches only its own fields. If both clients had changed the same field, the later write would win. To avoid overwriting unseen changes, send an If-Unmodified-Since header with the time of the last read. Salesforce then returns 412 Precondition Failed if the record changed after that time.