Sub topic 2
The Http, HttpRequest and HttpResponse classes
This chapter assumes you can write basic Apex (classes, methods, collections, exceptions) and that you know HTTP methods, status codes and headers. It covers the three classes that make up every Apex callout and what each one does and doesn't do. Later chapters cover authorization, request building, JSON and error handling in more depth.
Three classes, three jobs
Apex splits a callout into three objects. Each has one job.
| Class | Job | Typical members |
|---|---|---|
| `Http` | Sends a request and waits for the reply | `send(HttpRequest)` |
| `HttpRequest` | Describes what to send | `setEndpoint`, `setMethod`, `setHeader`, `setBody`, `setTimeout` |
| `HttpResponse` | Describes what came back | `getStatusCode`, `getStatus`, `getHeader`, `getBody` |
All three are in the System namespace, so you don't need an import. You create each one with a no-argument constructor. Http has almost no state of its own. It is only the sender.
The flow is the same every time:
- Create an
HttpRequestand configure it. - Pass it to
Http.send. - Read the
HttpResponsethatsendreturns.
A first complete callout
This anonymous Apex fetches one todo item and prints the parts of the response. It uses a Named Credential called Todo_API, which is set up in a later chapter. Until you have that credential, the callout: endpoint will fail. Any authorized endpoint works in its place.
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());Notice the order. You configure the request fully before you call send. Once the call is made, the request has already left Salesforce, so changing req afterwards does nothing to that call.
HttpRequest in detail
HttpRequest is a plain data holder. Nothing is validated until send runs, so a bad endpoint or method shows up as an error at that point, not when you call the setter.
Endpoint and method
setEndpoint(String)takes a full URL or acallout:Named Credential URL.getEndpoint()returns what you set.setMethod(String)takes the verb as a string. Use uppercase:GET,POST,PUT,PATCH,DELETE,HEAD,TRACE. There is no enum, so a typo such as'Gett'is not caught by the compiler.
If you never call setMethod, you can't rely on a default. Always set it.
Headers
setHeader(String key, String value) sets one header. Calling it again with the same key replaces the earlier value. getHeader(String key) returns the value you set, or null if there is none.
Common headers you set yourself:
Content-Typewhen you send a body.Acceptto say what format you want back.Authorization, but only when you aren't using a Named Credential. Don't put secrets in code.
Body
Which setter you use depends on the data:
| Method | Use it for |
|---|---|
| `setBody(String)` | JSON, form-encoded text, plain text |
| `setBodyAsBlob(Blob)` | Binary data such as files or images |
| `setBodyDocument(Dom.Document)` | XML built with the `Dom` classes |
Each setter has a matching getter (getBody, getBodyAsBlob, getBodyDocument). A request has one body, so use one setter per request.
Timeout and compression
setTimeout(Integer) takes milliseconds. The default is 10,000 (10 seconds) and the maximum is 120,000 (120 seconds). Setting a value above the maximum is an error. The timeout covers waiting for the service, and it also counts against the cumulative 120-second callout limit for the transaction.
setCompressed(Boolean) tells Salesforce whether to compress the request body with gzip. It is rarely needed.
HttpResponse in detail
Http.send returns a fully built HttpResponse. You read from it. You only set values on it inside tests, as the mock chapter shows.
| Method | Returns |
|---|---|
| `getStatusCode()` | The numeric code, such as `200` or `404` |
| `getStatus()` | The reason phrase, such as `OK` or `Not Found` |
| `getHeader(String)` | One header value, or `null` if absent |
| `getHeaderKeys()` | A `List<String>` of all header names |
| `getBody()` | The body as a `String` |
| `getBodyAsBlob()` | The body as a `Blob` |
| `getBodyDocument()` | The body parsed as an XML `Dom.Document` |
Use getStatusCode() for decisions in code. The text from getStatus() is for log messages, because servers can word it differently.
Listing every header
When a service behaves unexpectedly, print all the response headers. getHeaderKeys() is the way to do it:
public with sharing class ResponseInspector {
public static void dump(HttpResponse res) {
System.debug('HTTP ' + res.getStatusCode() + ' ' + res.getStatus());
List<String> keys = res.getHeaderKeys();
if (keys != null) {
for (String key : keys) {
System.debug(key + ': ' + res.getHeader(key));
}
}
System.debug('Body length: ' + res.getBody().length());
}
}The null check on keys is deliberate. getHeaderKeys() can return null when there are no headers, and a for loop over null throws a NullPointerException.
What send does and doesn't throw
Http.send separates two kinds of failure, and mixing them up is the most common error with these classes.
- The service answered with an error status.
sendreturns normally. A404or500is a validHttpResponse. Your code must check the status code. - No answer could be obtained.
sendthrowsSystem.CalloutException. This covers timeouts, unreachable hosts, TLS failures and unauthorized endpoints.
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API/todos/99999');
req.setMethod('GET');
try {
HttpResponse res = new Http().send(req);
if (res.getStatusCode() >= 200 && res.getStatusCode() < 300) {
System.debug('Success: ' + res.getBody());
} else {
System.debug('Service replied with error ' + res.getStatusCode());
}
} catch (CalloutException e) {
System.debug('No usable reply: ' + e.getMessage());
}A response with a bad status code goes through the else branch. A network failure goes through the catch. Handle both.
Behaviors worth knowing
Redirects
Apex does not follow HTTP redirects for you. A 301 or 302 comes back as an ordinary response with a Location header. If you need to follow it, read getHeader('Location'), build a new HttpRequest and call send again. Each follow-up counts as its own callout against your limit.
Reusing objects
One Http instance can send many requests, one after another:
Http http = new Http();
for (Integer i = 1; i <= 3; i++) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API/todos/' + i);
req.setMethod('GET');
HttpResponse res = http.send(req);
System.debug(i + ' -> ' + res.getStatusCode());
}Create a new HttpRequest for each call. Reusing one and changing a few fields works, but it makes it easy to leak a header or body from the previous call into the next.
Each send counts toward limits
Every send is one callout. A transaction may make at most 100, and the cumulative time across them is capped at 120 seconds. A callout inside a loop is the usual way to hit this, so keep the call count visible in your design. The limits chapter covers it fully.
Body size and memory
The body of a response is held in memory, so it counts against the heap limit. Reading a large response with getBody() and then converting it to other structures can use several times its size. For binary data, getBodyAsBlob() avoids a text decoding step.
Text and binary
getBody() decodes bytes into a String. If the content isn't text, such as a PDF, use getBodyAsBlob(). Decoding binary as text corrupts it, and no later step can restore the original bytes.
Putting the roles together
Real code wraps the three classes in one small method so callers never touch them. This version gives the caller either a good body or a clear exception:
public with sharing class SimpleGet {
public class SimpleGetException extends Exception {}
public static String get(String path) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API' + path);
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
req.setTimeout(15000);
HttpResponse res = new Http().send(req);
Integer code = res.getStatusCode();
if (code < 200 || code >= 300) {
throw new SimpleGetException('GET ' + path + ' failed: ' + code + ' ' + res.getStatus());
}
return res.getBody();
}
}The method does four things in order. It builds the request, sends it, checks the code, and only then returns the body. Later chapters extend each step, but the shape stays the same.
Common mistakes
- Forgetting
setMethod, then wondering why the service rejects the call. - Treating a non-2xx response as an exception that will be thrown for you.
- Setting
Content-Typebut sending no body, or the reverse. - Reading
getBody()for binary data. - Calling
sendafter DML in the same transaction. This causes an error that a later chapter explains. - Assuming
getHeaderreturns an empty string for a missing header. It returnsnull.
Exercise
A callout to a service returns HTTP 503. Does Http.send throw a CalloutException? How should your code find out about the failure, and what would a timeout do differently?
Show answer
No. A 503 is a valid reply, so send returns an HttpResponse normally. Your code must read getStatusCode() and treat anything outside 200-299 as a failure. A timeout means no reply arrived, so send throws a System.CalloutException, which you catch with try/catch.
Exercise
You need to download a PDF from a service. Which HttpResponse method should you call to read it, and why not getBody()?
Show answer
Call getBodyAsBlob(). getBody() decodes the bytes as text, which corrupts binary content such as a PDF. A Blob keeps the bytes exactly as received.