A REST API in Salesforce lets external applications send and receive data using standard web protocols like HTTP. For example, a mobile app can fetch a list of recent opportunities by sending a GET request to https://yourdomain.my.salesforce.com/services/data/v58.0/sobjects/Opportunity. This enables real-time sync between Salesforce and other systems without building custom connectors.

How Does the REST API Work in Salesforce?

The REST API follows standard REST principles: you use HTTP methods (GET, POST, PATCH, DELETE) to interact with Salesforce resources like records, objects, or metadata. Each request includes an authentication token, a URL that points to a specific resource, and optionally a JSON body for data you’re sending. Salesforce responds with JSON-formatted data and HTTP status codes indicating success or error.

You access REST endpoints through endpoints like /services/data/vXX.0/, where vXX.0 is the API version. For example, to retrieve an account record, you send a GET request to /services/data/v58.0/sobjects/Account/001XXXXXXXXXXXX. Salesforce returns fields like Id, Name, and CreatedDate in the response body.

Authentication uses OAuth 2.0. You obtain an access token by sending credentials to the auth endpoint (e.g., https://login.salesforce.com/services/oauth2/token), then include that token in the Authorization header as Bearer <token>. Without a valid token, Salesforce returns a 401 Unauthorized error.

What Are the Common REST Endpoints and Operations?

Here are the most frequently used REST endpoints and what they do:

  1. /services/data/vXX.0/sobjects/: Use this to work with standard and custom objects. For example, a POST to /services/data/v58.0/sobjects/Contact creates a new contact.
  2. /services/data/vXX.0/query/?q=SOQL: Use this to run SOQL queries and retrieve multiple records. Example: GET /services/data/v58.0/query/?q=SELECT+Id,Name+FROM+Account+WHERE+CreatedDate+>+2024-01-01 returns accounts created this year.
  3. /services/data/vXX.0/queryAll/: Same as /query/, but includes soft-deleted records and archived data.
  4. /services/data/vXX.0/composite/: Lets you combine multiple operations in one request—for example, create an account and two related contacts in a single call.
  5. /services/data/vXX.0/sobjects/Account/describe/: Returns metadata about the Account object, including field names, types, and required flags.

Each operation must respect Salesforce’s object and field-level security. If your集成 user lacks read access to a field, it won’t appear in the response—even if the query explicitly requests it.

How Do You Handle Errors?

REST API responses include error codes and messages in JSON. Common errors include:

  • 400 Bad Request: The request body is malformed or missing required fields (e.g., no Name on Account creation).
  • 401 Unauthorized: The access token is missing, expired, or invalid.
  • 403 Forbidden: The user has access but not to this specific object or record.
  • 404 Not Found: The record ID doesn’t exist or the endpoint is wrong.
  • 429 Too Many Requests: You’ve hit the daily or per-hour limit (e.g., 15,000 REST API calls per license per 24 hours).

Each error response includes a code (like INVALID_FIELD) and a message describing what went wrong. For example: {"message":"No such column 'CustomField__c' on sobject of type Account"}. Use this to debug field names or object typos.

What Are the Limits and Performance Rules?

Every Salesforce org has REST API call limits. A standard license allows 15,000 API calls per 24 hours. Enterprise and Unlimited editions get more, based on the number of user licenses. You can check your remaining calls in Setup > System Log > API Usage. If you exceed the limit, subsequent requests return 429 errors for 24 hours.

Response times vary by complexity and org load. Simple record retrieves (e.g., GET sobjects/Account/001...) typically return in under 200 ms. Complex SOQL queries with joins or large result sets may take several seconds. To stay responsive, use the queryMore endpoint for batches over 2,000 records, or filter results with WHERE clauses and LIMIT.

Some endpoints support pagination. For example, a query returns 2,000 records with a nextRecordsUrl field. To get the next batch, send a GET to that URL (not a new query). Do not modify the URL—Salesforce generates it with the correct continuation token.

How Do You Test a REST API Call in Salesforce?

You can test REST API calls directly in Salesforce using the Developer Console or Workbench. In Developer Console, go to Debug > Open Execute Anonymous Window and use the following Apex code to perform a simple GET:

HttpRequest req = new HttpRequest();
req.setEndpoint('callout:My_Named_Credential/sobjects/Account?limit=5');
req.setMethod('GET');
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getBody());

