Sub topic 1
Apex callouts in brief: Http, HttpRequest and HttpResponse
Prerequisites
This chapter assumes you can read and write basic Apex classes and static methods. It also assumes you know what an HTTP request is: a method such as GET or POST, headers, an optional body, and a status code in the response. You do not need to know anything about Named Credentials yet. Later chapters build on the three classes introduced here.
What a callout is
A callout is an outbound HTTP request that Apex code sends to a service outside Salesforce. Apex provides three classes for this, all in the System namespace:
| Class | Role |
|---|---|
| `HttpRequest` | Describes what to send: endpoint, method, headers, body, timeout. |
| `Http` | Sends a request. Its `send` method returns a response. |
| `HttpResponse` | Holds what came back: status code, headers, body. |
The flow is always the same. You build an HttpRequest, pass it to Http.send, and read the HttpResponse.
Building the request
HttpRequest has setters for each part of the message.
setEndpoint(String)sets the full URL.setMethod(String)setsGET,POST,PUT,PATCH,DELETEand so on.setHeader(String, String)sets one header. Call it once per header.setBody(String)sets a text body.setBodyAsBlob(Blob)sets a binary body.setTimeout(Integer)sets the timeout in milliseconds.
The default timeout is 10 seconds. The maximum is 120,000 milliseconds (120 seconds). A longer timeout does not help if the service is slow, because all callouts in one transaction share a 120-second total.
Always set Content-Type when you send a body, and Accept when you care about the response format. Many services reject a body that has no content type.
Sending and reading the response
Http.send is synchronous. Your code waits until the response arrives or the timeout expires. The HttpResponse offers these getters:
getStatusCode()returns an integer such as 200 or 404.getStatus()returns the text, such asOK.getBody()returns the body as a String.getBodyAsBlob()returns it as a Blob.getHeader(String)returns one header value, or null if it is absent.
A complete example
The class below posts JSON to a URL and returns the response body. It uses a plain URL, which is the approach the rest of this tutorial replaces.
public with sharing class HttpBasics {
public static String postJson(String url, Map<String, Object> payload) {
HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setHeader('Accept', 'application/json');
req.setTimeout(20000);
req.setBody(JSON.serialize(payload));
HttpResponse res;
try {
res = new Http().send(req);
} catch (System.CalloutException e) {
throw new CalloutException('Could not reach ' + url + ': ' + e.getMessage());
}
Integer code = res.getStatusCode();
if (code >= 200 && code < 300) {
return res.getBody();
}
throw new CalloutException('Service returned ' + code + ' ' + res.getStatus());
}
}Three details in this code matter in real projects.
JSON.serializebuilds the body from a map, so you do not concatenate JSON by hand. Hand-built JSON breaks as soon as a value contains a quote.- The
tryandcatchhandle transport failures.Http.sendthrows aSystem.CalloutExceptionwhen the host cannot be reached, the connection drops, or the timeout expires. In those cases you never get anHttpResponse. - The status check handles service-level failures. A 400, 404 or 500 does not throw. You receive a normal
HttpResponseand must inspect the status code yourself.
Two kinds of failure
Beginners often handle only one of these, so keep them apart.
| Failure | What you see | How to handle it |
|---|---|---|
| Transport failure (timeout, DNS error, connection reset) | `System.CalloutException` thrown from `send` | Catch the exception. |
| Service failure (401, 404, 429, 500) | A normal `HttpResponse` with that status code | Check `getStatusCode()`. |
Redirects belong to the second kind. Apex does not follow a 301 or 302 for you. If the service redirects, read the Location header and send a new request.
Platform rules that shape callout code
Salesforce enforces several rules on callouts. You will meet each of them early.
Allowed endpoints
Salesforce blocks callouts to a URL unless the host is approved. With a plain URL, an administrator must add it under Remote Site Settings, or the call fails with an "Unauthorized endpoint" error. Named Credentials remove this step, because the credential itself authorizes the endpoint. Later chapters cover that.
Limits
- One transaction can make up to 100 callouts.
- The combined time of all callouts in a transaction is limited to 120 seconds.
- Request and response sizes count against the heap limit. The heap limit is 6 MB for synchronous code and 12 MB for asynchronous code.
No callouts after uncommitted DML
If your transaction has inserted, updated or deleted records and has not committed, a callout fails with "You have uncommitted work pending. Please commit or rollback before calling out." Make the callout first, or move it into a separate transaction.
Where callouts can run
Triggers cannot make synchronous callouts, because a trigger runs inside a database transaction. Move the callout to asynchronous Apex:
public with sharing class AccountSync implements Queueable, Database.AllowsCallouts {
private final Id accountId;
public AccountSync(Id accountId) {
this.accountId = accountId;
}
public void execute(QueueableContext context) {
Account acc = [SELECT Id, Name FROM Account WHERE Id = :accountId];
HttpBasics.postJson('https://api.example.com/accounts',
new Map<String, Object>{ 'id' => acc.Id, 'name' => acc.Name });
}
}A trigger handler would enqueue this job with System.enqueueJob(new AccountSync(acc.Id)). The Database.AllowsCallouts marker interface is required. Without it, the callout throws an error. A method annotated @future(callout=true) is the older alternative.
Tests cannot send real callouts
A test method that reaches Http.send without a mock fails with "Methods defined as TestMethod do not support Web service callouts". The testing chapter shows how to use HttpCalloutMock.
Why this is not enough
The example above has two weaknesses.
- The URL is stored in code. Moving from a sandbox to production means editing and redeploying Apex.
- Authentication has no safe place to live. If the service needs an API key, you would add something like
req.setHeader('X-Api-Key', 'abc123'). That puts a secret in source control, in debug logs and in every org where the class is deployed.
The next chapters address both problems. A Named Credential holds the location, an External Credential holds the authentication, and Apex refers to them only by name.
Practical habits
- Treat any status outside 200 to 299 as an error unless you have a reason not to.
- Include the status code and a trimmed body in your exception message. It saves time when you read logs.
- Keep the code that builds and sends the request in one small class. Test code can then mock it with one
HttpCalloutMock. - Set a timeout deliberately. The 10-second default is often too short for slow reporting APIs and too long for a user-facing page.
Exercise
A callout to a partner API returns a response with status code 503. Does Http.send throw an exception, and how should your code detect the failure? Name one other situation that does throw a System.CalloutException.
Show answer
No exception is thrown. A 503 is a normal HTTP response, so send returns an HttpResponse and your code must check getStatusCode() (for example, treat anything outside 200 to 299 as an error). A System.CalloutException is thrown for transport problems, such as a timeout (no response within setTimeout), a host that cannot be reached, or an endpoint that is not authorized.
Exercise
A trigger on Account calls new Http().send(req) directly and the save fails. Describe a fix that keeps the callout and name the interface the fix requires.
Show answer
Move the callout into asynchronous Apex. The trigger (or its handler) enqueues a Queueable job with System.enqueueJob, and the job class implements Queueable and Database.AllowsCallouts. The callout then runs in its own transaction, after the trigger's transaction has committed.