Sub topic 2
Reading Path, Query, and Body Input
Assume you know basic Apex, SOQL, DML, HTTP, JSON, and Salesforce permissions. In an Apex REST service, RestContext gives the handler access to the incoming request and outgoing response.
Read request data
A path identifies a resource, a query parameter changes how it is returned, and a request body carries structured input.
| HTTP input | Apex access |
|---|---|
| Path | `RestContext.request.requestURI` |
| Query string | `RestContext.request.params` |
| Header | `RestContext.request.headers` |
| JSON body | `RestContext.request.requestBody` |
This endpoint reads all three input types:
@RestResource(urlMapping='/v1/accounts/*')
global with sharing class AccountEndpoint {
global class ResponseBody {
global Boolean success;
global String message;
global String accountName;
global String source;
}
@HttpPost
global static ResponseBody create() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
ResponseBody output = new ResponseBody();
String accountId = req.requestURI.substringAfterLast('/');
String source = req.params.get('source');
try {
Map<String, Object> body =
(Map<String, Object>) JSON.deserializeUntyped(
req.requestBody.toString()
);
String name = (String) body.get('name');
if (String.isBlank(accountId) || String.isBlank(name)) {
res.statusCode = 400;
output.success = false;
output.message = 'The path Id and name are required.';
return output;
}
output.success = true;
output.message = 'Input accepted.';
output.accountName = name;
output.source = source;
res.statusCode = 201;
return output;
} catch (Exception e) {
res.statusCode = 400;
output.success = false;
output.message = 'The request body is invalid.';
return output;
}
}
}JSON.deserializeUntyped returns generic Apex values. A JSON object becomes Map<String, Object>, while a JSON array becomes List<Object>. A returned Apex object is serialized to JSON automatically.
Status codes and errors
Use status codes that describe the result.
201 Created: a resource was created.200 OK: the request succeeded.400 Bad Request: input is invalid.401 Unauthorized: authentication is missing or invalid.403 Forbidden: the caller lacks permission.404 Not Found: the resource does not exist.500 Internal Server Error: an unexpected server failure occurred.
Authentication and class access
A caller normally sends an OAuth access token:
curl -H "Authorization: Bearer $ACCESS_TOKEN" \
"https://MyDomain.my.salesforce.com/services/apexrest/v1/accounts/001XXXXXXXXXXXXXXX"The connected app issues the token. Salesforce then checks whether the token’s user can access the Apex class. Grant the class through a profile or permission set. with sharing applies record-sharing rules, but you must also enforce object and field permissions when querying or changing data.
Exercise
Which Apex property contains a JSON request body?
Show answer
RestContext.request.requestBody.