Sub topic 2
Defining a resource with @RestResource
This chapter assumes you can write Apex classes with static methods, run SOQL queries, and read an HTTP request line. You will turn an ordinary Apex class into a REST resource that Salesforce serves at its own URL.
What a resource is
A resource is an Apex class that Salesforce exposes at a URL. You mark the class with the @RestResource annotation and give it a urlMapping. When a request arrives whose path matches that mapping, Salesforce runs the matching method in your class.
Every custom service lives under one fixed prefix, /services/apexrest. The mapping you write is appended to it.
A minimal resource
@RestResource(urlMapping='/v1/Accounts/*')
global with sharing class AccountRestService {
@HttpGet
global static Account getAccount() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
String accountId = req.requestURI.substringAfterLast('/');
List<Account> rows = [
SELECT Id, Name, Industry
FROM Account
WHERE Id = :accountId
WITH USER_MODE
LIMIT 1
];
if (rows.isEmpty()) {
res.statusCode = 404;
return null;
}
return rows[0];
}
}Three parts of this class matter for defining the resource:
@RestResource(urlMapping='/v1/Accounts/*')registers the class. The full URL ishttps://MyDomainName.my.salesforce.com/services/apexrest/v1/Accounts/001XXXXXXXXXXXXXXX.globalon the class and on each handler method. Apex REST requires it.staticon every handler method. Salesforce does not create an instance of your class, so the handlers cannot rely on instance state.
How URL mapping works
The urlMapping value follows a few rules.
- It must start with a slash. Salesforce adds the
/services/apexrestprefix for you, so do not include it. - It can end with a wildcard,
*. With/v1/Accounts/*, a request to/v1/Accounts/001...matches, and so does any longer path under it. Your code reads the part the wildcard covers fromRestContext.request.requestURI. - Matching is case-sensitive.
/v1/Accounts/*does not match/v1/accounts/001.... - It is limited to 255 characters.
Without a wildcard, the mapping matches only that exact path. This suits collection endpoints like /v1/Accounts, where no record Id follows.
Sharing and the class declaration
The class declares with sharing, so record visibility follows the calling user. The query adds WITH USER_MODE, which also enforces object permissions and field-level security. Apex REST classes run in system context by default. Leaving out both of these would let any authorized caller read records they should not see. Chapter coverage of this topic comes later in the tutorial. For now, make with sharing your default.
Common errors
| Symptom | Likely cause |
|---|---|
| Save fails on the class | Class or method is not `global`, or a handler is not `static` |
| 404 on a request you expect to work | Case mismatch, or the mapping includes `/services/apexrest` |
| Handler returns an unexpected value | Path read with the wrong segment, for example without `substringAfterLast` |
| Two handlers for the same verb | A class can have only one method per HTTP annotation |
Because each class allows one method per verb, a resource that needs several GET behaviors must branch inside a single handler, or you should split it into separate resource classes with different mappings.
Try it
Deploy the class, obtain an access token, and call the endpoint.
curl -H "Authorization: Bearer $ACCESS_TOKEN" \
"https://MyDomainName.my.salesforce.com/services/apexrest/v1/Accounts/001XXXXXXXXXXXXXXX"Salesforce serializes the returned Account to JSON automatically. A bad Id returns the 404 the handler sets.
Exercise
A teammate writes @RestResource(urlMapping='/services/apexrest/v1/Orders/*') and requests /services/apexrest/v1/Orders/123, but gets a 404. What is wrong, and what is the corrected mapping?
Show answer
The mapping repeats the /services/apexrest prefix, which Salesforce already adds, so the real path would be /services/apexrest/services/apexrest/v1/Orders/.... The corrected mapping is /v1/Orders/*.