Sub topic 8
Apex REST: custom endpoints for custom logic
This chapter assumes you can read basic Apex, know the REST resources covered earlier (query and sObject endpoints), and can obtain an OAuth access token. Apex REST lets you publish your own HTTP endpoints from inside Salesforce. The endpoints run Apex code, so an integration can call one URL and get a result that the standard REST API would need several calls to build.
What Apex REST is
Apex REST exposes an Apex class as a web service. You annotate the class with @RestResource and annotate its methods with HTTP verb annotations. Salesforce routes matching requests to those methods. Every endpoint lives under this path:
/services/apexrest/<urlMapping>The URL mapping is relative to /services/apexrest/. A class declared with urlMapping='/AccountSummary/*' answers at /services/apexrest/AccountSummary/{accountId}.
Callers authenticate the same way they do for the standard REST API. They send a bearer token from an OAuth 2.0 flow. The running user's profile, permission sets, and Apex class access decide who can call the endpoint.
When a custom endpoint is worth building
Standard REST resources work on one object or a small set of objects at a time. A custom endpoint fits when you need one of these:
- Server-side logic. Validation, calculations, or branching that should not live in every client.
- One call instead of many. Composite requests can chain calls, but each step is still a standard resource. Apex can run several queries and DML statements and return one response.
- A stable contract. The response shape is yours. You can hide field names, merge objects, and change the data model without breaking clients.
- Transaction control. Apex can use a savepoint and roll back all the work if one step fails.
Do not build a custom endpoint when a standard resource already does the job. Custom code costs more to write, test, deploy, and maintain.
A first endpoint
This is the example from the plan, shown with its pieces named.
@RestResource(urlMapping='/AccountSummary/*')
global with sharing class AccountSummaryResource {
@HttpGet
global static Account doGet() {
RestRequest req = RestContext.request;
String accountId = req.requestURI.substringAfterLast('/');
return [SELECT Id, Name, Industry FROM Account WHERE Id = :accountId];
}
}@RestResourcemarks the class and sets the URL mapping.- The class must be
global. Its methods must beglobal static. with sharingmakes the query respect the running user's record access. This matters for security, and the next section returns to it.RestContext.requestgives you the incoming request: URI, headers, parameters, and body.- The returned
Accountis serialized to JSON automatically.
Call it with a token:
curl "https://MyDomain.my.salesforce.com/services/apexrest/AccountSummary/001XXXXXXXXXXXXXXX" \
-H "Authorization: Bearer $ACCESS_TOKEN"If the Id matches no record, the query throws a QueryException. The caller gets an error response, and the section on error handling shows how to make that response meaningful.
HTTP method annotations
Each annotation can be used once per class. That means one @HttpGet, one @HttpPost, and so on.
| Annotation | HTTP method | Typical use |
|---|---|---|
| `@HttpGet` | GET | Read data |
| `@HttpPost` | POST | Create data or run an action |
| `@HttpPut` | PUT | Upsert or replace |
| `@HttpPatch` | PATCH | Partial update |
| `@HttpDelete` | DELETE | Delete |
Because each verb can appear only once, a class with several operations on the same path needs the method itself to branch on the URL. Alternatively, use separate classes with separate URL mappings.
Reading input
Input arrives in three places.
- Path. Parse
req.requestURI, as the first example does. - Query string. Use
req.params, aMap<String, String>. - Body. Use
req.requestBody, aBlob. Convert it withtoString()and deserialize it.
Apex can also bind a JSON body to method parameters. The parameter names must match the JSON keys. The example below uses that binding on a POST.
@RestResource(urlMapping='/AccountIntake/*')
global with sharing class AccountIntakeResource {
global class IntakeResponse {
global Boolean success;
global Id accountId;
global String message;
}
@HttpPost
global static IntakeResponse create(String name, String industry) {
IntakeResponse res = new IntakeResponse();
Savepoint sp = Database.setSavepoint();
try {
Account a = new Account(Name = name, Industry = industry);
insert a;
res.success = true;
res.accountId = a.Id;
res.message = 'Created';
} catch (DmlException e) {
Database.rollback(sp);
RestContext.response.statusCode = 400;
res.success = false;
res.message = e.getDmlMessage(0);
}
return res;
}
}A client sends this body:
{ "name": "Acme Corp", "industry": "Technology" }Binding is convenient for small, flat bodies. For nested or variable payloads, accept the raw body and call JSON.deserialize into a wrapper class. That also lets you validate the payload before use.
Controlling the response
If a method returns a value, Apex serializes it to JSON. For finer control, use RestContext.response.
RestResponse res = RestContext.response;
res.statusCode = 404;
res.addHeader('Content-Type', 'application/json');
res.responseBody = Blob.valueOf('{"error":"Account not found"}');When you write responseBody yourself, return void from the method. Otherwise the returned value is serialized and replaces what you set.
Error handling
An uncaught exception in an Apex REST method returns HTTP 500 with a generic error. Clients cannot tell a bad request from a server fault. Catch the exceptions you expect and set a status code that matches the cause.
@HttpGet
global static void doGet() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
res.addHeader('Content-Type', 'application/json');
String accountId = req.requestURI.substringAfterLast('/');
List<Account> rows = [
SELECT Id, Name, Industry
FROM Account
WHERE Id = :accountId
LIMIT 1
];
if (rows.isEmpty()) {
res.statusCode = 404;
res.responseBody = Blob.valueOf(JSON.serialize(
new Map<String, String>{ 'error' => 'Account not found' }));
return;
}
res.statusCode = 200;
res.responseBody = Blob.valueOf(JSON.serialize(rows[0]));
}Assigning the query to a List avoids the QueryException that a single-record query throws when nothing matches. Note that an invalid Id string in the URL can still fail the query. Validate the format first if clients are untrusted.
A consistent error shape helps callers. Pick one structure, such as { "error": "...", "code": "..." }, and use it everywhere.
Security
Apex REST code runs in system context by default. That has consequences you must handle yourself.
- Sharing. Declare
with sharingso record-level access follows the running user. Without it, the class may expose records the caller cannot see.inherited sharingis also an option when the class should follow its caller, though a REST entry point has no calling Apex, sowith sharingis the clearer choice. - Field and object permissions. Sharing does not enforce field-level security or object permissions. Add
WITH USER_MODEto your SOQL, orWITH SECURITY_ENFORCED, and run DML withas user. - Input. Use bind variables (
:accountId) in static SOQL. If you must build dynamic SOQL, escape values withString.escapeSingleQuotes. - Class access. Users reach the endpoint only if their profile or a permission set grants access to the Apex class. Grant it to the integration user and to no one else.
Here is the earlier query with permissions enforced:
List<Account> rows = [
SELECT Id, Name, Industry
FROM Account
WHERE Id = :accountId
WITH USER_MODE
LIMIT 1
];Limits and cost
An Apex REST call is one API request against your org's daily API allocation. Inside the method, ordinary Apex governor limits apply, such as the cap on SOQL queries and DML statements per transaction. A custom endpoint can hide a lot of work behind one request. That is its strength, but a method that loops over many records and runs a query inside the loop will fail on limits at modest volumes.
Design for bulk inside the method:
- Query once, outside loops, and use maps to look up related rows.
- Collect records in a list and run one DML statement.
- Keep the response small. Return what the caller needs.
For loads of thousands of records, an endpoint is the wrong tool. Use Bulk API 2.0, covered in an earlier chapter.
Testing and deployment
Apex requires test coverage before code reaches production, so every endpoint needs a test class. You can call the method directly after building a request and response.
@IsTest
private class AccountSummaryResourceTest {
@IsTest
static void returnsAccount() {
Account a = new Account(Name = 'Test Co', Industry = 'Technology');
insert a;
RestRequest req = new RestRequest();
req.requestURI = '/services/apexrest/AccountSummary/' + a.Id;
req.httpMethod = 'GET';
RestContext.request = req;
RestContext.response = new RestResponse();
Account result = AccountSummaryResource.doGet();
System.assertEquals('Test Co', result.Name);
}
}The test sets RestContext.request and RestContext.response by hand, because no real HTTP call happens. Test the error paths too, such as a missing record and a bad payload.
Versioning
Apex REST endpoints are not versioned by Salesforce. The API version in the path (/services/data/v60.0/) applies to standard resources only. If you change the response shape, you can break existing clients. Put a version in the URL mapping, such as /v1/AccountSummary/*, and publish /v2/... as a new class when the contract changes.
How the pieces fit
The diagram shows the path of a request.
Common mistakes
- Forgetting
global. The class and its annotated methods will not compile without it. - Two methods with the same annotation. Only one
@HttpGetis allowed per class. - Returning a value and setting
responseBody. The return value wins. Usevoidwhen you build the response yourself. - Skipping
with sharingand user mode. The endpoint then returns data the caller should not see. - Relying on uncaught exceptions. Callers get a 500 with no useful detail.
- Queries and DML inside loops. These hit governor limits at small volumes.
- Changing a live contract. Existing clients break. Version the URL instead.
Summary
Apex REST turns an Apex class into an HTTP endpoint under /services/apexrest/. Use it when an integration needs custom logic, one call in place of several, or a stable contract. Enforce sharing and field-level security yourself, return clear status codes, keep work bulk-safe, test every path, and version the URL.
Exercise
A client calls your Apex REST endpoint with an Id that matches no Account. The method runs Account a = [SELECT Id FROM Account WHERE Id = :accountId]; and the client receives HTTP 500. How do you change the code so the client gets a clear 404, and which return type should the method use?
Show answer
Query into a List<Account> with LIMIT 1 and check isEmpty(). If it is empty, set RestContext.response.statusCode = 404, write a JSON error to RestContext.response.responseBody, and return. Use a void return type, because a returned value would replace the body you set by hand.
Exercise
Your endpoint is declared global class without a sharing keyword, and its SOQL has no user-mode clause. A user with limited access calls it. What risk does this create, and what two changes reduce it?
Show answer
The class runs in system context, so it can return records and fields the caller is not allowed to see. Declare the class with sharing to enforce record-level access, and add WITH USER_MODE to the SOQL to enforce object and field permissions.
Exercise
An integration needs to load 200,000 Contacts nightly. A teammate proposes an Apex REST endpoint that accepts batches and inserts them. Which API fits better, and why?
Show answer
Bulk API 2.0. It processes large volumes asynchronously and handles job tracking and per-record results. An Apex REST endpoint is limited by governor limits per transaction and by one synchronous request per batch, so it suits small, logic-heavy calls rather than bulk loads.