Sub topic 8
Apex REST: custom endpoints for custom logic
This chapter assumes you can read basic Apex, know how the REST API authenticates with an OAuth access token, and understand SOQL. Here you will see when a custom endpoint is worth writing and how to build one.
Why write a custom endpoint
The standard REST API exposes records one object at a time. Some integrations need more than that:
- Several queries and updates that must behave as one operation.
- Business rules that should live in Salesforce, not in every client.
- A response shaped for one consumer, not the full record.
Apex REST lets you publish an Apex class as an HTTP endpoint. The caller makes one request. Your code runs server-side and returns the result.
A first endpoint
An Apex REST class needs three things:
- The
@RestResourceannotation with aurlMapping. - A
globalclass. - Methods marked with an HTTP annotation:
@HttpGet,@HttpPost,@HttpPatch,@HttpPut, or@HttpDelete.
@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];
}
}The endpoint is available at /services/apexrest/AccountSummary/{accountId}. The * is a wildcard, and the urlMapping is case-sensitive. Each class can have only one method per HTTP verb.
Call it like any other REST resource:
curl "https://MyDomain.my.salesforce.com/services/apexrest/AccountSummary/$ACCOUNT_ID" \
-H "Authorization: Bearer $ACCESS_TOKEN"Handling errors yourself
The example above fails badly for an unknown Id. The query throws a QueryException, and the caller gets a generic 500 response. Set the status code yourself so clients can tell a bad request from a server fault:
@RestResource(urlMapping='/AccountSummary/*')
global with sharing class AccountSummaryResource {
@HttpGet
global static Account doGet() {
RestRequest req = RestContext.request;
String accountId = req.requestURI.substringAfterLast('/');
List<Account> rows = [
SELECT Id, Name, Industry FROM Account WHERE Id = :accountId
];
if (rows.isEmpty()) {
RestContext.response.statusCode = 404;
return null;
}
return rows[0];
}
}Common mistakes
- Ignoring sharing. Apex runs in system mode by default. Declare
with sharingand useWITH USER_MODEin queries, or the endpoint may expose records the caller cannot normally see. - Missing access. The calling user needs Apex class access through a profile or permission set. The OAuth connected app needs a scope such as
api. - Skipping tests. Deploying to production requires Apex test coverage. Write tests that set
RestContext.requestandRestContext.response. - Forgetting limits. Each call counts against API limits. Your code also runs under Apex governor limits, such as the cap on SOQL queries per transaction.
- Changing the contract. Standard REST resources carry an API version in the URL. Your custom endpoint does not, so a change affects every caller at once. Many teams put a version in the
urlMapping, such as/v1/AccountSummary/*.
When to choose it
Use standard REST for plain record access, and Composite when you only need to combine standard calls. Choose Apex REST when the logic itself must run inside Salesforce. Custom endpoints cost more to maintain, because you own the code, the tests, and the contract.
Exercise
A client needs to create an Account, check a custom approval rule, and create a related Contact in one transaction. The approval rule lives in Apex. Which API fits best, and why?
Show answer
Apex REST. A Composite request can chain standard record calls, but it cannot run your custom approval rule. An Apex REST method can hold the rule and do all the DML in one transaction. The method should use with sharing and set clear status codes on failure.