Sub topic 2
Defining a resource with @RestResource
This chapter covers how a plain Apex class becomes an HTTP endpoint. It explains how the URL mapping is built, how Salesforce picks a class for an incoming request, and which mistakes cause the usual 404 and 405 responses. It assumes you can write Apex classes and static methods, run SOQL and DML, and read HTTP status codes and JSON. It also assumes you know how profiles and permission sets grant access. The handler methods (@HttpGet and the others) get their own chapter, so this one uses them only as needed.
What the annotation does
@RestResource is a class-level annotation. It tells the platform that the class is an Apex REST resource and which URL path it answers. Every Apex REST service lives under one fixed base path:
https://MyDomainName.my.salesforce.com/services/apexrest/Your urlMapping is appended to that base. With urlMapping='/v1/Accounts/*', the service answers requests such as /services/apexrest/v1/Accounts/001XXXXXXXXXXXXXXX.
Here is a minimal complete resource:
@RestResource(urlMapping='/v1/ping')
global with sharing class PingRestService {
@HttpGet
global static String ping() {
return 'pong';
}
}After you save this class, a GET request to /services/apexrest/v1/ping returns the JSON string "pong". There is nothing to register and no separate deployment step. Saving a valid annotated class publishes the endpoint, and the class name plays no part in the URL.
Rules for the class declaration
The platform enforces several rules when you save the class:
- The class must be
global. Apublicclass with@RestResourcedoes not compile. - Each handler method must be
global static. The platform calls handlers without creating an instance, so instance methods and instance state do not work. urlMappingis required and must start with/.- The mapping is limited to 255 characters.
- Each mapping can belong to only one class in the org. A second class that declares the same
urlMappingis rejected. - A class can have at most one method for each HTTP annotation. Two
@HttpGetmethods in one class are an error.
The global requirement matters if you package your code. Global members become part of a managed package's public contract and are hard to remove later. Keep the class thin and put business logic in a separate class that can stay public.
How the URL mapping works
The urlMapping value is a path pattern. It can be an exact path or contain the wildcard *.
| `urlMapping` | Matches | Typical use |
|---|---|---|
| `/v1/ping` | Only `/v1/ping` | A single fixed endpoint |
| `/v1/Accounts/*` | `/v1/Accounts/001...` and other paths under `/v1/Accounts/` | Records addressed by an Id in the path |
| `/v1/*` | Any path starting with `/v1/` | A catch-all for a whole API version |
Three details cause most mapping bugs.
- Matching is case-sensitive. A resource mapped to
/v1/Accounts/*does not answer/v1/accounts/001.... Pick a casing convention and keep to it. - The wildcard is not a parameter. Salesforce does not extract the value for you. Inside the handler you read it from
RestContext.request.requestURI, as the next section shows. - The mapping excludes the query string. In
/v1/Accounts/001...?fields=Name, only the path is matched. The query string reaches your code throughRestContext.request.params.
Which class wins when mappings overlap
You can have several resource classes whose mappings overlap. Salesforce resolves a request in this order:
- If a mapping equals the request path exactly, that class handles the request.
- Otherwise, among all wildcard mappings that match, the longest mapping string wins.
- If nothing matches, the platform returns 404.
The following diagram shows that decision.
This lets you give one path special treatment without touching the general resource. Suppose you already have AccountRestService mapped to /v1/Accounts/*. You can add a second class for a reporting endpoint:
@RestResource(urlMapping='/v1/Accounts/summary')
global with sharing class AccountSummaryRestService {
@HttpGet
global static Map<String, Integer> getSummary() {
Integer total = [SELECT COUNT() FROM Account WITH USER_MODE];
return new Map<String, Integer>{ 'accountCount' => total };
}
}A request to /v1/Accounts/summary now goes to AccountSummaryRestService, because the exact match beats the wildcard. Any other path under /v1/Accounts/ still goes to AccountRestService.
Reading the wildcard portion
Because the wildcard is not extracted for you, the handler parses the path itself. The resource class from the topic plan does this with substringAfterLast:
@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];
}
}Note what happens when the caller sends /v1/Accounts/ with nothing after the last slash. substringAfterLast('/') returns an empty string. The bind variable then matches no record, so the query returns an empty list and the handler returns 404. If the value were not a valid Id at all, the same bind would raise a query exception instead of an empty result. Handling that case is covered in the chapter on status codes and errors.
Two more points apply to every resource class:
requestURIcontains the path after/services/apexrest, for example/v1/Accounts/001.... It does not include the host or the query string.- Static state does not persist between requests. Each request runs in its own transaction, so do not cache data in static variables and expect another request to see it.
Sharing and the class declaration
The keyword you put on the class decides which sharing rules apply. Apex REST classes run in system context by default, so without a sharing keyword, record sharing is not enforced for the caller. Declare with sharing on every resource class, as the examples here do. Field-level security and object permissions need extra work, such as WITH USER_MODE in queries and as user on DML. A later chapter covers those in detail.
The caller must also be allowed to run the class. Grant Apex Class Access in a profile or permission set that the calling user holds. When the caller is an integration, this is usually the integration user's permission set. If the class is not enabled for the user, the request does not reach your code.
Common errors and what they mean
| Symptom | Likely cause | Fix |
|---|---|---|
| 404 `NOT_FOUND` with a message that no match was found for the URL | Mapping typo, wrong case, missing `/services/apexrest` prefix, a namespace segment you forgot, or the user lacks class access | Compare the full URL to the mapping character by character, then check the user's permission sets |
| 405 `METHOD_NOT_ALLOWED` | The class has no method annotated for that HTTP verb | Add the annotated method, or call with a verb the class supports |
| Compile error on save about visibility | The class or a handler is not `global`, or a handler is not `static` | Declare the class `global` and each handler `global static` |
| Save error about a duplicate mapping | Another class in the org already declares the same `urlMapping` | Change one mapping, or merge the two classes |
| Requests hit the wrong class | An exact or longer wildcard mapping overlaps yours | Review all `@RestResource` classes in the org |
| Works for an admin but not for an integration user | Class access is granted only to the admin's profile | Add the class to the integration user's permission set |
To list every resource in an org and look for overlaps, run a quick search from the CLI:
sf data query --use-tooling-api \
--query "SELECT Name FROM ApexClass WHERE Body LIKE '%@RestResource%'"The tooling API accepts LIKE on Body for this purpose, and you can then open the matching classes to read their mappings.
Design habits that avoid trouble
- Put a version in the mapping.
/v1/Accounts/*lets you add/v2/Accounts/*later without breaking existing clients. Thev1here is only a path segment. It is unrelated to the Apex class's API version. - Use nouns, not verbs.
/v1/Accounts/*with different HTTP methods is clearer than/v1/getAccount. - Keep the resource class thin. Parse the request, call a service class, and shape the response. That makes the logic testable without
RestContext. - Avoid broad catch-alls. A mapping like
/*can absorb requests you did not intend to handle and makes overlap harder to reason about.
Exercise
An org has two classes. OrderRestService is mapped to /v1/Orders/*. OrderExportRestService is mapped to /v1/Orders/export. Which class handles a GET to /services/apexrest/v1/Orders/export, and which handles a GET to /services/apexrest/v1/Orders/801XXXXXXXXXXXX? A caller then reports a 404 for /services/apexrest/v1/orders/801XXXXXXXXXXXX. What is the most likely cause?
Show answer
OrderExportRestService handles /v1/Orders/export because an exact match beats a wildcard match. OrderRestService handles /v1/Orders/801XXXXXXXXXXXX because only the wildcard mapping matches. The 404 on the lowercase orders path is most likely a case mismatch, because URL mappings are case-sensitive and no mapping matches /v1/orders/....