Sub topic 3
Building resource URLs: instance, version, and sObject
This chapter assumes you know basic HTTP (methods, headers, status codes), can read JSON, and already have an access token from the previous chapter. Here you will learn how every Salesforce REST API URL is assembled, which part of it can change, and the mistakes that produce confusing 404 and 400 responses.
The anatomy of a resource URL
Every record request goes to a URL built from four parts:
- The instance URL, which is the host of your org.
- The fixed path prefix
/services/data/. - The API version, such as
v60.0. - The resource path, such as
sobjects/Accountorquery.
Put together, the URL to create an Account looks like this:
https://MyDomain.my.salesforce.com/services/data/v60.0/sobjects/AccountThe access token authenticates the request. The URL tells Salesforce which org, which API behavior, and which object you mean. If any part is wrong, the request fails before your data is looked at.
The instance URL
The instance URL is the base address of your org. For most orgs it is your My Domain host, for example https://MyDomain.my.salesforce.com. A sandbox host usually contains the sandbox name, such as https://MyDomain--dev.sandbox.my.salesforce.com.
Do not guess this value and do not hard-code a generic host such as login.salesforce.com for data calls. The login host is for obtaining tokens. Data calls go to the instance URL. When you authenticate with OAuth 2.0, the token response includes an instance_url field, and that is the value to use as your base.
Store it in an environment variable so the same code works against a Developer Edition org, a sandbox, and production:
export SF_INSTANCE_URL="https://MyDomain.my.salesforce.com"
export SF_API_VERSION="v60.0"Watch for a trailing slash. If SF_INSTANCE_URL ends in /, concatenating /services/data/... produces a double slash. Strip it once when you load the value.
The API version
The version segment, such as v60.0, selects which release of the REST API handles the call. Salesforce publishes new versions several times a year. Each version keeps its behavior stable, so a script pinned to v60.0 keeps working the same way after the org itself is upgraded.
Points to keep in mind:
- The version is part of the path, so it is required.
/services/data/sobjects/Accountis not a valid resource URL. - Newer versions can add fields and resources. An object or field introduced in a later release will not appear if you call an older version.
- Old versions are eventually retired, and calls to a retired version fail. Review the pinned version periodically.
- Pin one version in a single configuration value. Do not scatter literals through your code.
To see which versions your org supports, request the root data path without a version:
curl "$SF_INSTANCE_URL/services/data/" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN"The response is a JSON array. Each element has a version, a label, and a url. You can pick one, usually the latest, and use its url as your versioned base.
A request to a versioned base returns a map of the resources available at that version:
curl "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN"The response lists keys such as sobjects, query, and limits, each with its URL. This is a useful first call when you want to confirm that the host, version, and token all work together.
The sObject resource paths
Record operations hang off the sobjects resource. A path has up to three levels:
| Path | Purpose |
|---|---|
| `/sobjects` | Lists the objects available to the user |
| `/sobjects/Account` | Create a record (POST) or get basic object info (GET) |
| `/sobjects/Account/describe` | Full metadata for the object, including fields |
| `/sobjects/Account/001xx000003DGb2AAG` | Read (GET) or update (PATCH) one record |
| `/sobjects/Account/001xx000003DGb2AAG?fields=Name,Industry` | Read only the listed fields |
Two rules follow from this table. When you create a record, the URL names only the object, because the record does not have an ID yet. When you read or update, the URL ends with the record ID. The same record URL serves several HTTP methods, and the method decides the operation. The next chapters cover the method and status code pairings.
Object API names
The object segment is the API name, not the label shown in the Salesforce interface. Standard objects use their plain names, such as Account, Contact, and Opportunity. Custom objects end in __c, for example Invoice__c. Custom fields use the same suffix in JSON bodies and in the fields parameter, such as Region__c.
API names are not case sensitive for lookup in most cases, but use the exact casing that appears in Setup or in the describe output. This keeps your code consistent and avoids surprises in tools that compare strings.
If the name is wrong, Salesforce answers with 404 and an error such as NOT_FOUND with a message saying the requested resource does not exist. A missing __c on a custom object is the most common cause.
Namespaced objects
Objects and fields from a managed package carry a namespace prefix followed by two underscores, for example acme__Invoice__c. Use the full name in the URL.
Query parameters
Anything after ? is a query parameter. Parameters narrow or modify the request but do not change which resource you address. The fields parameter is one example. Separate multiple field names with commas and no spaces:
?fields=Name,Industry,Region__cValues must be URL encoded when they contain special characters. This matters most for SOQL, which contains spaces, quotes, and operators. In curl, --data-urlencode with -G handles this for you, and in Python the params argument of requests does the same. Avoid building these strings by hand.
Building URLs in code
Centralize URL construction in one place. The helper below validates its inputs, strips stray slashes, and returns a URL you can pass to any HTTP client.
import os
from urllib.parse import quote
def build_base(instance_url: str, version: str) -> str:
instance_url = instance_url.rstrip("/")
version = version.strip("/")
if not instance_url.startswith("https://"):
raise ValueError("instance URL must start with https://")
if not version.startswith("v"):
raise ValueError("version must look like v60.0")
return f"{instance_url}/services/data/{version}"
def sobject_url(base: str, sobject: str, record_id: str | None = None) -> str:
url = f"{base}/sobjects/{quote(sobject, safe='')}"
if record_id:
url += f"/{quote(record_id, safe='')}"
return url
base = build_base(
os.environ.get("SF_INSTANCE_URL", "https://MyDomain.my.salesforce.com"),
os.environ.get("SF_API_VERSION", "v60.0"),
)
print(sobject_url(base, "Account"))
print(sobject_url(base, "Account", "001xx000003DGb2AAG"))
print(sobject_url(base, "Invoice__c"))Running it prints:
https://MyDomain.my.salesforce.com/services/data/v60.0/sobjects/Account
https://MyDomain.my.salesforce.com/services/data/v60.0/sobjects/Account/001xx000003DGb2AAG
https://MyDomain.my.salesforce.com/services/data/v60.0/sobjects/Invoice__cEncoding each segment with quote prevents a value containing / or ? from changing the structure of the path.
Common errors and what they mean
| Symptom | Likely cause | Fix |
|---|---|---|
| 404 `NOT_FOUND` on a valid-looking object | Wrong API name, missing `__c`, or a version too old to know the object | Check the name in Setup or `/sobjects`, and raise the version |
| 404 on every call | Missing `/services/data/` or version segment | Compare your URL with the pattern above |
| 401 `INVALID_SESSION_ID` | Token expired, or the token belongs to a different org than the host | Refresh the token and confirm the instance URL matches it |
| Connection or DNS failure | Typo in the host, or a sandbox host used with a production token | Use the `instance_url` from the token response |
| 405 `METHOD_NOT_ALLOWED` | Method not supported on that path, such as POST to a record ID URL | POST to the object URL, PATCH the record URL |
| 400 `MALFORMED_ID` | Record ID has the wrong length or characters | Copy the ID exactly from the create response |
Record ID formats
Record IDs in a URL come in two forms: 15 characters, which are case sensitive, and 18 characters, which are case insensitive and include a three-character checksum. The REST API returns 18-character IDs. Prefer those, because comparing 15-character IDs in a case-insensitive system, such as a spreadsheet, can make two different records look identical. The first three characters are a key prefix that identifies the object type, so 001 means Account.
Exercise
A teammate's script sends a POST to https://MyDomain.my.salesforce.com/services/data/sobjects/Account and gets a 404. Name the problem, write the corrected URL for API version v60.0, and say which custom-object detail you would check if the same pattern failed for an object called Invoice.
Show answer
The URL is missing the API version segment. The corrected URL is https://MyDomain.my.salesforce.com/services/data/v60.0/sobjects/Account. For the custom object, check that the API name ends in __c (Invoice__c) and that any managed-package namespace prefix is included.
Exercise
You want to read only the Name and Region__c fields of the Account with ID 001xx000003DGb2AAG. Write the path and query string that follow the instance URL, using v60.0.
Show answer
/services/data/v60.0/sobjects/Account/001xx000003DGb2AAG?fields=Name,Region__c