Sub topic 1
REST Basics and When to Write an Apex REST Service
Prerequisites
This chapter assumes basic Apex classes and static methods, SOQL and DML, HTTP methods and status codes, JSON, and Salesforce permissions.
REST Basics and Custom Services
REST is an HTTP style for exposing resources, such as accounts or orders. A client selects a resource with a URL and uses an HTTP method to describe the action.
Salesforce provides a standard REST API for common object operations. Write a custom Apex REST service when the standard API does not match your contract. Common reasons include combining several objects, applying business rules, hiding internal fields, or supporting a client-specific request and response shape.
Defining a Resource with @RestResource
The @RestResource annotation makes an Apex class available as an Apex REST resource. Its urlMapping defines the path after /services/apexrest.
@RestResource(urlMapping='/v1/accounts/*')
global with sharing class AccountRestService {
@HttpGet
global static Account getAccount() {
RestRequest request = RestContext.request;
RestResponse response = RestContext.response;
String accountId = request.requestURI.substringAfterLast('/');
List<Account> accounts = [
SELECT Id, Name, Industry
FROM Account
WHERE Id = :accountId
WITH USER_MODE
LIMIT 1
];
if (accounts.isEmpty()) {
response.statusCode = 404;
return null;
}
return accounts[0];
}
}A request to /services/apexrest/v1/accounts/001... reaches this class. Returned Apex objects are serialized to JSON automatically.
Mapping HTTP Methods to Apex Methods
Annotations map HTTP methods to static Apex methods.
| Annotation | Typical purpose |
|---|---|
| `@HttpGet` | Read resources |
| `@HttpPost` | Create resources |
| `@HttpPut` | Replace a resource |
| `@HttpPatch` | Update selected fields |
| `@HttpDelete` | Delete a resource |
A class can contain one handler for each annotation. Keep each handler focused on one operation and return an intentional status code.
Working with RestContext
RestContext.request provides the incoming RestRequest. Use it for the URI, HTTP method, headers, query parameters, and request body. RestContext.response provides the RestResponse, where you set statusCode, headers, and, when needed, a response body.
Path values can be extracted from the URI. Query values are available through request.params. For JSON input, read request.requestBody and deserialize it into an Apex class with JSON.deserialize.
Exercise
Which annotation should handle a request that creates a new Account?
Show answer
@HttpPost, because POST commonly creates a new resource.