Sub topic 2
The Http, HttpRequest and HttpResponse classes
This chapter assumes you know basic Apex syntax and exceptions, and that you know HTTP methods, status codes and headers. You will meet the three classes that every Apex callout uses and see how they divide the work.
Three classes, three jobs
Apex models an HTTP exchange with three classes in the System namespace. You don't need to import them.
| Class | Role | Typical members |
|---|---|---|
| `HttpRequest` | Describes what to send | `setEndpoint`, `setMethod`, `setHeader`, `setBody`, `setTimeout` |
| `Http` | Sends the request | `send(HttpRequest)` |
| `HttpResponse` | Describes what came back | `getStatusCode`, `getStatus`, `getBody`, `getHeader` |
Http holds no state. It has one method that matters, send, which takes a request and returns a response. You build the request, hand it to send, and read the response.
A first complete callout
The class below sends a GET request through a Named Credential called Todo_API. Named Credentials are covered in a later chapter. For now, treat the callout: prefix as a way to name an authorized endpoint.
public with sharing class HttpBasics {
public static void showTodo() {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API/todos/1');
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
Http http = new Http();
HttpResponse res = http.send(req);
System.debug('Status code: ' + res.getStatusCode());
System.debug('Status text: ' + res.getStatus());
System.debug('Content-Type: ' + res.getHeader('Content-Type'));
System.debug('Body: ' + res.getBody());
}
}You can run this from Execute Anonymous with HttpBasics.showTodo(); once the Named Credential exists.
What each object exposes
An HttpRequest is a mutable bag of settings. Its setters are plain methods, and calling one twice replaces the earlier value. The method name is a string, so 'GET', 'POST', 'PUT', 'PATCH' and 'DELETE' all work. If you never call setMethod, the request is sent as a GET.
An HttpResponse is read-only in practice. It gives you these values:
getStatusCode()returns the numeric code, such as 200 or 404.getStatus()returns the reason text, such asOK.getBody()returns the body as aString.getBodyAsBlob()returns it as aBlob, which suits binary content.getHeader(name)returns one header value, ornullif the header is absent.getHeaderKeys()lists the header names.
You normally create an HttpResponse yourself only in tests, where a mock builds one to return.
Two kinds of failure
send reports problems in two different ways, and mixing them up causes common bugs.
- If the request cannot complete,
sendthrows aSystem.CalloutException. Examples are an unreachable host, a timeout, or an endpoint that has not been authorized. - If the server answers with an error such as 404 or 500,
senddoes not throw. It returns a normalHttpResponsewith that status code.
Instances and reuse
Create a new HttpRequest for each call. Reusing one object across calls is possible, but it carries over stale headers and bodies. An Http instance is cheap, so new Http() inline is fine.
Each call to send counts as one callout against the governor limit for the transaction. Creating the objects costs nothing against that limit. Only send does.
Exercise
A callout returns a response with status code 503. Does http.send(req) throw a CalloutException? How should the calling code find out about the failure?
Show answer
No. A 503 is a valid HTTP response, so send returns an HttpResponse normally. The calling code must check res.getStatusCode() and decide how to handle a non-success status, for example by throwing its own exception. A CalloutException is thrown only when the call cannot complete, such as on a timeout or an unauthorized endpoint.