Sub topic 1
Apex callouts in brief: Http, HttpRequest and HttpResponse
Prerequisites
This chapter assumes you already know:
- Basic Apex syntax and classes.
- HTTP methods, headers and status codes.
- How to find your way around Salesforce Setup.
You don't need any Named Credential knowledge yet. This chapter covers the plain callout that later chapters improve.
What a callout is
A callout is a request that Apex sends to a service outside Salesforce, usually a REST API. Apex has three built-in classes for it:
| Class | Role |
|---|---|
| `HttpRequest` | Describes the request: endpoint, method, headers, body, timeout. |
| `Http` | Sends the request with `send()`. |
| `HttpResponse` | Holds the status code, headers and body that come back. |
The flow is the same every time. You build a request, send it, then check the response before you use it.
A first callout
The class below calls a weather endpoint with the URL written directly in the code.
public with sharing class PlainWeatherService {
public static String getForecast(String city) {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/v1/forecast?city='
+ EncodingUtil.urlEncode(city, 'UTF-8'));
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
req.setTimeout(20000);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new CalloutException(
'Weather API returned status ' + res.getStatusCode());
}
return res.getBody();
}
}Here is what each part does:
setEndpointtakes the full URL.EncodingUtil.urlEncodekeeps spaces and special characters in the city name from breaking it.setMethodtakes the HTTP verb as a string, such asGETorPOST.setTimeoutis in milliseconds. The default is 10,000 and the maximum is 120,000.sendblocks until the service answers or the timeout passes.getStatusCodeandgetBodyread the result. Check the status before you parse the body.
For a POST, add req.setBody(jsonString) and a Content-Type header.
Limits and common errors
- Unauthorized endpoint. With a raw URL, Salesforce blocks the call unless an admin adds a Remote Site Setting for that host. The error says the endpoint URL is not in the remote site settings.
- Uncommitted work pending. A callout fails if the same transaction has already done DML and not committed. Make the callout first, or move it to asynchronous Apex.
- Callouts from triggers. A trigger runs inside the save transaction, so it can't call out directly. Use
@future(callout=true)or Queueable Apex withDatabase.AllowsCallouts. - Governor limits. One transaction can make up to 100 callouts.
- Tests. Test methods can't make real callouts. The testing chapter covers mocks.
Why this is not enough
The example works, but the host is hardcoded and needs a Remote Site Setting. Real APIs also need credentials, such as a key in a header. If you paste that key into the class, it ends up in source control and in every sandbox copy. The next chapters fix this by moving the location and the authentication out of Apex.
Exercise
A trigger on Account must call an external API after an insert. Why does a direct new Http().send(req) inside the trigger fail, and what are two ways to fix it?
Show answer
The trigger runs inside the save transaction, so it cannot make a callout directly. The fixes are to run the callout in a method annotated @future(callout=true), or to enqueue a Queueable class that implements Database.AllowsCallouts.