Sub topic 3
A quick HTTP callout refresher
This chapter reviews the Apex classes you use to call an external HTTP service. The rest of the tutorial moves these calls out of triggers and into asynchronous code, so the callout itself needs to be solid first. It assumes you can read Apex, know what a governor limit is, and understand HTTP verbs, status codes and JSON.
The three classes
A callout in Apex uses three built-in classes:
| Class | Role |
|---|---|
| `HttpRequest` | Describes what to send: endpoint, method, headers, body, timeout. |
| `Http` | Sends the request. Its `send` method blocks until a response arrives or the call times out. |
| `HttpResponse` | Holds what came back: status code, headers, body. |
You build the request, pass it to Http.send, and read the response. Nothing is sent until you call send.
A complete callout
The class below wraps one GET request. It assumes a Named Credential called Billing_API exists in your org. The next chapter covers how to set one up.
public class BillingClient {
public class BillingException extends Exception {}
public static Map<String, Object> getAccount(String externalId) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts/' + EncodingUtil.urlEncode(externalId, 'UTF-8'));
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
req.setTimeout(20000);
HttpResponse res;
try {
res = new Http().send(req);
} catch (CalloutException e) {
throw new BillingException('Callout failed: ' + e.getMessage());
}
Integer code = res.getStatusCode();
if (code < 200 || code >= 300) {
throw new BillingException('Unexpected status ' + code + ': ' + res.getBody());
}
return (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
}
}Each part of this class has a job.
setEndpointtakes a full URL, or acallout:reference to a Named Credential followed by a path.setMethodtakes a verb as a string.GET,POST,PUT,PATCHandDELETEall work.setHeadercan be called once per header.setTimeouttakes milliseconds.sendthrows aCalloutExceptionwhen the call cannot complete, for example on a timeout or an unreachable host.- A non-2xx response does not throw. You must check the status code yourself.
The last point causes many silent bugs. A 500 or 404 response arrives as a normal HttpResponse, and code that never checks getStatusCode() treats it as success.
Sending a body
A POST or PUT needs a body and a Content-Type header. For JSON, serialize a collection or a typed class with JSON.serialize.
public class BillingPoster {
public static HttpResponse postAccounts(List<Account> accounts) {
List<Map<String, Object>> payload = new List<Map<String, Object>>();
for (Account a : accounts) {
payload.add(new Map<String, Object>{ 'id' => a.Id, 'name' => a.Name });
}
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(payload));
return new Http().send(req);
}
}Building a small map for each record, instead of serializing the whole Account, controls exactly which fields leave Salesforce. Serializing an sObject sends every field that was queried, plus an attributes entry.
setBody takes a String. If you need binary content, use setBodyAsBlob. For the response, getBody returns a string and getBodyAsBlob returns a blob.
Reading the response
HttpResponse gives you three things to inspect.
getStatusCode()returns the integer code, such as200or404.getStatus()returns the reason text, such asOK.getBody()returns the payload as a string.getHeader('Name')returns one header value.
To parse JSON, you have two options. JSON.deserializeUntyped returns nested Map<String, Object> and List<Object> values, and you cast as you go. JSON.deserialize(body, MyType.class) fills a typed Apex class, which is easier to read when the response shape is stable.
public class AccountResult {
public String id;
public String status;
}
HttpResponse res = new Http().send(req);
AccountResult parsed = (AccountResult) JSON.deserialize(res.getBody(), AccountResult.class);
System.debug(parsed.status);Apex does not allow reserved words as property names. If the remote JSON uses a key like type or number, deserialize untyped, or rename the key in the class and handle the mapping yourself.
Limits that apply to every callout
Governor limits apply to callouts the same way they apply to queries and DML. These are the ones to know.
| Limit | Value |
|---|---|
| Callouts per transaction | 100 |
| Timeout per callout | 10 seconds by default, 120 seconds maximum |
| Cumulative callout time per transaction | 120 seconds |
| Request or response size | 6 MB synchronous, 12 MB asynchronous |
The cumulative timeout matters more than the per-call value. Ten callouts that each wait 15 seconds will exhaust the 120-second budget even though each one is under its own timeout. Setting a timeout that fits the real service, rather than always 120000, keeps one slow endpoint from consuming the whole budget.
The size limits are also checked against heap. A large response that you parse into maps can hit the heap limit before it reaches the size limit, so request only the fields you need.
Endpoints must be authorized
Apex only calls endpoints the org has approved. There are two ways to approve one:
- A Named Credential. The
callout:Namesyntax uses it, and it also stores the authentication settings. - A Remote Site Setting, for a plain URL such as
https://api.example.com/accounts.
If neither exists for the endpoint, send throws a CalloutException with a message like "Unauthorized endpoint". The fix is configuration, not code.
Named Credentials are the better choice. They keep secrets out of Apex, handle token refresh for OAuth, and let you change the host per environment without a code change. The next chapter covers them.
Where callouts are not allowed
Two restrictions affect how you structure the code in this tutorial.
- After uncommitted DML in the same transaction. If you insert or update a record and then call
sendbefore the transaction commits, Apex throws aCalloutExceptionwith the message "You have uncommitted work pending". This is the reason triggers cannot call out directly, and the next chapters build on it. - In tests, without a mock. Test code cannot reach a real endpoint. A test that reaches
sendwithout a registered mock fails with "Methods defined as TestMethod do not support Web service callouts". A later chapter shows how to supply mocks withTest.setMock.
Common mistakes
- Not checking the status code. A
4xxor5xxresponse does not raise an exception. - Catching only
CalloutException. Parsing a bad body raisesJSONException, and casting a wrong shape raisesTypeException. - Hardcoding credentials in headers. Use a Named Credential so the secret never appears in code or debug logs.
- Logging full request bodies. Logs can contain customer data. Log the status code and a short identifier instead.
- Forgetting URL encoding. Query values built from record data should go through
EncodingUtil.urlEncode. - Using the default timeout without thinking. Ten seconds is short for some services and too long for others. Set it on purpose.
Check your understanding
Exercise
A callout to your billing service returns HTTP 503, but your Apex code continues as if the sync worked. Why does this happen, and what is the minimum change that fixes it?
Show answer
Http.send throws a CalloutException only when the call cannot complete, such as a timeout or unreachable host. A 503 is a valid HTTP response, so it comes back as a normal HttpResponse and nothing is thrown. The fix is to read res.getStatusCode() after send and treat anything outside 200 to 299 as a failure, for example by logging it or throwing an exception.
Exercise
You make 12 callouts in one transaction. Each has a 15-second timeout, and the remote service takes 14 seconds to answer every time. Which limit do you hit, and at roughly which callout?
Show answer
You hit the cumulative callout time limit of 120 seconds, not the 100-callout limit and not the per-call timeout. Each call finishes within its 15-second timeout, but 8 calls at 14 seconds use 112 seconds, so the 9th call pushes the transaction over 120 seconds and it fails.