This requires a named credential called My_Named_Credential that stores your auth settings. Alternatively, use Salesforce Workbench (workbench.developerforce.com): log in, choose REST Explorer from the Utilities menu, then type a query like /services/data/v58.0/sobjects/Account and click Execute. This shows live JSON results and response headers.

Third-party tools like Postman or curl also work. In Postman, set the method to GET, enter the full URL, and add the Authorization header with Bearer <token>. For POST, include a JSON body like {"Name":"Test Account","Phone":"555-1234"} and set Content-Type to application/json.

What Common Problems Do People Face?

Many integration issues come from misconfigurations or overlooked details. Here’s what to check first:

  • Authentication: Ensure the access token is still valid. Tokens expire after two hours unless refreshed with the refresh_token grant.
  • Field names: Custom fields must end in __c (e.g., Custom_Field__c), not __r (which is for relationships).
  • Object permissions: The user profile or permission set must grant Read/Create/Edit access to the object.
  • API version mismatch: Using v40.0 endpoints with v58.0 syntax (or vice versa) causes 400 errors.
  • HTTPS only: Salesforce rejects unencrypted HTTP requests—even localhost must use https://.

Another frequent mistake is sending large JSON payloads in a single request. Salesforce limits request bodies to 10 MB and query results to 2,000 records per batch. For bulk data, use the Bulk API instead of REST.

When Should You Use REST Instead of Other APIs?

REST is ideal when:

  • You need simple, stateless operations (e.g., fetching a list of leads or updating a single contact).
  • You’re building a web or mobile app that already uses JSON and HTTP.
  • You want lightweight integrations—REST requires less boilerplate than SOAP.

REST is not ideal for:

  • Bulk data loads over 10,000 records (use Bulk API).
  • Real-time processing with strict latency requirements (REST has more overhead than Platform Events).
  • Complex transactions requiring transaction control (REST does not support savepoints or rollbacks).

Remember: REST is read/write, not write-only. You can create, read, update, and delete records, but each request is independent—Salesforce does not maintain session state between calls.

How Do You Secure REST API Calls?

Security starts with strong authentication. Always use OAuth 2.0 with a refresh token flow, never username/password in code. Store tokens in encrypted storage (e.g., Heroku Secrets, AWS Secrets Manager). For external users, create a dedicated profile with minimal object access and restrict IP ranges in Session Settings > Login IP Ranges.

Validate all input data before sending it to Salesforce. Never trust user-submitted JSON—check field types, lengths, and required flags. For example, if a Phone field expects 10 digits, reject inputs with letters or extra characters before making the API call.

Use named credentials in Salesforce to manage endpoints and auth tokens. This keeps passwords and tokens out of Apex code and lets admins rotate credentials without redeploying. To set it up: Setup > Named Credentials > New, enter the base URL (e.g., https://login.salesforce.com), and choose OAuth 2.0 as the authentication protocol.

What Follow-Up Questions Do People Have?

How Do You Refresh an Expired Access Token?

Send a POST to https://login.salesforce.com/services/oauth2/token with grant_type=refresh_token, client_id, client_secret, and refresh_token in the body. The response includes a new access_token and token_type. Do not reuse the old token—Salesforce invalidates it after refresh.

Can You Use REST API with Sandbox Orgs?

Yes. Use the sandbox’s login URL (e.g., https://test.salesforce.com) and append /services/data/vXX.0 to the endpoint. Make sure your connected app’s callback URL matches the sandbox domain, and update the named credential endpoint if used.

What Happens If You Try to Update a Read-Only Field?

Fields like CreatedDate, LastLoginDate, or SystemModstamp return a 400 error with message "cannot modify read-only field". Check the field’s describe metadata (GET /services/data/vXX.0/sobjects/Account/describe) to see isCreateable and isUpdateable flags before sending updates.