Sub topic 5
Building a request: method, headers, body and timeout
This chapter covers the four parts of an HttpRequest that you set on almost every callout: the method, the headers, the body and the timeout. It assumes you know basic Apex syntax and exceptions, HTTP methods, status codes and headers, and basic JSON. It also assumes you can create a Named Credential in Setup. The earlier chapters introduced the Http, HttpRequest and HttpResponse classes and the callout: prefix. Here you will put them to work.
The shape of a request
An HttpRequest is a plain object. You create it, set properties on it, and pass it to Http.send(). Nothing leaves Salesforce until send() runs, so you can build the request in a helper method and test it separately.
A request needs two things to be valid: an endpoint and a method. Everything else is optional, but real services usually expect at least a content type or an accept header.
| Setter | Purpose | Notes |
|---|---|---|
| `setEndpoint(String)` | The URL, or a `callout:` Named Credential URL | Required |
| `setMethod(String)` | The HTTP verb | Required in practice |
| `setHeader(String, String)` | One request header | Call once per header |
| `setBody(String)` | Request body as text | Used by POST, PUT, PATCH |
| `setBodyAsBlob(Blob)` | Request body as binary | For files and non-text data |
| `setTimeout(Integer)` | Timeout in milliseconds | 1 to 120000 |
| `setCompressed(Boolean)` | Compress the request body | Optional |
Endpoint and method
Prefer a Named Credential endpoint. The callout:Todo_API prefix is replaced at run time with the URL stored in the Named Credential, and the platform adds authentication for you. You append the path after the prefix.
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API/todos/1');
req.setMethod('GET');The method is a string. Salesforce accepts GET, POST, PUT, PATCH, DELETE, HEAD, TRACE and OPTIONS. Use upper case. The platform does not stop you from sending a body with a GET, but many servers ignore or reject it, so don't.
Query strings and URL encoding
When a path or parameter comes from user input or a record field, encode it. A space or an ampersand in an unencoded value changes the meaning of the URL.
String term = 'buy milk & eggs';
String endpoint = 'callout:Todo_API/todos?title='
+ EncodingUtil.urlEncode(term, 'UTF-8');
System.debug(endpoint);EncodingUtil.urlEncode turns spaces into + and the ampersand into %26. Encode each value separately, not the whole URL, or you will also encode the ? and = characters that the server needs.
PATCH and older clients
PATCH is accepted by setMethod in current API versions. If a service you call only supports PATCH through a header override, some teams send a POST with X-HTTP-Method-Override: PATCH. Check the service documentation before using that trick, because it only works if the server supports it.
Headers
Each setHeader call sets one header. Calling it again with the same name replaces the earlier value. You can read a header back with getHeader.
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API/todos');
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
req.setHeader('User-Agent', 'MySalesforceOrg/1.0');
System.debug(req.getHeader('Accept'));The headers that matter most for JSON services are these:
Content-Typedescribes the body you send. Useapplication/jsonfor JSON andapplication/x-www-form-urlencodedfor form data.Accepttells the server which format you want back.Authorizationcarries credentials. With a Named Credential, let the platform set it. Do not build it by hand.
Authentication headers
Never hard-code a token or API key in Apex. Source code is visible to anyone with access to the org's metadata, and it ends up in version control. A Named Credential keeps the secret in Setup, outside your code. If a service needs a custom header with a secret, such as X-Api-Key, define it in the Named Credential configuration where your org's setup supports it, rather than reading it from a custom setting and writing it into the request.
Headers you cannot control
The platform sets some headers itself, such as Host and Content-Length. Setting Content-Length by hand is unnecessary and can cause errors. Let the runtime compute it from the body.
The body
The body is a string. For JSON, you rarely write it by hand. You build a typed Apex object and serialize it, as the next chapters show in detail. A short version looks like this:
public with sharing class TodoClient {
public class Todo {
public Integer id;
public Integer userId;
public String title;
public Boolean completed;
}
public static Todo create(Todo newTodo) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API/todos');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(newTodo, true));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 201) {
throw new CalloutException('Create failed with status ' + res.getStatusCode());
}
return (Todo) JSON.deserialize(res.getBody(), Todo.class);
}
}Three points in this code are worth stopping on.
JSON.serialize(newTodo, true)has a second argument,suppressApexObjectNulls. When it istrue, fields that arenullare left out of the JSON. Here that means a new todo is sent without anid, and the server assigns one. Withfalse, the body would contain"id":null, which some servers reject.- The
Content-Typeheader matches the body. A mismatch is a common cause of400and415responses. The server may read a JSON body as plain text and fail to parse it. - The code checks for
201, not200. A create call usually returns201 Created. Check the documentation for the status code the service actually returns.
Binary bodies
Use setBodyAsBlob when the body is not text, for example a PDF. Set the Content-Type to the file's media type. Do not call both setBody and setBodyAsBlob on one request. The later call replaces the earlier one.
Blob fileData = Blob.valueOf('example file content');
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API/upload');
req.setMethod('PUT');
req.setHeader('Content-Type', 'application/octet-stream');
req.setBodyAsBlob(fileData);Heap size
A request body and its response both count against the heap limit, which is 6 MB for synchronous Apex and 12 MB for asynchronous Apex. Request and response bodies are also limited in size by the platform. Building a very large JSON string in memory is the usual way to hit the heap limit. If you must send large data, split it into batches of records and send them in separate callouts.
The timeout
By default, a callout waits 10 seconds for a response. If the server is slower, send() throws a System.CalloutException with a message such as Read timed out. You change the wait with setTimeout, which takes milliseconds.
req.setTimeout(20000); // 20 secondsThe allowed range is 1 to 120,000 milliseconds, which is 120 seconds. A value outside that range is not accepted.
Choose a timeout on purpose. A longer timeout makes the call more tolerant of slow services, but it also keeps your transaction open longer. Callout time counts toward the cumulative limit of 120 seconds across all callouts in one transaction. Three callouts that each wait 60 seconds will exceed it. A shorter timeout fails fast and frees the transaction, which is better for a user waiting on a page.
A timeout does not mean the server did nothing. The request may have arrived and the server may have processed it, even though your code never saw the answer. For a POST that creates a record, a retry after a timeout can create a duplicate. If the service supports an idempotency key, send it in a header so retries are safe.
Timeout of the Named Credential
A Named Credential can also have its own settings, but the timeout you set on the request is the one Apex applies to that call. Set it explicitly instead of relying on the default, so the behavior is visible in the code.
A reusable builder
When several methods in a class build similar requests, put the shared setup in one place. This keeps headers and timeouts consistent.
public with sharing class TodoRequestFactory {
private static final Integer DEFAULT_TIMEOUT_MS = 20000;
public static HttpRequest build(String method, String path, String jsonBody) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API' + path);
req.setMethod(method);
req.setHeader('Accept', 'application/json');
req.setTimeout(DEFAULT_TIMEOUT_MS);
if (jsonBody != null) {
req.setHeader('Content-Type', 'application/json');
req.setBody(jsonBody);
}
return req;
}
}The factory sets Content-Type only when there is a body. A GET then carries no misleading content type. A caller uses it like this:
HttpRequest getReq = TodoRequestFactory.build('GET', '/todos/1', null);
HttpResponse res = new Http().send(getReq);
System.debug(res.getStatusCode());Common mistakes
- Forgetting the method. An
HttpRequestwithoutsetMethodfails or behaves unpredictably. Always set it. - Wrong content type. The body is JSON but the header says text, or the header is missing. The server returns
400or415. - Unencoded values in the URL. Special characters break the query string or change its meaning.
- Default timeout assumed to be enough. Ten seconds is short for some services. Set the value you need.
- Secrets in code. Use a Named Credential.
- Sending
nullfields. UseJSON.serialize(obj, true)when the server treatsnulland "absent" differently.
Inspecting a request while you develop
Before you send a request, print what you built. The debug log shows the method, endpoint and body, so you can compare them to the service documentation.
HttpRequest req = TodoRequestFactory.build('POST', '/todos', '{"title":"Test"}');
System.debug(req.getMethod() + ' ' + req.getEndpoint());
System.debug(req.getBody());
System.debug(req.getHeader('Content-Type'));HttpRequest.toString() also returns a readable summary. Do not log request bodies that contain personal data in a production org, because debug logs are visible to administrators and developers.
Summary
Set the endpoint through a Named Credential and the method as an upper-case string. Add Accept and, when there is a body, a matching Content-Type. Serialize typed objects instead of hand-writing JSON. Set the timeout explicitly, and remember that a timeout leaves the outcome on the server unknown. Centralize the shared setup in a factory so every request is consistent.
Exercise
A POST callout sends a JSON body, but the service answers 415 Unsupported Media Type. The code calls setBody(JSON.serialize(obj)) and never calls setHeader. What is the most likely cause, and what is the fix?
Show answer
The request has no Content-Type header, so the server does not know the body is JSON. Add req.setHeader('Content-Type', 'application/json') before sending.
Exercise
A callout to a slow service fails with "Read timed out" after 10 seconds. You change the timeout to 150000 milliseconds. Why does this not work, and what value range is allowed?
Show answer
The allowed range is 1 to 120000 milliseconds, so 150000 is out of range. Use a value up to 120000, and keep in mind that all callouts in one transaction share a cumulative 120 second limit. For work that routinely takes longer, move the callout to asynchronous Apex or consider a Continuation.
Exercise
Why might retrying a POST that timed out create a duplicate record, and how can you reduce that risk?
Show answer
A timeout only means your code did not receive a response. The server may already have processed the request. Send an idempotency key in a header, if the service supports one, so the server can recognize and ignore the repeated request.