Sub topic 5
Request-reply: calling out and waiting for an answer
This chapter assumes you know basic Apex, HTTP methods and status codes, and JSON. It also assumes you have read the chapters on synchronous versus asynchronous communication and on Named Credentials.
What request-reply means
In request-reply, Salesforce sends a request to an external system and waits for the response before it continues. The caller and the responder are tightly coupled in time. If the external system is slow or down, your code feels it right away.
Use this pattern when the next step depends on the answer. Examples are checking an invoice status before showing it on a page, validating an address, or fetching a price quote.
A working callout
The class below calls a billing system through a Named Credential called Billing_API. The endpoint starts with callout:, so Salesforce supplies the host and the credentials. No secret appears in code.
public with sharing class InvoiceClient {
public static String fetchInvoiceStatus(String invoiceId) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/invoices/' + EncodingUtil.urlEncode(invoiceId, 'UTF-8'));
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
req.setTimeout(10000);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
Map<String, Object> body = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (String) body.get('status');
}
throw new CalloutException('Billing API returned ' + res.getStatusCode());
}
}Here is what each part does:
callout:Billing_API/...resolves to the base URL stored in the Named Credential. The path after the name is appended to it.EncodingUtil.urlEncodeprotects the URL from unsafe characters in the ID.setTimeout(10000)limits the wait to 10 seconds. The default is 10 seconds and the maximum is 120 seconds.new Http().send(req)blocks until a response arrives or the timeout expires.- The status code check keeps an error page from being parsed as data.
Failure behavior
Request-reply fails in the caller's transaction, so you must handle failures there. Three kinds of failure matter.
- Transport failures. A timeout or an unreachable host throws a
System.CalloutException. No status code exists. Catch it. - HTTP errors. A
4xxor5xxresponse is not an exception.sendreturns normally, and your code must inspect the status. - Bad payloads. A
200response with an unexpected body can still cause aJSONExceptionor a null value.
A 4xx usually means the request is wrong, so retrying will not help. A 5xx, a 429, or a timeout may be temporary, so a limited retry can help. Retries are covered in a later chapter.
Rules that constrain callouts
Several platform rules shape how you write this pattern. Limits get a full chapter later, but these three affect your first callout.
- Uncommitted work. Apex cannot make a callout after a DML statement in the same transaction. The error is "You have uncommitted work pending." Make the callout first, or move it to a separate transaction.
- Triggers. A callout cannot run directly in a trigger, because a trigger runs inside the save transaction. Hand the work to an asynchronous context such as Queueable Apex that implements
Database.AllowsCallouts. - Time and count. A transaction has a cap on the number of callouts and on the total time spent waiting. A slow external system uses up your synchronous time budget.
public with sharing class InvoiceSync implements Queueable, Database.AllowsCallouts {
private final Id accountId;
private final String invoiceId;
public InvoiceSync(Id accountId, String invoiceId) {
this.accountId = accountId;
this.invoiceId = invoiceId;
}
public void execute(QueueableContext ctx) {
String status = InvoiceClient.fetchInvoiceStatus(invoiceId);
update new Account(Id = accountId, Description = 'Invoice status: ' + status);
}
}Note that the callout runs before the update, which respects the uncommitted work rule. Starting this job from a trigger with System.enqueueJob turns the pattern into a hybrid. The trigger does not wait, but the job itself still makes a request-reply call.
When request-reply fits
| Question | Fits request-reply | Look elsewhere |
|---|---|---|
| Does the user or next step need the answer now? | Yes | No |
| Is the volume small per transaction? | Yes | Thousands of records |
| Can the external system respond in a few seconds? | Yes | Slow or unreliable |
| Must the two systems stay independent of each other? | No | Yes |
Exercise
A trigger on Opportunity must look up a credit score from an external service and save it on the record. Why does a direct callout in the trigger fail, and what is a safe design?
Show answer
A trigger runs inside the save transaction, and Apex does not allow a callout there. The callout would also hold the transaction open while it waits. A safe design is to enqueue a Queueable job that implements Database.AllowsCallouts. The job makes the callout through a Named Credential, checks the HTTP status, and then updates the record in its own transaction.
Exercise
A callout returns HTTP 503. Does Http.send throw an exception? What should the code do?
Show answer
No. Http.send returns an HttpResponse with status code 503, and only transport failures such as timeouts throw CalloutException. The code must check getStatusCode(). A 503 may be temporary, so the code can retry a limited number of times or report the failure to the caller.