Sub topic 3
Mapping HTTP methods to Apex methods
This chapter assumes you can already define a @RestResource class with a urlMapping. It covers how Salesforce picks a method to run for each HTTP verb, what each annotation expects, and which mistakes cause errors.
How the platform routes a request
Apex REST routes in two steps. It first matches the request path to a urlMapping. It then looks inside that class for the one method whose annotation matches the HTTP verb. The method's name is irrelevant. Only the annotation counts.
Two rules follow from this routing:
- A class can have at most one method per annotation. Two
@HttpGetmethods in one class fail at save time. - To expose several GET operations, either use different
urlMappingvalues in different classes, or branch inside the single method on the URL or query string.
The five annotations
| Annotation | HTTP verb | Typical meaning | Idempotent | Input source |
|---|---|---|---|---|
| `@HttpGet` | GET | Read a record or list | Yes | URL and query string |
| `@HttpPost` | POST | Create a record or run an action | No | JSON body |
| `@HttpPut` | PUT | Replace a record, or create at a known Id | Yes | JSON body |
| `@HttpPatch` | PATCH | Change only some fields | Usually | JSON body |
| `@HttpDelete` | DELETE | Remove a record | Yes | URL |
An idempotent operation gives the same end state when a client repeats it. This matters because clients retry after timeouts. A retried POST may create a duplicate. A retried PUT or DELETE should not.
Signature requirements
Every handler must be global static, inside a global class. A public or private handler is not exposed. A private helper in the same class is fine, because only annotated methods are routed.
@HttpGet
global static Account getAccount() { /* ... */ }Return types can be a primitive, an sObject, a collection, or a user-defined class. Apex serializes the value to JSON or XML for you. A void method returns an empty body. Returning null also gives an empty body, so set a status code yourself when that means "not found".
Parameter binding differs by verb
POST, PUT and PATCH bind the JSON body to method parameters by name. Given this body:
{ "name": "Acme", "industry": "Energy" }the method createAccount(String name, String industry) receives both values. A key that is missing from the body leaves its parameter null. The match is by name, so renaming a parameter changes the public contract of your API.
GET and DELETE have no body to bind. Salesforce documents that handlers for these verbs should declare no parameters. Read the record Id and any filters from RestContext.request instead, as the next chapters cover in detail.
A PATCH handler has a particular problem. A bound String industry parameter is null both when the client omits industry and when the client sends "industry": null. You cannot tell "leave it alone" from "clear it". For true partial updates, read the raw body and inspect which keys are present, as the example below does.
A complete resource with all five verbs
This class builds on the AccountRestService from earlier chapters. It adds the remaining verbs and returns explicit status codes.
@RestResource(urlMapping='/v1/Accounts/*')
global with sharing class AccountRestService {
private static final Set<String> PATCHABLE = new Set<String>{ 'Name', 'Industry' };
@HttpGet
global static Account getAccount() {
Id accountId = idFromUri();
if (accountId == null) {
RestContext.response.statusCode = 400;
return null;
}
List<Account> rows = [
SELECT Id, Name, Industry
FROM Account
WHERE Id = :accountId
WITH USER_MODE
LIMIT 1
];
if (rows.isEmpty()) {
RestContext.response.statusCode = 404;
return null;
}
return rows[0];
}
@HttpPost
global static Account createAccount(String name, String industry) {
RestResponse res = RestContext.response;
try {
Account acc = new Account(Name = name, Industry = industry);
insert as user acc;
res.statusCode = 201;
res.addHeader('Location', '/services/apexrest/v1/Accounts/' + acc.Id);
return acc;
} catch (DmlException e) {
res.statusCode = 400;
return null;
}
}
@HttpPut
global static Account replaceAccount(String name, String industry) {
RestResponse res = RestContext.response;
Id accountId = idFromUri();
if (accountId == null) {
res.statusCode = 400;
return null;
}
try {
Account acc = new Account(Id = accountId, Name = name, Industry = industry);
update as user acc;
return acc;
} catch (DmlException e) {
res.statusCode = 400;
return null;
}
}
@HttpPatch
global static Account updateAccount() {
RestResponse res = RestContext.response;
Id accountId = idFromUri();
Blob body = RestContext.request.requestBody;
if (accountId == null || body == null || body.size() == 0) {
res.statusCode = 400;
return null;
}
try {
Map<String, Object> fields =
(Map<String, Object>) JSON.deserializeUntyped(body.toString());
Account acc = new Account(Id = accountId);
for (String key : fields.keySet()) {
if (PATCHABLE.contains(key)) {
acc.put(key, fields.get(key));
}
}
update as user acc;
return acc;
} catch (JSONException e) {
res.statusCode = 400;
return null;
} catch (DmlException e) {
res.statusCode = 400;
return null;
}
}
@HttpDelete
global static void deleteAccount() {
RestResponse res = RestContext.response;
Id accountId = idFromUri();
if (accountId == null) {
res.statusCode = 400;
return;
}
List<Account> rows = [
SELECT Id FROM Account
WHERE Id = :accountId
WITH USER_MODE
LIMIT 1
];
if (rows.isEmpty()) {
res.statusCode = 404;
return;
}
try {
delete as user rows;
res.statusCode = 204;
} catch (DmlException e) {
res.statusCode = 400;
}
}
private static Id idFromUri() {
String last = RestContext.request.requestURI.substringAfterLast('/');
try {
return Id.valueOf(last);
} catch (StringException e) {
return null;
}
}
}Points worth noting in this class:
PATCHABLEis an allow-list. Without it, a client could send any field name, andacc.putwould try to write it. User mode enforces field-level security, but an allow-list keeps the contract explicit.- PUT assigns every bound parameter, so a missing
industryclears the field. That is the "replace" semantic. PATCH only touches keys that were sent. idFromUri()is a private helper. It is not routed, so it can have any signature.- A successful DELETE sets 204 (No Content). Leaving the status at the default would send 200 with an empty body, which is legal but less precise.
Calling each verb
You can exercise the handlers with curl. Replace the domain and Id with your own.
BASE="https://MyDomainName.my.salesforce.com/services/apexrest/v1/Accounts"
curl -X POST "$BASE/" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"name":"Acme","industry":"Energy"}'
curl -X PATCH "$BASE/001XXXXXXXXXXXXXXX" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"Industry":"Banking"}'
curl -X DELETE "$BASE/001XXXXXXXXXXXXXXX" \
-H "Authorization: Bearer $ACCESS_TOKEN"The Content-Type: application/json header matters for POST, PUT and PATCH. Without it, Salesforce may fail to parse the body, and the call returns an error such as 415 (Unsupported Media Type) before your method runs.
Common errors
| Symptom | Likely cause |
|---|---|
| Save error about duplicate `@HttpGet` (or another verb) | Two methods in one class use the same annotation |
| 404 with a message that no resource matches | The path does not match `urlMapping`, or the URL is missing `/services/apexrest` |
| 405 Method Not Allowed | The class has no method for that verb |
| Parameter is `null` in POST | The JSON key does not match the parameter name |
| Parameter is `null` in PATCH even though the client sent the field | Same name mismatch, or the client sent an explicit `null` |
| Handler never runs, the platform returns an error | Method is not `global static`, or the class is not `global` |
| 200 returned when you expected an error | You returned early without setting `statusCode` |
Choosing between PUT, PATCH and POST
Use POST when the server assigns the Id, or when the call is an action rather than a resource write, such as "recalculate this account". Use PUT when the client sends the full representation and the call should be safely repeatable. Use PATCH when clients send only the fields that changed. If your clients only ever send full records, you can skip PATCH and keep the API smaller.
Exercise
A client sends POST /services/apexrest/v1/Accounts/ with the body {"Name":"Acme","industry":"Energy"}. Your handler is createAccount(String name, String industry), and the insert fails with a required-field error. Why, and what is the fix?
Show answer
Parameter binding matches JSON keys to parameter names, and the key "Name" does not match the parameter "name" because the client's capitalization differs from your declared name. The name parameter stays null, so Account.Name is empty and the insert fails. Fix it by having the client send "name" exactly as declared, or by changing the handler to read the body yourself and accept both spellings. Whichever you choose, document the key names, because they are part of your API contract.
Exercise
Why can a PATCH handler declared as updateAccount(String name, String industry) not distinguish "leave industry alone" from "clear industry"? How do you make the distinction?
Show answer
Bound parameters are null both when the key is absent and when the client sends an explicit null. To tell them apart, declare no parameters, read RestContext.request.requestBody, deserialize it with JSON.deserializeUntyped into a Map<String, Object>, and use containsKey to see which fields the client sent. Only assign the fields whose keys are present.
Exercise
You need one endpoint to list accounts and another to fetch one account by Id. Both are GET. Can you put two @HttpGet methods in AccountRestService?
Show answer
No. A class can have only one method per HTTP annotation, and a second @HttpGet fails at save time. Either branch inside the single GET handler (for example, return a list when the URI ends at /Accounts/ and a single record when it ends with an Id), or create a second resource class with a different urlMapping.