Sub topic 12
Making callouts from invocable methods
A callout is an HTTP request from Apex to an external system. Invocable methods are a common place to make one, because a flow often needs data or a decision from a service outside Salesforce. This chapter assumes you can write an @InvocableMethod with request and result classes and that you know why it receives a list. It also assumes you know what a flow transaction is. The sections below cover where a callout can run, how to write one that handles bulk input, and how to test it.
Why callouts need extra care in Flow
Apex enforces two rules for callouts:
- A callout cannot run while the transaction has uncommitted DML. The error is
You have uncommitted work pending. Please commit or rollback before calling out. - A transaction can make at most 100 callouts. The cumulative callout time must also stay under 120 seconds. Each single callout times out after 10 seconds unless you set
req.setTimeout(), which accepts up to 120000 milliseconds.
Flow adds a complication. You don't control when the platform commits. The same invocable method can run safely in one flow and fail in another, depending on what ran earlier in the transaction.
| Where the action runs | Callout from Apex action? |
|---|---|
| Screen flow, before any DML since the last screen | Yes |
| Screen flow, after a Create, Update, or Delete element in the same transaction | No. Uncommitted work error |
| Before-save record-triggered flow | No. Apex actions are not available here |
| After-save record-triggered flow, regular path | No. The triggering DML is still pending |
| After-save record-triggered flow, Run Asynchronously path | Yes |
| Autolaunched flow started from Apex that already did DML | No. Uncommitted work error |
A screen element ends the transaction and commits pending work. A screen flow can therefore do DML, show a screen, and then make a callout.
Marking the method with callout=true
@InvocableMethod has a callout attribute that defaults to false. Set it to true on any method that makes a callout:
@InvocableMethod(label='Look Up Postal Codes' callout=true category='Address')The attribute documents the intent, and it tells the platform that the action contacts an external system. It does not move the callout to a safe place in the transaction. The table above still applies.
A bulk-safe callout method
The method below looks up city names for postal codes through a named credential called Postal_API. A named credential stores the endpoint and authentication outside your code. Using callout:Postal_API/... as the endpoint means no URL or secret appears in Apex.
The design follows from the 100-callout limit. A record-triggered flow can hand the method up to 200 interviews in one call. One callout per request would use half the limit on a single action. The method therefore makes one callout per distinct postal code. It then maps the results back onto the inputs in the original order.
public with sharing class PostalCodeLookup {
public class Request {
@InvocableVariable(label='Postal Code' required=true)
public String postalCode;
}
public class Result {
@InvocableVariable(label='Is Success')
public Boolean isSuccess;
@InvocableVariable(label='City')
public String city;
@InvocableVariable(label='Error Message')
public String errorMessage;
}
@InvocableMethod(
label='Look Up Postal Codes'
description='Returns the city for each postal code using the Postal_API named credential.'
callout=true
category='Address'
)
public static List<Result> lookup(List<Request> requests) {
Map<String, Result> byCode = new Map<String, Result>();
for (Request req : requests) {
if (String.isBlank(req.postalCode) || byCode.containsKey(req.postalCode)) {
continue;
}
byCode.put(req.postalCode, callService(req.postalCode));
}
List<Result> results = new List<Result>();
for (Request req : requests) {
if (String.isBlank(req.postalCode)) {
results.add(failure('Postal code is blank.'));
} else {
results.add(byCode.get(req.postalCode));
}
}
return results;
}
private static Result callService(String code) {
if (Limits.getCallouts() >= Limits.getLimitCallouts()) {
return failure('Callout limit reached. Try fewer records.');
}
HttpRequest httpReq = new HttpRequest();
httpReq.setEndpoint('callout:Postal_API/lookup?code=' + EncodingUtil.urlEncode(code, 'UTF-8'));
httpReq.setMethod('GET');
httpReq.setTimeout(15000);
try {
HttpResponse httpRes = new Http().send(httpReq);
if (httpRes.getStatusCode() != 200) {
return failure('Service returned status ' + httpRes.getStatusCode());
}
Map<String, Object> body = (Map<String, Object>) JSON.deserializeUntyped(httpRes.getBody());
Result res = new Result();
res.isSuccess = true;
res.city = (String) body.get('city');
return res;
} catch (CalloutException e) {
return failure('Callout failed: ' + e.getMessage());
} catch (JSONException e) {
return failure('Unexpected response format.');
}
}
private static Result failure(String message) {
Result res = new Result();
res.isSuccess = false;
res.errorMessage = message;
return res;
}
}Several choices in this code matter:
- Deduplication. Two interviews with the same postal code share one callout and one
Resultobject. This is safe because the flow only reads the result. - Order preservation. The second loop walks the original list, so result
ialways belongs to requesti. - Limit guard.
Limits.getCallouts()counts callouts already made in the transaction, including those from earlier actions in the same flow. The guard turns a hardLimitExceptioninto a per-record failure. ALimitExceptioncannot be caught and would fail the whole transaction. - URL encoding. The postal code comes from user or record data, so it is encoded before it goes into the URL.
- Caught exceptions.
CalloutExceptionandJSONExceptionbecome per-record failures. The flow continues and can branch onisSuccess.
The last point is a trade-off. If you catch an exception and return a failure result, the fault connector never fires. Pick one signal. Return per-record failures when some records can succeed while others fail. Let the exception propagate when the entire action cannot work, such as a missing named credential or an authentication failure. An uncaught exception rolls back the transaction and follows the fault path. See the chapter on error handling for the details.
Async options when the transaction is not safe
Sometimes the flow must call out from a position where it is not allowed, for example on the regular path of a record-triggered flow. You have two options:
- Run Asynchronously path. In an after-save record-triggered flow, put the action on this path. The callout runs in its own transaction after the triggering save commits. This is the simplest fix and the one to try first. The flow cannot wait for the response. Nothing on the synchronous path sees the result, so write the outcome to a record.
- Hand off to Queueable. The invocable method enqueues a
Queueableclass that implementsDatabase.AllowsCallouts. You can also use@future(callout=true), which suits only simple, short jobs. Both options return nothing to the flow, so the result must be stored on a record or published as a platform event.
public with sharing class PostalCodeJob implements Queueable, Database.AllowsCallouts {
private final List<Id> accountIds;
public PostalCodeJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext ctx) {
// Callouts are allowed here. Query the accounts, call the service,
// and update the records with the results.
}
}An invocable method that enqueues this job consumes one of the 50 enqueue calls allowed per transaction. Enqueue one job per invocation of the method, with all IDs in it, not one job per request.
Testing a callout method
Apex tests cannot make real callouts. A test that reaches Http.send() without a mock fails with Methods defined as TestMethod do not support Web service callouts. Implement HttpCalloutMock and register it with Test.setMock. The test below also checks that deduplication works, by counting how many callouts the mock received.
@IsTest
private class PostalCodeLookupTest {
private static Integer callCount = 0;
private class SuccessMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
callCount++;
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setHeader('Content-Type', 'application/json');
res.setBody('{"city":"Springfield"}');
return res;
}
}
private class ErrorMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(503);
res.setBody('Unavailable');
return res;
}
}
private static List<PostalCodeLookup.Request> buildRequests(List<String> codes) {
List<PostalCodeLookup.Request> requests = new List<PostalCodeLookup.Request>();
for (String code : codes) {
PostalCodeLookup.Request req = new PostalCodeLookup.Request();
req.postalCode = code;
requests.add(req);
}
return requests;
}
@IsTest
static void makesOneCalloutPerDistinctCodeAndKeepsOrder() {
Test.setMock(HttpCalloutMock.class, new SuccessMock());
Test.startTest();
List<PostalCodeLookup.Result> results =
PostalCodeLookup.lookup(buildRequests(new List<String>{ '12345', '12345', '', '67890' }));
Test.stopTest();
Assert.areEqual(4, results.size(), 'One result per request');
Assert.isTrue(results[0].isSuccess);
Assert.isTrue(results[1].isSuccess);
Assert.isFalse(results[2].isSuccess, 'Blank code fails at its own position');
Assert.isTrue(results[3].isSuccess);
Assert.areEqual(2, callCount, 'Duplicate codes share one callout');
}
@IsTest
static void reportsServiceErrorsPerRecord() {
Test.setMock(HttpCalloutMock.class, new ErrorMock());
Test.startTest();
List<PostalCodeLookup.Result> results =
PostalCodeLookup.lookup(buildRequests(new List<String>{ '12345' }));
Test.stopTest();
Assert.isFalse(results[0].isSuccess);
Assert.isTrue(results[0].errorMessage.contains('503'));
}
}Two further points apply when you test callouts:
- DML before the callout. If a test inserts data and then reaches a callout in the same transaction, it fails with the uncommitted work error, just as in production. Put the setup DML before
Test.startTest(). ThestartTest/stopTestpair gives the code under test a fresh transaction with fresh limits. - Flow tests do not call out. Flow tests and debug runs in Flow Builder can run the Apex action. Whether a callout succeeds there depends on the same placement rules as in production, so a debug run on the wrong path shows the error.
Common mistakes
- Making one callout per request. A 200-record save then fails after 100 callouts.
- Hard-coding endpoints and credentials. Use a named credential, and for external systems with no named credential, a Remote Site Setting.
- Placing the action on the regular path of an after-save flow, where the triggering DML is still pending.
- Assuming a response arrives in time. A slow service holds the user's transaction. In a screen flow the user waits on the spinner, up to the callout timeout.
- Catching every exception and returning success. The flow then continues as if the call worked.
Exercise
An after-save record-triggered flow on Opportunity updates a field and then calls your invocable method, which makes a callout. The flow fails with "You have uncommitted work pending." Give two ways to fix it, and say which one lets the flow use the response.
Show answer
First, move the Apex action to the Run Asynchronously path of the flow, so the callout runs in a separate transaction after the save commits. Second, have the invocable method enqueue a Queueable class that implements Database.AllowsCallouts. Neither lets the flow use the response in the original transaction. In both cases the callout runs after that transaction has finished, so the result must be written to a record or sent in a platform event. If the flow needs the response, the callout must run in a screen flow before any DML, or the DML must be moved after the callout.
Exercise
A record-triggered flow passes 150 interviews to your method in one call. Each has a postal code, and about 30 distinct codes appear among them. How many callouts should the method make, and what happens if it makes one per request?
Show answer
It should make about 30 callouts, one per distinct code, and then copy each result back to every request that used that code, in the original order. One per request makes 150 callouts, which exceeds the limit of 100 per transaction. The 101st callout throws an uncatchable LimitException and the whole transaction rolls back.