Sub topic 12
Making callouts from invocable methods
This chapter assumes you can write an @InvocableMethod with request and result classes, and that you know how bulk input reaches it. It covers what changes when the method calls an external web service.
Why callouts need extra care
A callout is an HTTP request from Apex to an outside system. Flow runs your method inside a transaction, and callouts follow rules that depend on what that transaction has already done.
- Uncommitted DML blocks callouts. If the transaction has inserted, updated, or deleted records and not yet committed, the callout fails with "You have uncommitted work pending."
- Limits apply per transaction. You get 100 callouts, and the combined wait time for all callouts is 120 seconds. Each callout times out after 10 seconds unless you call
setTimeout, which accepts up to 120 seconds. - Some flow types cannot call out directly. A before-save record-triggered flow cannot run a callout. An after-save record-triggered flow can only do it in its Run Asynchronously path.
Where callouts work
| Flow context | Callout from an Apex action |
|---|---|
| Screen flow, after a screen | Allowed. A screen commits earlier work. |
| Screen flow, after a Create/Update Records element and before any screen | Fails with uncommitted work pending. |
| Autolaunched flow, no DML before the action | Allowed. |
| Record-triggered flow, before save | Not allowed. |
| Record-triggered flow, after save, main path | Not allowed. |
| Record-triggered flow, Run Asynchronously path | Allowed. |
The practical rule is to put the callout before any DML, or after a screen, or in the asynchronous path.
A callout-safe method
Set callout=true on the annotation so the method is declared as calling an external system. Use a Named Credential for the endpoint. It keeps the URL and the secrets out of your code. The example assumes a Named Credential called Postal_Service.
public with sharing class AddressValidator {
public class Request {
@InvocableVariable(label='Postal Code' required=true)
public String postalCode;
}
public class Result {
@InvocableVariable(label='Is Valid')
public Boolean isValid;
@InvocableVariable(label='Error Message')
public String errorMessage;
}
@InvocableMethod(
label='Validate Postal Codes'
description='Calls the postal service once per request.'
category='Address'
callout=true
)
public static List<Result> validate(List<Request> requests) {
List<Result> results = new List<Result>();
for (Request req : requests) {
Result res = new Result();
if (String.isBlank(req.postalCode)) {
res.isValid = false;
res.errorMessage = 'Postal code is required.';
results.add(res);
continue;
}
try {
HttpRequest httpReq = new HttpRequest();
httpReq.setEndpoint('callout:Postal_Service/validate?code='
+ EncodingUtil.urlEncode(req.postalCode, 'UTF-8'));
httpReq.setMethod('GET');
httpReq.setTimeout(10000);
HttpResponse httpRes = new Http().send(httpReq);
res.isValid = httpRes.getStatusCode() == 200;
if (!res.isValid) {
res.errorMessage = 'Service returned status ' + httpRes.getStatusCode();
}
} catch (CalloutException e) {
res.isValid = false;
res.errorMessage = e.getMessage();
}
results.add(res);
}
return results;
}
}The method returns one result per request, in order, so a failed call for one record does not lose the others. A limit exception cannot be caught, so the loop still needs a ceiling.
Bulk input and the 100-callout limit
This method makes one callout per request. A record-triggered flow can pass up to 200 interviews in one call, which would break the 100-callout limit. You have three ways to deal with that:
- Send one callout for the whole list, if the API accepts batches.
- Deduplicate inputs, so repeated values share one callout.
- Enqueue a
Queueableclass that implementsDatabase.AllowsCallouts. This moves the work to a separate transaction with its own limits. The invocable method itself cannot be@future, but it can enqueue a queueable job. The flow gets no response from the callout in that case, so write the outcome back to a record.
Testing
Apex tests cannot make real callouts. Register a mock with Test.setMock before calling the method.
@IsTest
private class AddressValidatorTest {
private class SuccessMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{}');
return res;
}
}
@IsTest
static void returnsOneResultPerRequest() {
Test.setMock(HttpCalloutMock.class, new SuccessMock());
AddressValidator.Request good = new AddressValidator.Request();
good.postalCode = '12345';
AddressValidator.Request blank = new AddressValidator.Request();
Test.startTest();
List<AddressValidator.Result> results =
AddressValidator.validate(new List<AddressValidator.Request>{ good, blank });
Test.stopTest();
Assert.areEqual(2, results.size());
Assert.isTrue(results[0].isValid);
Assert.isFalse(results[1].isValid);
}
}Exercise
A screen flow uses Update Records on an Account, then immediately runs an Apex action that makes a callout. The action fails with "You have uncommitted work pending." Name two ways to fix the flow.
Show answer
Move the Apex action before the Update Records element so the callout runs before any DML. Or put a screen between the two elements, because a screen commits the transaction. Moving the callout to an asynchronous queueable job also works.