Sub topic 11
Discovering fields and required values with describe
This chapter assumes you can build a sObject resource URL, send an authenticated request with a bearer token, and read a JSON response. It also assumes you have created a record with POST and seen a REQUIRED_FIELD_MISSING error. If those steps are new to you, review the chapters on authentication, resource URLs, and error handling first.
By the end you will be able to ask Salesforce what an object looks like before you write to it. You will use that answer to work out which fields are required, which are writable, and which values are allowed.
Why describe exists
Every Salesforce org is customized. An admin can add custom fields, make a field required, restrict a picklist, or change what a profile can see. A payload that works in a Developer Edition org can fail in production because of any of these changes.
The describe resource returns the structure of an object as JSON. You can read the answer in code instead of guessing, copying a field list from documentation, or learning about a rule from a failed request.
Describe reports what the org and the calling user allow right now. It reflects custom fields, field-level security, and record types visible to the authenticated user. That makes it more accurate than static documentation for your org.
The two describe resources
There are two resources for an object, and they answer different questions.
| Resource | URL path | Returns |
|---|---|---|
| Basic information | `/sobjects/Account` | Object summary and a list of recently viewed records |
| Describe | `/sobjects/Account/describe` | Full metadata: fields, record types, child relationships, URLs |
A GET on the plain sObject URL is not a record lookup. It returns basic information about the object. The /describe path returns the full field list, and that is the one this chapter uses.
There is also a global describe at /sobjects. It lists every object available to the user, with a short summary for each. Use it to find out whether an object exists in the org and what its API name is.
export SF_INSTANCE_URL="https://MyDomain.my.salesforce.com"
export SF_ACCESS_TOKEN="<access token>"
export SF_API_VERSION="v60.0"
curl "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/sobjects/Account/describe" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN"The response is large. An Account describe in a typical org is hundreds of kilobytes, because it lists every field with its full metadata. Save it to a file or filter it before reading it.
What the response contains
The top level of the describe response holds object-wide properties. The ones you will use most are these.
nameandlabel: the API name (Account) and the display name.createable,updateable,deletable,queryable: whether the calling user can create, update, delete, or query this object.fields: an array with one entry per field.recordTypeInfos: the record types available to the user.childRelationships: related objects that point to this one.
Check createable and updateable before you build a form or a sync job. If createable is false, a POST fails no matter how correct the payload is.
Reading a field entry
Each entry in fields describes one field. These are the properties that decide how you write to it.
| Property | Meaning |
|---|---|
| `name` | API name to use in payloads and queries, for example `Industry` or `Region__c` |
| `label` | Display name shown in the UI |
| `type` | Data type, such as `string`, `picklist`, `boolean`, `reference`, `date`, `currency` |
| `createable` | `true` if you can set the field when creating a record |
| `updateable` | `true` if you can change the field on an existing record |
| `nillable` | `true` if the field may be empty |
| `defaultedOnCreate` | `true` if Salesforce supplies a value when you omit it |
| `length` | Maximum length for text fields |
| `picklistValues` | Allowed values for picklist fields |
| `referenceTo` | Object names a reference field can point to |
| `externalId` | `true` if the field can be used for upserts by external ID |
| `unique` | `true` if values must be unique |
Two details trip people up. First, name is the API name, and for custom fields it ends in __c. Using the label in a payload gives an INVALID_FIELD or No such column error. Second, the createable and updateable flags are separate. A field such as CreatedDate is neither. An auto-number or formula field is readable but not writable. Many fields are createable but not updateable, and a PATCH that includes one of them fails.
Working out the required fields
Describe has no single required property. You derive it from three flags. A field must be supplied on create when all of the following are true:
createableistrue.nillableisfalse.defaultedOnCreateisfalse.
If a field is not nillable but is defaulted on create, Salesforce fills it in and you can omit it. If it is not createable, you cannot send it at all, so it is never your responsibility.
For Account, this rule returns Name. In an org where an admin has marked custom fields as required at the database level, you will see those too.
The rule has one limit. Describe reports database-level requirements. It does not report required fields enforced by page layouts, validation rules, or Flow. A page-layout requirement applies only in the UI, so the API accepts the record. A validation rule applies in the API, and it returns FIELD_CUSTOM_VALIDATION_EXCEPTION when it fails. Describe cannot predict that failure, so you still need error handling after you pre-check the payload.
Filtering describe output with Python
A short script turns the large response into a useful list. This one fetches the describe for any object, prints the required fields, and prints the picklist values for a chosen field.
import os
import sys
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}"}
def describe(sobject):
response = requests.get(
f"{base}/sobjects/{sobject}/describe",
headers=headers,
timeout=30,
)
if not response.ok:
raise RuntimeError(f"{response.status_code}: {response.text}")
return response.json()
def required_fields(meta):
return [
f["name"]
for f in meta["fields"]
if f["createable"] and not f["nillable"] and not f["defaultedOnCreate"]
]
def picklist_values(meta, field_name):
for f in meta["fields"]:
if f["name"] == field_name:
return [v["value"] for v in f["picklistValues"] if v["active"]]
raise KeyError(field_name)
if __name__ == "__main__":
sobject = sys.argv[1] if len(sys.argv) > 1 else "Account"
meta = describe(sobject)
print("createable:", meta["createable"])
print("required on create:", required_fields(meta))
if sobject == "Account":
print("Industry values:", picklist_values(meta, "Industry"))Run it with python describe_fields.py Account. For a standard Account it prints ['Name'] as the required list, followed by the active Industry values. The exact picklist values depend on your org.
The script filters picklist values on active. Each entry has value, label, and active. Inactive values stay in the list so that old records remain valid, but you should not send them on new records.
Picklists, restrictions, and record types
A picklist field can be restricted or unrestricted. A restricted picklist rejects any value that is not in the list. An unrestricted one can accept other values through the API, depending on org settings. The field entry reports this in restrictedPicklist.
Record types add another layer. Two record types on the same object can offer different picklist values, and the object-wide picklistValues list does not show that split. To get values for one record type, use the layout and record-type resources, or send a request for the record type and handle a INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST error. For a first integration, use the object-wide list and handle that error.
Dependent picklists need the same care. The field entry has a controllerName, and validFor data that encodes which values are allowed for each controlling value. Most integrations treat validFor as an advanced topic and rely on the API to reject invalid pairs.
Resolving reference fields
A reference field holds the ID of another record. The referenceTo array names the objects it can point to. For Account.OwnerId, it lists User (and sometimes Group). For Contact.AccountId, it lists Account.
When a field points to more than one object, referenceTo has several entries. That is a polymorphic relationship. You can not tell from the ID alone which object it is, but the first three characters of the ID, the key prefix, identify the object. Describe lists each object's prefix in keyPrefix.
Using describe in a workflow
The following sequence shows where describe fits in a create flow.
Caching and cost
Describe calls count toward your API request limit. They are also slow compared with a record read, because of the response size. Do not call describe before every create.
- Fetch describe once at startup or on a schedule, and keep it in memory or on disk.
- Refresh it when you see an
INVALID_FIELDerror, which suggests the schema changed. - Use the
If-Modified-Sinceheader on the describe request. If nothing changed, Salesforce returns304 Not Modifiedwith no body, which saves bandwidth.
The describe result depends on the user, so do not share one cached copy between integration users that have different permissions.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `NOT_FOUND` on `/describe` | Wrong object name, or the user cannot see the object | Check the API name with the global describe |
| Field missing from the `fields` array | Field-level security hides it from this user | Grant access or use a different user |
| `INVALID_FIELD` on create | Label used instead of API name, or a non-createable field sent | Use `name` and check `createable` |
| `INVALID_FIELD_FOR_INSERT_UPDATE` on PATCH | Field is createable but not updateable | Remove it from the update payload |
| Required list is empty but create fails | Validation rule, trigger, or flow enforces the rule | Read `errorCode` and `message` in the error body |
Summary of the decision rules
- Use
/sobjectsto find object names, and/sobjects/<Object>/describeto inspect one. - Send fields by
name, never bylabel. - Send a field on create only if
createableis true, and on update only ifupdateableis true. - A field is required when it is createable, not nillable, and not defaulted on create.
- Cache the result, and refresh it when errors suggest the schema changed.
Exercise
A describe response for a custom object shows a field with name "Region__c", createable true, updateable false, nillable false, and defaultedOnCreate false. Is the field required on create? Can you include it in a PATCH to change an existing record?
Show answer
Yes, it is required on create, because it is createable, not nillable, and not defaulted on create, so every POST must include it. No, it cannot be changed in a PATCH, because updateable is false. Sending it in an update fails with an error such as INVALIDFIELDFORINSERTUPDATE, so you must set the correct value when you create the record.
Exercise
Your create request for a Contact fails with FIELDCUSTOMVALIDATION_EXCEPTION, but your describe-based check found no missing required fields. Why did the check not catch it, and where do you find the cause?
Show answer
Describe reports database-level structure such as nillable and createable. It does not include validation rules, which run when the record is saved. The cause is in the error response: read the message in the error object, which holds the text of the failed rule, and check the validation rules for the object in Setup.