Sub topic 5
Reading path, query and body input
A request can carry data in four places: the URL path, the query string, the headers and the body. An Apex REST handler reads all of them through RestContext.request. This chapter shows where each kind of input lives and how to read it safely. It also covers what to do when the caller sends something unexpected.
It assumes you can write Apex classes with static methods, run SOQL and DML, and read a JSON document. It also assumes you have seen the @RestResource and HTTP method annotations from earlier chapters.
Where input arrives
Take this request:
POST /services/apexrest/v1/Accounts/001XXXXXXXXXXXXXXX?notify=true
Content-Type: application/json
{"name": "Acme", "industry": "Energy"}Each part is read differently:
| Input | Example value | How to read it |
|---|---|---|
| Path | `001XXXXXXXXXXXXXXX` | `req.requestURI`, then string parsing |
| Query string | `notify=true` | `req.params.get('notify')` |
| Header | `Content-Type` | `req.headers.get('Content-Type')` |
| Body | the JSON document | method parameters, or `req.requestBody` |
Reading the path
The urlMapping on @RestResource decides which requests reach your class. A trailing * matches any remaining path. The handler receives the full path in requestURI, including the /services/apexrest prefix. The query string is not part of requestURI.
The usual way to get a record Id is to take the last segment:
RestRequest req = RestContext.request;
String lastSegment = req.requestURI.substringAfterLast('/');Do not trust that segment. A caller can send anything, and an invalid value passed to a SOQL bind variable of type Id throws an exception. Validate it first:
private static Id parseId(String value) {
try {
return Id.valueOf(value);
} catch (StringException e) {
return null;
}
}Id.valueOf throws a StringException when the text is not a valid 15- or 18-character Id. Returning null lets the handler answer with a 400 instead of an unhandled exception, which Salesforce reports as a 500.
When the path has several segments, such as /v1/Accounts/001.../Contacts, split it into parts:
List<String> parts = req.requestURI.split('/');Splitting by position is fragile. If your API needs more than one nested level, consider a separate resource class for each level. The design chapter returns to this.
Reading the query string
req.params is a Map<String, String> of query parameters. Salesforce URL-decodes the values, so industry=Oil%20%26%20Gas arrives as Oil & Gas.
Every value is a string, and any parameter can be missing. Convert and default each one:
String industry = RestContext.request.params.get('industry');
Integer pageSize = 20;
String rawLimit = RestContext.request.params.get('limit');
if (String.isNotBlank(rawLimit)) {
try {
pageSize = Integer.valueOf(rawLimit);
} catch (TypeException e) {
// fall through to a 400 response
}
}Integer.valueOf('abc') throws a TypeException. The map holds one value per name. If a caller repeats a parameter (?id=1&id=2), you cannot assume which value you get. Define your API so each parameter appears once, or use a comma-separated value and split it yourself.
A complete search endpoint
This class reads two optional parameters, validates them and builds the query. Because WITH USER_MODE cannot be added to a string built at runtime in a convenient way, the example uses Database.queryWithBinds with AccessLevel.USER_MODE.
@RestResource(urlMapping='/v1/AccountSearch')
global with sharing class AccountSearchService {
private static final Integer DEFAULT_PAGE_SIZE = 20;
private static final Integer MAX_PAGE_SIZE = 200;
@HttpGet
global static List<Account> search() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
String industry = req.params.get('industry');
Integer pageSize = DEFAULT_PAGE_SIZE;
String rawLimit = req.params.get('limit');
if (String.isNotBlank(rawLimit)) {
try {
pageSize = Integer.valueOf(rawLimit);
} catch (TypeException e) {
res.statusCode = 400;
return null;
}
if (pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
res.statusCode = 400;
return null;
}
}
String soql = 'SELECT Id, Name, Industry FROM Account';
if (String.isNotBlank(industry)) {
soql += ' WHERE Industry = :industry';
}
soql += ' ORDER BY Name LIMIT :pageSize';
return Database.queryWithBinds(
soql,
new Map<String, Object>{ 'industry' => industry, 'pageSize' => pageSize },
AccessLevel.USER_MODE
);
}
}A call to /services/apexrest/v1/AccountSearch?industry=Energy&limit=5 returns up to five Energy accounts as a JSON array.
Reading headers
req.headers is another Map<String, String>. Use it when the caller controls behavior with a header, for example an idempotency key or a client version:
String clientVersion = RestContext.request.headers.get('X-Client-Version');Header lookups are exact-match on the map key. Check the casing you actually receive in a debug log, and set headers with the same casing in tests, so the code path behaves the same in both places. Keep headers for metadata about the request. Put the data you are acting on in the path, query string or body.
Reading the body
There are two ways to read a JSON body: let the platform bind it to method parameters, or parse it yourself.
Option 1: automatic parameter binding
For @HttpPost, @HttpPut and @HttpPatch, Apex matches top-level JSON keys to method parameter names and converts the values to the parameter types. This request:
{"name": "Acme", "industry": "Energy"}binds to this method:
@HttpPost
global static CreateResult createAccount(String name, String industry) { /* ... */ }This is short and works well for flat payloads with a few fields. Its limits are:
- The JSON key names must match the Apex parameter names, so you cannot use names that are reserved words in Apex.
- A value of the wrong type, such as a string where you declared an Integer, fails before your code runs, and the caller gets an error response you did not write.
- You cannot customize the error message for malformed input.
@HttpGetand@HttpDeletehave no body, so declare no parameters on them and readreq.paramsinstead.
Option 2: parse `requestBody` yourself
req.requestBody is a Blob. Convert it to a string with toString() and deserialize into a class that mirrors the JSON. This gives you control over validation and error responses, and it handles nested objects and lists naturally. The next chapter covers JSON handling in more depth; here the focus is on reading and validating input.
@RestResource(urlMapping='/v1/ContactImport')
global with sharing class ContactImportService {
global class ContactInput {
public String lastName;
public String email;
public Id accountId;
}
global class ImportRequest {
public List<ContactInput> contacts;
}
global class ImportResult {
public Boolean success;
public Integer inserted;
public String message;
}
@HttpPost
global static ImportResult importContacts() {
RestResponse res = RestContext.response;
Blob body = RestContext.request.requestBody;
ImportResult result = new ImportResult();
if (body == null || body.size() == 0) {
return fail(res, result, 'Request body is required.');
}
ImportRequest payload;
try {
payload = (ImportRequest) JSON.deserializeStrict(
body.toString(), ImportRequest.class
);
} catch (JSONException e) {
return fail(res, result, 'Invalid JSON: ' + e.getMessage());
}
if (payload.contacts == null || payload.contacts.isEmpty()) {
return fail(res, result, 'contacts must be a non-empty list.');
}
List<Contact> toInsert = new List<Contact>();
for (ContactInput input : payload.contacts) {
if (String.isBlank(input.lastName)) {
return fail(res, result, 'Every contact needs a lastName.');
}
toInsert.add(new Contact(
LastName = input.lastName,
Email = input.email,
AccountId = input.accountId
));
}
try {
insert as user toInsert;
} catch (DmlException e) {
return fail(res, result, e.getMessage());
}
res.statusCode = 201;
result.success = true;
result.inserted = toInsert.size();
return result;
}
private static ImportResult fail(RestResponse res, ImportResult result, String message) {
res.statusCode = 400;
result.success = false;
result.message = message;
return result;
}
}The details that matter here:
JSON.deserializeStrictthrows aJSONExceptionif the body contains a key your class does not declare.JSON.deserializeignores unknown keys. Use strict parsing when a misspelled field should be an error, and the lenient version when clients may send extra data.- Null and empty bodies need an explicit check. A POST without a body is valid HTTP, and calling
toString()on a null Blob throws aNullPointerException. - Validation after parsing. A document can be valid JSON and still be wrong for your API, such as an empty list or a missing required field. Check these before any DML.
- One DML statement inserts the whole list. This keeps the endpoint bulk-friendly, a point the last chapter develops.
- Character encoding.
Blob.toString()decodes the bytes as UTF-8. If your clients send another encoding, decode explicitly withEncodingUtilor require UTF-8 in the API contract.
Choosing a style
| Situation | Use |
|---|---|
| Identify a single record | Path segment, validated as an Id |
| Filter, sort or page a list | Query parameters |
| Create or update with a few flat fields | Bound parameters |
| Nested data, lists, custom errors | `requestBody` plus a wrapper class |
| Request metadata such as a version or key | Headers |
Testing input handling
You test input without HTTP by building a RestRequest, filling in the parts the handler reads, and assigning it to RestContext. For a body, set requestBody with Blob.valueOf:
@IsTest
private class ContactImportServiceTest {
@IsTest
static void rejectsInvalidJson() {
RestRequest req = new RestRequest();
req.requestURI = '/services/apexrest/v1/ContactImport';
req.httpMethod = 'POST';
req.requestBody = Blob.valueOf('{"contacts": [');
RestContext.request = req;
RestContext.response = new RestResponse();
ContactImportService.ImportResult result = ContactImportService.importContacts();
Assert.areEqual(400, RestContext.response.statusCode);
Assert.isFalse(result.success);
}
}For query parameters, call req.params.put('industry', 'Energy') before invoking the handler. A good set of tests covers a valid input, a missing input, a malformed input and an out-of-range input for each parameter the handler reads.
Exercise
A client calls GET /services/apexrest/v1/AccountSearch?limit=abc. What does the AccountSearchService example return, and which line of Apex causes it?
Show answer
It sets the status code to 400 and returns null, so the caller gets an error with no account list. Integer.valueOf('abc') throws a TypeException, the catch block sets res.statusCode = 400 and returns null before any query runs.
Exercise
Why does ContactImportService read requestBody and call JSON.deserializeStrict instead of declaring a contacts parameter on the method? Give two benefits.
Show answer
Parsing it yourself lets you return your own 400 message when the JSON is malformed, instead of the platform's generic error. It also gives you strict checking of unknown keys and lets you validate the nested contact list before any DML runs.