Sub topic 3
A quick HTTP callout refresher
This chapter assumes you can read basic Apex, know what an HTTP request and a JSON body are, and have seen governor limits. It reviews the three classes behind every callout, so the later chapters can focus on moving that callout out of a trigger.
The three classes
Apex makes a callout with three classes:
HttpRequestdescribes what you send: the endpoint, the method, the headers, and the body.Httpsends the request. Itssendmethod blocks until the response arrives or the timeout expires.HttpResponseholds what comes back: the status code, the headers, and the body.
A minimal callout
The method below posts a JSON body and checks the result. It uses a Named Credential called Billing_API. The next chapter explains Named Credentials. For now, treat the callout: prefix as a placeholder that Salesforce replaces with the real base URL and adds the authentication.
public class BillingClient {
public static Boolean postAccounts(List<Account> accounts) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setTimeout(20000);
req.setBody(JSON.serialize(accounts));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() >= 200 && res.getStatusCode() < 300) {
return true;
}
System.debug(LoggingLevel.ERROR,
'Callout failed: ' + res.getStatusCode() + ' ' + res.getBody());
return false;
}
}Several details matter here:
setTimeouttakes milliseconds. The default is 10 seconds and the maximum is 120 seconds.Http.senddoes not throw an exception for a 4xx or 5xx response. It returns normally, so you must checkgetStatusCode()yourself.Http.senddoes throw aSystem.CalloutExceptionwhen the call cannot complete at all, for example on a timeout or an unreachable host.JSON.serializeturns sObjects, collections, and maps into a JSON string.JSON.deserializeUntypedandJSON.deserializedo the reverse for the response body.
Limits that apply to a callout
Each transaction has callout limits, and they shape the design in the chapters that follow:
| Limit | Value |
|---|---|
| Callouts per transaction | 100 |
| Timeout per callout | 120 seconds maximum |
| Total callout time per transaction | 120 seconds |
| Request or response size | 6 MB synchronous, 12 MB asynchronous |
The 100-callout cap is why you send one bulk request for many records. A trigger that makes one callout per record would hit it quickly, even before the trigger restriction becomes a problem.
Reading the response
A callout is not finished when send returns. Decide up front what success means and handle the response body.
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
Map<String, Object> body =
(Map<String, Object>) JSON.deserializeUntyped(res.getBody());
System.debug('Created: ' + body.get('created'));
}Keep the parsing close to the callout. If the service returns a different shape than you expect, the cast fails with a TypeException, and you want that failure to be easy to find.
Exercise
A callout to an external service returns HTTP 500. Does Http.send throw an exception, and how does your code find out about the failure?
Show answer
No. Http.send returns an HttpResponse normally for 4xx and 5xx statuses. The code must check res.getStatusCode(). A CalloutException is thrown only when the call cannot complete, such as a timeout or an unreachable host.