Sub topic 4
Working with RestContext, RestRequest and RestResponse
This chapter assumes you can write a @RestResource class with an @HttpGet method, as in the previous chapters. It also assumes you know the basics of HTTP headers and status codes. Here you will look at the objects Apex gives you to read the incoming call and shape the reply.
The static context
A handler method runs without a request parameter. Instead, Salesforce fills in a static class named RestContext before your method starts. It has two properties:
RestContext.requestis aRestRequest. It describes what the client sent.RestContext.responseis aRestResponse. It describes what you will send back.
Most handlers start by copying both into local variables.
Reading the request
RestRequest exposes the parts of the call you will use most often.
| Property | Type | Contains |
|---|---|---|
| `httpMethod` | String | `GET`, `POST`, and so on |
| `requestURI` | String | The path after `/services/apexrest`, such as `/v1/Echo/abc` |
| `resourcePath` | String | The full path, starting with `/services/apexrest` |
| `params` | Map<String, String> | Query string parameters |
| `headers` | Map<String, String> | Request headers |
| `requestBody` | Blob | The raw body, or null if none was sent |
The body is a Blob, so convert it with toString() before you parse it. The next chapter covers how to bind input in more detail.
Shaping the response
RestResponse has three properties you will set:
statusCodeis an Integer. If you leave it unset, a normal return produces 200.responseBodyis a Blob that holds the payload.headersis a map, andaddHeader(name, value)adds a single header.
You can send a reply in two ways. If your method returns a value, Salesforce serializes it to JSON and uses it as the body. If your method returns void, you build the body yourself and assign it to responseBody. The second way gives you full control over content type and format.
A handler that uses both objects
This service echoes back what it received. It returns void, so it writes the body directly.
@RestResource(urlMapping='/v1/Echo/*')
global with sharing class EchoRestService {
@HttpGet
global static void echo() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
Map<String, Object> payload = new Map<String, Object>{
'method' => req.httpMethod,
'uri' => req.requestURI,
'lastSegment' => req.requestURI.substringAfterLast('/'),
'limit' => req.params.get('limit'),
'clientId' => req.headers.get('X-Client-Id')
};
res.statusCode = 200;
res.addHeader('Content-Type', 'application/json');
res.responseBody = Blob.valueOf(JSON.serialize(payload));
}
}A call to /services/apexrest/v1/Echo/abc?limit=5 returns the method, the URI, the segment abc and the value 5. A missing parameter or header gives null, not an error.
Testing without HTTP
Because the handler reads static state, a test can set that state and call the method directly.
@IsTest
private class EchoRestServiceTest {
@IsTest
static void echoReturnsLastSegment() {
RestRequest req = new RestRequest();
req.requestURI = '/v1/Echo/abc';
req.httpMethod = 'GET';
req.addParameter('limit', '5');
RestContext.request = req;
RestContext.response = new RestResponse();
EchoRestService.echo();
Map<String, Object> body = (Map<String, Object>)
JSON.deserializeUntyped(RestContext.response.responseBody.toString());
Assert.areEqual('abc', body.get('lastSegment'));
Assert.areEqual(200, RestContext.response.statusCode);
}
}Common mistakes
- Reading
requestBodywhen no body was sent. A GET request has a null body, so callingtoString()on it throws aNullPointerException. Check for null first. - Using
resourcePathwhen you meantrequestURI.resourcePathincludes the/services/apexrestprefix, so asubstringAfterLastcall works on either, but comparisons against your mapping will fail on the wrong one. - Forgetting the Content-Type header. When you assign
responseBodyyourself, Salesforce does not guess the type. SetContent-Typeexplicitly. - Skipping the reset in tests.
RestContextis static, so assign a freshRestRequestandRestResponsein every test method.
Exercise
A handler returns void and sets res.responseBody = Blob.valueOf('{"ok":true}'), but the client receives a response without a JSON content type. What is missing, and which line fixes it?
Show answer
The handler never set a Content-Type header. Because the body is written directly, Salesforce does not infer the type. Add res.addHeader('Content-Type', 'application/json'); before returning.
Exercise
In a test, why must you assign RestContext.request and RestContext.response before calling the handler?
Show answer
The handler reads both from the static RestContext class. In a test no HTTP call fills them in, so they are null until you assign them. Calling the handler without that setup throws a NullPointerException.