Sub topic 4
Working with RestContext, RestRequest and RestResponse
This chapter assumes you can write Apex classes with static methods and that you know how a class is mapped to a URL with @RestResource and how handler methods get @HttpGet or @HttpPost. It also assumes you know what an HTTP request looks like: a method, a URI, headers, and an optional body.
By the end you will know where a handler gets request data from, how to shape the response, and how to test both without making an HTTP call.
Why a handler has no request parameter
A servlet-style framework would pass a request and a response into your method. Apex REST does not. Handler methods are static, and the platform stores the current request and response in a global holder class, RestContext.
RestContext has two static properties:
RestContext.requestis aRestRequest. It describes what the client sent.RestContext.responseis aRestResponse. It describes what you will send back.
Both are filled in by the platform before your handler runs. Both are tied to the current transaction, so a handler sees only its own call.
A common habit is to copy both objects into local variables at the top of the handler. It shortens the code and makes it clear that these are the two objects the method works with.
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;What RestRequest gives you
RestRequest is read-oriented. Most of its members describe the incoming call.
| Member | Type | What it holds |
|---|---|---|
| `httpMethod` | `String` | The method, such as `GET` or `POST`. |
| `requestURI` | `String` | The path after the host, for example `/services/apexrest/v1/Accounts/001...`. |
| `resourcePath` | `String` | The `urlMapping` pattern that matched, with the `/services/apexrest` prefix. |
| `headers` | `Map<String, String>` | Request headers. |
| `params` | `Map<String, String>` | Query string parameters. |
| `requestBody` | `Blob` | The raw body bytes. |
| `remoteAddress` | `String` | The address the call came from. |
Two points often trip people up.
requestURIis the concrete path the caller used.resourcePathis the pattern you declared. ForurlMapping='/v1/Accounts/*', the first might end in an Id and the second ends in/*. UserequestURIwhen you need the value the caller supplied.requestBodyis aBlob, not aString. CalltoString()to get text. Chapter 5 and Chapter 6 cover reading input and parsing JSON in detail. Here you only need to know that the raw bytes live in this property.
A handler that reports what it received
The next class echoes request metadata back. It is a useful way to see what the platform puts in each property, and you can deploy it temporarily while debugging a client.
@RestResource(urlMapping='/v1/Echo/*')
global with sharing class EchoRestService {
@HttpGet
global static Map<String, Object> echo() {
RestRequest req = RestContext.request;
Map<String, Object> info = new Map<String, Object>();
info.put('httpMethod', req.httpMethod);
info.put('requestURI', req.requestURI);
info.put('resourcePath', req.resourcePath);
info.put('params', req.params);
info.put('lastSegment', req.requestURI.substringAfterLast('/'));
info.put('bodyBytes', req.requestBody == null ? 0 : req.requestBody.size());
return info;
}
}A call to /services/apexrest/v1/Echo/abc?limit=5 returns JSON in which lastSegment is abc and params contains limit with the value 5.
What RestResponse gives you
RestResponse is write-oriented. You fill it in, and the platform sends it.
| Member | Type | What it does |
|---|---|---|
| `statusCode` | `Integer` | The HTTP status. If you never set it, a successful call returns 200. |
| `responseBody` | `Blob` | The raw body you want to send. |
| `headers` | `Map<String, String>` | Response headers you have set. |
| `addHeader(name, value)` | method | Adds one response header. |
Two ways to produce a body
You have two ways to produce the response body, and you should pick one per handler.
- Return a value. The method has a non-void return type. The platform serializes the returned object, usually to JSON, and uses it as the body. The
getAccountexample in the topic plan works this way. - Write the body yourself. The method returns
void, and you setres.responseBodyto aBlob. You are now responsible for the content type as well.
Returning a value is shorter and keeps the handler easy to test. Writing the body yourself is the right choice when the payload is not a plain object, for example plain text, CSV, or a JSON string you built by hand.
@RestResource(urlMapping='/v1/Health/*')
global with sharing class HealthRestService {
@HttpGet
global static void check() {
RestResponse res = RestContext.response;
res.statusCode = 200;
res.addHeader('Content-Type', 'application/json');
res.addHeader('Cache-Control', 'no-store');
res.responseBody = Blob.valueOf('{"status":"ok"}');
}
}Here the handler sets the status, two headers, and the body bytes. Nothing is returned, so nothing is serialized for you.
Status code still works with a return value
Setting statusCode does not require a void method. In the getAccount example from the topic plan, the handler sets res.statusCode = 404 and returns null. The status comes from the response object, and the body comes from the returned value. This is the pattern for a handler that returns an object on success and an empty or error body otherwise. Chapter 7 covers status codes and error handling in full.
Edge cases and gotchas
RestContext is empty outside a REST call. If you call a helper from a trigger, a batch job, or an anonymous script, RestContext.request is null, and the first property you touch throws a NullPointerException. Keep REST-specific code in the handler class. Pass plain values (an Id, a name) into service classes that other code also uses.
Headers are strings. headers is a Map<String, String>, so a missing header returns null. Check for null before you call string methods on it. Do not assume a particular letter case for header names. Test the header lookup against the client you actually use.
String clientVersion = RestContext.request.headers.get('X-Client-Version');
if (clientVersion == null) {
clientVersion = '1';
}Query parameters are strings too. params.get('limit') gives you '5', not 5. Convert it with Integer.valueOf and guard against a null or a value that is not a number. Chapter 5 covers this.
A blob is not text. requestBody.toString() assumes UTF-8 text. For a binary upload, keep the Blob as it is and do not convert it.
Unhandled exceptions become server errors. If your handler throws and you do not catch the exception, the platform returns a 500-level response. Catching the exceptions you can predict, and setting a clear status for each, gives clients a response they can act on.
The response is what you leave behind. Because RestContext.response is a shared object for the call, a helper method that sets statusCode also affects the final response. That is convenient, but it also means a helper can change the status without the handler noticing. Keep response writes in the handler itself where you can.
Testing without an HTTP call
Because the handler reads from RestContext, a test only needs to fill RestContext the way the platform would, then call the method directly. No callout and no mock are involved.
@IsTest
private class EchoRestServiceTest {
@IsTest
static void echoReportsQueryParams() {
RestRequest req = new RestRequest();
req.requestURI = '/services/apexrest/v1/Echo/abc';
req.httpMethod = 'GET';
req.params.put('limit', '5');
RestContext.request = req;
RestContext.response = new RestResponse();
Map<String, Object> result = EchoRestService.echo();
Assert.areEqual('abc', result.get('lastSegment'));
Map<String, String> params = (Map<String, String>) result.get('params');
Assert.areEqual('5', params.get('limit'));
}
@IsTest
static void healthSetsStatusAndBody() {
RestContext.request = new RestRequest();
RestContext.response = new RestResponse();
HealthRestService.check();
Assert.areEqual(200, RestContext.response.statusCode);
Assert.areEqual('{"status":"ok"}', RestContext.response.responseBody.toString());
}
}Notes on this test:
- Set both
RestContext.requestandRestContext.responsein every test. A handler that touches only the request still often sets a status on the response. - A new
RestRequeststarts with emptyheadersandparamsmaps, so you can callputon them straight away. - For a
POST, setreq.requestBody = Blob.valueOf('{"name":"Acme"}'). - Assert on
RestContext.responseafter the call, because that is the object your handler wrote to.
Common errors
| Symptom | Likely cause |
|---|---|
| `NullPointerException` on `RestContext.request` | The code ran outside a REST call, or a test did not assign the request. |
| Body arrives as an empty string | The handler returned `void` and never set `responseBody`. |
| Client receives 200 on a failed lookup | The handler returned `null` without setting `statusCode`. |
| Response has the wrong content type | The body was written manually and no `Content-Type` header was added. |
| Query value cannot be used as a number | `params` values are strings and were not converted. |
Exercise
A handler is declared global static void export(). It builds a CSV string called csv. Write the lines that send the CSV with status 200 and a suitable content type. Why can this handler not just return the string?
Show answer
Use RestResponse res = RestContext.response; res.statusCode = 200; res.addHeader('Content-Type', 'text/csv'); res.responseBody = Blob.valueOf(csv);. The handler returns void, so the platform has no returned value to serialize, and the body must be written to responseBody. A returned string would be serialized as a JSON string, with quotes and escaping, instead of being sent as raw CSV.
Exercise
Your test for a GET handler fails with a NullPointerException on the first line of the handler. The test builds a RestRequest and calls the method. What is missing?
Show answer
The test never assigned the request to RestContext.request. Building a RestRequest is not enough, because the handler reads RestContext.request. Add RestContext.request = req; and also RestContext.response = new RestResponse(); before calling the handler.
Exercise
What is the difference between requestURI and resourcePath, and which one would you use to read an Id that the caller put in the URL?
Show answer
resourcePath is the urlMapping pattern that matched, such as /services/apexrest/v1/Accounts/*. requestURI is the concrete path the caller used, such as /services/apexrest/v1/Accounts/001.... Use requestURI, for example requestURI.substringAfterLast('/'), to read the Id.