Sub topic 5
Building a Request: Method, Headers, Body and Timeout
This chapter assumes you know basic Apex syntax and exceptions, HTTP methods, status codes and headers, and that you have a Named Credential called Todo_API set up in Setup. Here you will build an HttpRequest piece by piece.
The shape of a request
An HttpRequest holds everything the remote service needs to see: where to send it, which verb to use, which headers to include, an optional body, and how long to wait. You set each part with a setter method, then pass the finished object to Http.send().
| Part | Setter | Notes |
|---|---|---|
| Endpoint | `setEndpoint(String)` | Use `callout:Named_Credential/path` so the platform adds the base URL and authentication. |
| Method | `setMethod(String)` | `GET`, `POST`, `PUT`, `PATCH`, `DELETE` and so on. |
| Header | `setHeader(String, String)` | Call once per header name. |
| Body | `setBody(String)` | Text body, usually JSON. |
| Timeout | `setTimeout(Integer)` | Milliseconds, from 1 to 120000. |
Endpoint and method
The endpoint is a string. With a Named Credential, the part after callout:Todo_API is appended to the credential's base URL. The method is also a string, and Apex expects it in upper case.
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API/todos/' + todoId);
req.setMethod('GET');If you build the path from user input, encode it with EncodingUtil.urlEncode(value, 'UTF-8') so special characters cannot change the meaning of the URL.
Headers
Headers tell the service what you send and what you accept. Two matter most:
Content-Typedescribes the body you are sending. Set it whenever you send a body.Accepttells the service which format you want back.
Do not set an Authorization header yourself when a Named Credential already handles authentication. The credential adds it for you, and keeping secrets out of your code is the point of using one.
Body
A GET request normally has no body. For POST, PUT and PATCH, call setBody with a string. Apex also offers setBodyAsBlob for binary content. Chapter content on JSON covers building the string. For now, notice that the body and the Content-Type header must agree. If you send JSON but forget the header, many services reject the request or misread it.
Timeout
The default timeout is 10 seconds. Set it explicitly so the behavior is visible in your code. The maximum is 120 seconds, and a single transaction can spend at most 120 seconds in total across all its callouts. If the service does not answer in time, send throws a System.CalloutException.
Putting it together
The next method sends a POST. It sets every part described above.
public with sharing class RequestBuilder {
public static HttpRequest buildCreateRequest(String jsonBody) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API/todos');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setHeader('Accept', 'application/json');
req.setBody(jsonBody);
req.setTimeout(20000);
return req;
}
}Returning the request instead of sending it makes the builder easy to unit test: you can assert on the method, headers and body without making a call.
The flow of a request is shown below.
Common errors
- Lowercase or misspelled method. Use
'POST', not'post'or'Post'. - Missing
Content-Type. The service may answer415 Unsupported Media Typeor400. - Body on a GET. Some services ignore it and others reject it. Avoid it.
- Relying on the default timeout. A slow service fails after 10 seconds. Set a value that fits the service.
- Hard-coded URLs and credentials. These need a Remote Site Setting and expose secrets. Use the
callout:prefix.
Exercise
You send a POST with a JSON string in setBody, but the service replies 415 Unsupported Media Type. Which part of the request is most likely missing, and what should you add?
Show answer
The Content-Type header is most likely missing. Add req.setHeader('Content-Type', 'application/json') so the service knows the body is JSON.
Exercise
A callout to a slow service fails after about 10 seconds with a CalloutException, although the service would have answered in 15 seconds. What do you change?
Show answer
Call req.setTimeout with a larger value in milliseconds, for example req.setTimeout(20000). The default is 10 seconds and the maximum is 120000 milliseconds.