Sub topic 5
Which HTTP method and status code goes with which operation
This chapter assumes you can read an HTTP request and response (method, headers, status code) and that you have an access token and an instance URL, as covered in the earlier chapters. Here you learn which method each record operation uses and which success status code to expect. You also learn how to treat a response that differs from what you expected.
Why the pairing matters
The Salesforce REST API follows HTTP conventions closely. The method tells the server what you want to do. The status code tells you what happened. If you check only for "no exception raised", you can miss real problems. A 204 is a success with no body, so code that calls .json() on it will crash. A 300 means your request matched several records, and many clients treat that as a success because it is not a 4xx or 5xx code.
The core mapping
The table covers the three operations this tutorial builds, plus delete and upsert for completeness.
| Operation | Method | URL shape | Success status | Success body |
|---|---|---|---|---|
| Create a record | POST | `/sobjects/Account` | 201 Created | JSON with `id`, `success`, `errors` |
| Read a record | GET | `/sobjects/Account/{id}` | 200 OK | The record as JSON |
| Update a record | PATCH | `/sobjects/Account/{id}` | 204 No Content | Empty |
| Delete a record | DELETE | `/sobjects/Account/{id}` | 204 No Content | Empty |
| Upsert by external ID | PATCH | `/sobjects/Account/ExtId__c/{value}` | 201 if created, 204 if updated | JSON on 201, empty on 204 |
Two details deserve attention.
- Create sends no ID, update requires one. POST goes to the object collection URL. PATCH goes to a URL that ends in a specific record ID.
- Update returns nothing. The API does not send the updated record back. If you need the new values, make a GET afterward.
Seeing the status code yourself
Do not guess what the API returned. With curl, print the status code on its own line using -w.
curl -s -o /dev/null -w "%{http_code}\n" \
-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"}'The flags -s -o /dev/null hide the progress meter and the body, so the only output is the code. A successful update prints 204. Use -i instead when you also want to read the response headers.
What each success code means
200 OK
The request succeeded and the body holds the result. You see it for GET on a record, for SOQL queries, and for describe calls. Parse the body as JSON.
201 Created
The server created a new resource. The body is JSON of this form:
{
"id": "001xx000003DGb2AAG",
"success": true,
"errors": []
}Store the id. Every later read or update needs it.
204 No Content
The server did what you asked and has nothing to send back. The body is empty by design. This is the normal success result for PATCH and DELETE on a record. A common bug is to write response.json() unconditionally. On a 204 it raises a decoding error even though the update worked.
Other success-like codes
- 304 Not Modified. You sent an
If-Modified-SinceorIf-None-Matchheader on a GET, and the record has not changed. There is no body. Use your cached copy. - 300 Multiple Choices. An external ID lookup matched more than one record. The body lists the matching record URLs. Your data has duplicates that you must fix. Do not retry blindly.
Failure codes you will meet with record calls
A failed request returns a JSON array of error objects with message and errorCode. Use the status code to decide the category, then read errorCode for the exact cause.
| Status | Typical cause | Example `errorCode` |
|---|---|---|
| 400 Bad Request | Malformed JSON, a missing required field, an invalid field value | `REQUIRED_FIELD_MISSING`, `MALFORMED_QUERY` |
| 401 Unauthorized | The access token is missing, expired, or revoked | `INVALID_SESSION_ID` |
| 403 Forbidden | The user lacks permission, or the org passed its API request limit | `INSUFFICIENT_ACCESS`, `REQUEST_LIMIT_EXCEEDED` |
| 404 Not Found | The record ID or the resource URL does not exist | `NOT_FOUND` |
| 405 Method Not Allowed | The method is not supported on that URL | `METHOD_NOT_ALLOWED` |
| 415 Unsupported Media Type | The body is not JSON or XML, or the `Content-Type` header is wrong | `UNSUPPORTED_MEDIA_TYPE` |
| 500 Internal Server Error | A server-side problem | `UNKNOWN_EXCEPTION` |
The later chapter on error handling goes through these in detail. For now, remember the split: 4xx codes mean your request needs to change, and 5xx codes may succeed on a retry.
Checking the response against the operation
The clearest defensive pattern is to say which status you expect for each call, and to treat anything else as an error. The script below does this for a create and an update, and it prints the status code for each step.
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")
base = f"{instance_url}/services/data/{version}"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
def expect(response, expected_status):
"""Return the response only if it has the status we expected."""
if response.status_code != expected_status:
raise RuntimeError(
f"Expected {expected_status}, got {response.status_code}: "
f"{response.text}"
)
return response
# POST should give 201 and a JSON body.
created = expect(
requests.post(
f"{base}/sobjects/Account",
headers=headers,
json={"Name": "Status Code Demo", "Industry": "Technology"},
timeout=30,
),
201,
).json()
account_id = created["id"]
print("create:", 201, account_id)
# PATCH should give 204 and an empty body.
patched = expect(
requests.patch(
f"{base}/sobjects/Account/{account_id}",
headers=headers,
json={"Industry": "Banking"},
timeout=30,
),
204,
)
print("update:", patched.status_code, repr(patched.text))The final line prints update: 204 ''. The empty string confirms that the update response carries no body.
An exact match against one status code is deliberately strict. It catches the 200 that you did not expect from a URL you built wrongly, and it catches the 300 that a looser check such as response.ok would let through. Use a looser check, such as accepting either 201 or 204, only for upserts, where both are valid.
A PATCH workaround for restricted clients
Some HTTP libraries, proxies, and older tools cannot send PATCH. Salesforce lets you send a POST and override the method with the _HttpMethod query parameter:
curl -X POST "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/sobjects/Account/001xx000003DGb2AAG?_HttpMethod=PATCH" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"Industry": "Banking"}'The server handles this as a PATCH, so you still get a 204 on success. Use this only when you cannot send a real PATCH. A normal PATCH is clearer to anyone reading your code or your logs.
Common mistakes
- Using PUT or POST to update. POST on a record URL is not an update. Without the
_HttpMethodoverride, you get an error such as 405. Use PATCH. - Sending the full record on PATCH. PATCH changes only the fields you send. Do not send read-only fields such as
Id,CreatedDate, orSystemModstamp. Salesforce rejects them with a 400. - Expecting a body from PATCH. A 204 has none. Read the record with GET if you need the stored values.
- Treating any 2xx as the same. A 201 gives you an ID and a 204 does not. Branch on the exact code when your logic depends on the result.
- Retrying a 400. The same request fails again. Fix the payload first. Retry only network failures, 5xx codes, and 403
REQUEST_LIMIT_EXCEEDEDafter a delay.
Summary
POST creates and returns 201 with an ID. GET reads and returns 200 with the record. PATCH updates and returns 204 with no body. Upsert uses PATCH on an external ID URL and returns 201 or 204. Check the exact status code, and parse a body only when the status code says one exists.
Exercise
You send PATCH /sobjects/Account/001xx000003DGb2AAG with {"Industry": "Banking"}. The call returns 204, but your code crashes with a JSON decoding error. What is wrong, and how do you fix it?
Show answer
The code calls response.json() on a 204 No Content response, which has an empty body. The update itself succeeded. Fix it by not parsing a body for PATCH. Check that the status code is 204 and continue. If you need the updated values, send a GET request to the same record URL.
Exercise
A script uses response.ok to detect success and sends GET /sobjects/Account/ExtId__c/A-100 (an external ID lookup). It reports success but the response body is a list of URLs and no record fields. What status code did it get, and what does it mean?
Show answer
It got 300 Multiple Choices. More than one Account has the external ID value A-100, and the body lists the URLs of the matching records. response.ok is true for any status below 400, so 300 passes. Check for the exact expected status (200 here), and fix the duplicate external ID values in the data.