Sub topic 5
Reading path, query and body input
This chapter assumes you can write Apex classes and static methods, run SOQL, and read an HTTP request (method, headers, body). It also assumes you have a @RestResource class with at least one handler method, as in earlier chapters.
Where a request carries data
A caller can send data to your service in four places. Each one is read differently.
| Source | Example | How you read it |
|---|---|---|
| Path | `/v1/Contacts/001...` | `RestContext.request.requestURI` |
| Query string | `?limit=10` | `RestContext.request.params` |
| Header | `X-Request-Id: 42` | `RestContext.request.headers` |
| Body | `{"lastName":"Lee"}` | Method parameters, or `requestBody` |
Path input
With urlMapping='/v1/Contacts/*', the wildcard matches whatever follows /v1/Contacts/. The mapping tells Apex which class to call. It does not extract the value for you. Take the last segment of requestURI:
String accountId = RestContext.request.requestURI.substringAfterLast('/');requestURI does not include the query string. Validate the segment before you use it, because a caller can put anything there.
Query string and header input
params is a Map<String, String> holding every query parameter. A missing key returns null, and every value is a string, so you convert types yourself. headers works the same way.
@RestResource(urlMapping='/v1/Contacts/*')
global with sharing class ContactRestService {
@HttpGet
global static List<Contact> getContacts() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
String accountId = req.requestURI.substringAfterLast('/');
try {
Id.valueOf(accountId);
} catch (StringException e) {
res.statusCode = 400;
return null;
}
Integer maxRows = 20;
String limitParam = req.params.get('limit');
if (String.isNotBlank(limitParam) && limitParam.isNumeric()) {
maxRows = Math.max(1, Math.min(Integer.valueOf(limitParam), 200));
}
return [
SELECT Id, LastName, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
LIMIT :maxRows
];
}
}A request to /services/apexrest/v1/Contacts/001XXXXXXXXXXXXXXX?limit=5 returns at most five contacts. The code clamps limit to the range 1 to 200, so a caller cannot ask for an unbounded result.
Keep two rules in mind:
- Do not declare parameters on
@HttpGetor@HttpDeletemethods. These requests have no body to bind, so all their input comes from the path, query string and headers. - Header names are matched as the client sent them. If you need a custom header, test that your lookup works with the casing your clients use.
Body input with parameter binding
For @HttpPost, @HttpPut and @HttpPatch, Apex deserializes a JSON body into the method parameters. Each parameter name must match a top-level JSON key.
@HttpPost
global static Id createContact(String lastName, String email) {
Contact c = new Contact(LastName = lastName, Email = email);
insert as user c;
RestContext.response.statusCode = 201;
return c.Id;
}This method accepts the body {"lastName":"Lee","email":"[email protected]"}. A key the method does not declare is ignored. A declared parameter with no matching key is null, so check required values yourself.
Body input read manually
Binding fits flat, fixed bodies. For nested or optional data, declare no parameters and read the raw body instead. requestBody is a Blob.
@HttpPatch
global static void updateContact() {
RestRequest req = RestContext.request;
Map<String, Object> body;
try {
body = (Map<String, Object>) JSON.deserializeUntyped(
req.requestBody.toString()
);
} catch (Exception e) {
RestContext.response.statusCode = 400;
return;
}
// Read only the keys you expect, e.g. body.get('email')
}An empty body makes requestBody empty, and malformed JSON throws a JSONException. Catching both lets you answer with a 400 instead of an unhandled error.
Common mistakes
- Using a parameter name that differs from the JSON key. The value arrives as
nullwith no error. - Putting parameters on a
@HttpGetmethod and expecting query values to bind. - Using a path value in SOQL without checking it is a valid Id.
- Trusting
limit-style values without bounds.
Exercise
A client sends GET /services/apexrest/v1/Contacts/001XXXXXXXXXXXXXXX?limit=abc. Using the getContacts method above, how many rows can come back, and why?
Show answer
Up to 20. "abc" fails the isNumeric() check, so the default maxRows of 20 stays in effect. The request still succeeds, because the handler falls back to the default and does not reject the bad value.