Sub topic 6
Creating a record with POST
This chapter covers the create operation: sending a POST request to an sObject resource, reading the response, and handling the failures you will meet most often. It assumes you can already obtain an access token, know your instance URL and API version, and understand objects, fields, and record IDs. The earlier chapters on authentication and resource URLs cover those topics. Here they are used without being re-explained.
The working model
To create a record, you send a POST request to the collection URL for one sObject type. The body is a JSON object whose keys are field API names and whose values are the field values. Salesforce validates the body, runs the same save logic as any other create (validation rules, duplicate rules, triggers, flows), and inserts the record. It then returns the new record ID.
The URL has no record ID because the record does not exist yet:
POST {instance_url}/services/data/{version}/sobjects/{SObjectName}The sequence looks like this:
Sending the request with curl
This request creates an Account. The three exports hold the values for your org.
export SF_INSTANCE_URL="https://MyDomain.my.salesforce.com"
export SF_ACCESS_TOKEN="<access token>"
export SF_API_VERSION="v60.0"
curl -X POST "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/sobjects/Account" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"Name": "Acme Corp", "Industry": "Technology"}'Each part of the request does a specific job:
-X POSTselects the create operation. A GET on the same URL does not read a record. It returns a summary of the object, covered in the describe chapter.Authorization: Bearer ...carries the OAuth access token.Content-Type: application/jsontells Salesforce how to parse the body. Without it, Salesforce may reject the request with a 415 status (UNSUPPORTED_MEDIA_TYPE).- The body keys are API names, such as
NameandIndustry. For custom fields, use the full API name including the suffix, such asRegion__c.
A successful call returns status 201 Created and this body:
{
"id": "001xx000003DGb2AAG",
"success": true,
"errors": []
}The id value shown is a placeholder. Real IDs are 18 characters and begin with the three-character key prefix of the object (001 for Account). Store the ID, because every later read, update, or relationship needs it.
Which fields to send
You send only the fields you want to set. Everything else takes its default value or stays empty. What you can send depends on four things.
- Required fields. Account requires
Name. Your org may add more required fields, such as a custom field or a field required on the page layout. Layout requirements do not apply to the API, but field-level requirements and validation rules do. - Field-level security. The user behind the token must have create access to the object and edit access to each field you send. A field the user cannot see is treated as nonexistent.
- Read-only fields. Fields such as
Id,CreatedDate,LastModifiedDate, and formula fields cannot be set on create. Sending them produces an error. The exception is audit fields such asCreatedDate, which a user with the "Set Audit Fields upon Record Creation" permission can set. - Data formats. Dates use
YYYY-MM-DD. Date-times use ISO 8601, such as2026-12-01T08:17:44.000Z. Booleans are JSONtrueandfalse, not strings. Picklist values must match an existing value exactly, including case, if the picklist is restricted.
Linking to other records
A lookup or master-detail field takes the ID of the related record. To create a Contact under the Account you just made, send the Account ID in AccountId:
curl -X POST "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/sobjects/Contact" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"FirstName": "Dana", "LastName": "Reyes", "AccountId": "001xx000003DGb2AAG"}'Contact requires LastName. The relationship field name is AccountId, not Account. The name without Id is the relationship name, which is used in queries and not when you write the lookup value.
Creating a record from Python
The same call in Python, wrapped in a small function you can reuse for any sObject:
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 create_record(sobject, fields):
"""Create one record and return its ID. Raise with the response body on failure."""
response = requests.post(
f"{base}/sobjects/{sobject}",
headers=headers,
json=fields,
timeout=30,
)
if response.status_code != 201:
raise RuntimeError(f"{response.status_code}: {response.text}")
body = response.json()
if not body.get("success"):
raise RuntimeError(f"Create reported failure: {body}")
return body["id"]
account_id = create_record("Account", {"Name": "Acme Corp", "Industry": "Technology"})
contact_id = create_record(
"Contact",
{"FirstName": "Dana", "LastName": "Reyes", "AccountId": account_id},
)
print(account_id, contact_id)Three details are worth noting:
- Passing
json=fieldsserializes the dictionary for you. Combined with theContent-Typeheader, this avoids hand-built JSON strings with quoting mistakes. - The code compares the status to 201 and does not rely on
response.ok. Any 2xx status would passok, but a create should return exactly 201. - The
timeoutargument matters. Without it,requestscan wait forever on a stalled connection.
Common errors
Failed creates return a JSON array of error objects. Reading these in depth is the subject of the error handling chapter. For now, learn to recognize the failures specific to creating records.
| Status | `errorCode` | Typical cause | Fix |
|---|---|---|---|
| 400 | `REQUIRED_FIELD_MISSING` | A required field such as `Name` is absent or null | Add the field named in `fields` |
| 400 | `INVALID_FIELD` | Misspelled field, a custom field without `__c`, or a field the user cannot see | Check the API name and field-level security |
| 400 | `INVALID_FIELD_FOR_INSERT_UPDATE` | The body includes a read-only field such as `Id` | Remove the field |
| 400 | `INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST` | Value is not in a restricted picklist | Use an existing picklist value |
| 400 | `FIELD_CUSTOM_VALIDATION_EXCEPTION` | A validation rule rejected the data | Fix the data to satisfy the rule's message |
| 400 | `DUPLICATES_DETECTED` | A duplicate rule that blocks creation matched an existing record | Reuse the existing record or review the rule |
| 401 | `INVALID_SESSION_ID` | The access token is expired or invalid | Get a new token, then retry |
| 403 | `INSUFFICIENT_ACCESS_OR_READONLY` | The user lacks create permission on the object | Change the profile or permission set |
| 404 | `NOT_FOUND` | The sObject name or URL path is wrong | Check spelling and API version |
| 415 | `UNSUPPORTED_MEDIA_TYPE` | Missing or wrong `Content-Type` | Send `application/json` |
A rejected create is atomic for that one record. Either the record is saved or nothing is. You do not need to clean up after a 400.
The reverse case needs attention. If a request times out or the connection drops after Salesforce received it, you cannot tell whether the record was saved.
Retries and duplicates
POST is not idempotent. Sending the same create twice makes two records. Repeating a request is harmless for a read, but for a create it is a common source of duplicate data. Follow these rules:
- Retry automatically only on failures where Salesforce certainly did not save the record. A 401 after refreshing the token is the standard case.
- After a timeout, query for the record before sending the create again. If your data has a natural unique key, search on it.
- If your source system has a stable unique key, add an external ID field in Salesforce and use an upsert instead of a plain create. A repeated upsert updates the same record. The upsert chapter covers this.
Side effects of a create
A create through the API is a full save, not a raw database insert. Before you return the 201 to a caller, remember that:
- Before-save and after-save triggers, record-triggered flows, and workflow rules all run. Their changes (a field defaulted by a trigger, an owner assigned by a rule) are not in the 201 response. A follow-up GET shows them.
- If an automation throws an error, the whole create fails with an error such as
CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, and nothing is saved. - Every call counts against your org's daily API request limit, however small the body is. The limits chapter covers how to check and reduce usage.
The response tells you only that the record exists and what its ID is. To see the stored values, read the record back with GET.
Summary of the create contract
- Method and URL: POST to
/services/data/{version}/sobjects/{SObjectName}. - Headers:
Authorization: Bearer <token>andContent-Type: application/json. - Body: JSON object of API field names and values, with at least the required fields.
- Success: 201 with
id,success: true, and an emptyerrorsarray. - Failure: a 4xx status with a JSON array of
messageanderrorCodeobjects. Nothing is saved. - Retrying a create can duplicate the record.
Exercise
Your script posts {"Name": "Globex", "Industry": "Energy"} to /sobjects/Account. The call times out after 30 seconds and your retry logic immediately sends the same request again, which returns 201. Later, the team finds two "Globex" accounts. Explain why this happened, and name two ways to prevent it.
Show answer
The first request probably reached Salesforce and was saved, but the response was lost, so the client saw a timeout. POST is not idempotent, so the retry created a second record. To prevent it, either (1) query for an Account named Globex (or one with the source system's unique key) after a timeout and before retrying, or (2) put an external ID field on Account and use an upsert by external ID, so a repeated request updates the same record instead of creating another.
Exercise
A POST to /sobjects/Contact with the body {"FirstName": "Dana", "AccountId": "001xx000003DGb2AAG"} returns status 400. Which error code do you expect, and what is the fix?
Show answer
Expect REQUIREDFIELDMISSING, with "LastName" listed in the fields array, because LastName is required on Contact. Add a "LastName" value to the body and send the request again.