Sub topic 3
Mapping HTTP methods to Apex methods
This chapter assumes you can write a basic @RestResource class (covered in the previous chapter), know the HTTP verbs, and understand SOQL and DML. Here you will see how Salesforce picks the Apex method that handles a request.
How routing works
A resource class has one URL mapping. Salesforce uses the HTTP verb of the incoming request to choose a method inside that class. You tell it which verb each method handles with an annotation.
The five annotations
| Annotation | Typical use | Body bound to parameters |
|---|---|---|
| `@HttpGet` | Read a record or a list | No |
| `@HttpPost` | Create a record | Yes |
| `@HttpPut` | Replace or upsert a record | Yes |
| `@HttpPatch` | Change selected fields | Yes |
| `@HttpDelete` | Remove a record | No |
Rules the platform enforces
- The class must be
global, and each handler must beglobal static. - A class can have at most one method per annotation. You cannot have two
@HttpGetmethods in the same class. - A verb with no matching method returns an error (405, Method Not Allowed). A URL that matches no
urlMappingreturns 404. @HttpGetand@HttpDeletemethods should declare no parameters. These requests have no body to bind. Read the URL and query string throughRestContext.request.- For
@HttpPost,@HttpPutand@HttpPatch, parameter names are matched to top-level keys in the JSON body. A key with no matching parameter is ignored, and a parameter with no matching key isnull.
Example: PATCH and DELETE
The earlier examples in this tutorial cover GET and POST. This version adds partial update and delete to the same /v1/Accounts/* resource. In practice, all five handlers live in one class.
@RestResource(urlMapping='/v1/Accounts/*')
global with sharing class AccountRestService {
@HttpPatch
global static Account updateAccount(String name, String industry) {
RestResponse res = RestContext.response;
String accountId = RestContext.request.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;
}
Account acc = rows[0];
if (name != null) {
acc.Name = name;
}
if (industry != null) {
acc.Industry = industry;
}
update as user acc;
return acc;
}
@HttpDelete
global static void deleteAccount() {
RestResponse res = RestContext.response;
String accountId = RestContext.request.requestURI.substringAfterLast('/');
List<Account> rows = [
SELECT Id
FROM Account
WHERE Id = :accountId
WITH USER_MODE
LIMIT 1
];
if (rows.isEmpty()) {
res.statusCode = 404;
return;
}
delete as user rows;
res.statusCode = 204;
}
}The updateAccount handler changes only the fields the client sent. Fields omitted from the JSON arrive as null and are left alone. That is the behavior clients expect from PATCH. The deleteAccount handler returns void and sets 204 (No Content), because there is nothing to send back.
A client call looks like this:
curl -X PATCH \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"industry":"Banking"}' \
"https://MyDomainName.my.salesforce.com/services/apexrest/v1/Accounts/001XXXXXXXXXXXXXXX"PUT versus PATCH
Both receive a JSON body, so the platform treats them the same way. The difference is the contract you define. Use PUT when the client sends the full representation and you overwrite the record, or create it if it does not exist. Use PATCH when the client sends only the fields to change. Pick one meaning per verb and keep it consistent across your API.
Common errors
- Compile error on the method: the method is not
global static, or the class ispublic. - Save error about duplicate annotations: two methods in one class share the same HTTP annotation.
- Every field is
nullin POST: the JSON key names do not match the parameter names, or the client omittedContent-Type: application/json. - 405 on a call that should work: the class has no handler for that verb. Check for a typo in the annotation or a missing method.
Exercise
A client sends PATCH to /services/apexrest/v1/Accounts/001XXXXXXXXXXXXXXX with the body {"name":"Acme"}. Your class has @HttpGet, @HttpPost and @HttpDelete methods, but no @HttpPatch method. What happens, and what do you add to fix it?
Show answer
Salesforce finds the resource class from the URL but has no method for the PATCH verb, so it returns an error (405, Method Not Allowed) and no Apex handler runs. To fix it, add a global static method annotated with @HttpPatch. Give it a String name parameter so the JSON key "name" binds to it, and add a String industry parameter if the client may send that key too.