Sub topic 8
Callouts and governor limits in actions
This chapter assumes you can already write an @InvocableMethod with request and response wrapper classes, and that you know the bulk pattern from the earlier chapters: one pass over the list of requests, with no SOQL or DML inside the loop. Here you add the part that leaves Salesforce: a call to an external system. You also see which governor limits an action has to stay under.
Why callouts need extra care in an action
A callout is an HTTP request your Apex makes to another system. Agents use callouts for live data that Salesforce does not store, such as shipment status, inventory, or a pricing engine.
Callouts differ from SOQL in three ways:
- They are slow. A query takes milliseconds. A callout can take seconds, and the agent conversation waits for it.
- They fail in ways you do not control, such as timeouts, 500 responses, and malformed JSON.
- They cannot be mixed freely with DML. If your transaction has uncommitted database changes, a callout throws
System.CalloutException: You have uncommitted work pending.
Because the agent reads whatever your action returns, a callout failure must come back as a readable message. It must not escape as an unhandled exception.
Governor limits that matter for actions
An invocable method runs in synchronous Apex. These limits apply to each transaction:
| Limit | Value |
|---|---|
| SOQL queries | 100 |
| Rows returned by SOQL | 50,000 |
| DML statements | 150 |
| Rows processed by DML | 10,000 |
| CPU time | 10,000 ms |
| Heap size | 6 MB |
| Callouts | 100 |
| Total callout time | 120 seconds |
| Timeout of one callout | 10 seconds by default, up to 120 |
The callout limits are the ones people forget. The list of requests passed to your method can hold many items when the action is called from a flow or other automation. If each request triggers one callout, 101 requests exceed the callout limit. Calling a slow service many times can also exhaust the 120-second total.
You can read your remaining budget at run time with the Limits class:
Integer used = Limits.getCallouts();
Integer max = Limits.getLimitCallouts();
Integer remaining = max - used;Limits.getCallouts() returns how many callouts the current transaction has made. Limits.getLimitCallouts() returns the maximum.
Authenticating with a named credential
Do not put URLs and secrets in Apex. Use a named credential, a setup record that stores the endpoint and authentication. In Apex you reference it with the callout: prefix, and the platform adds the authentication to the request. Credentials stay out of source control, and each org (sandbox, production) can point to a different endpoint without a code change.
The example below assumes a named credential called Shipping_API whose URL is the base of a service that supports GET /shipments/{trackingNumber} and returns JSON like {"status":"In transit"}.
Also note the permission model. The running user needs access to the external credential, either through a permission set that grants the external credential principal or through a profile setting. A missing grant is a common reason an action works for an admin and fails for everyone else.
A callout action
This action looks up one shipment per request. It follows the rules from earlier chapters and adds a limit check, a timeout, and error handling that returns messages.
public with sharing class GetShipmentStatusAction {
public class Request {
@InvocableVariable(
label='Tracking Number'
description='The carrier tracking number of the shipment, for example 1Z999AA10123456784'
required=true
)
public String trackingNumber;
}
public class Response {
@InvocableVariable(
label='Shipment Status'
description='Current status such as In transit or Delivered. Empty if the lookup failed'
)
public String status;
@InvocableVariable(
label='Message'
description='A plain-language explanation to tell the user, including why a lookup failed'
)
public String message;
}
@InvocableMethod(
label='Get Shipment Status'
description='Looks up the live status of a shipment by tracking number using the shipping service'
category='Service'
callout=true
)
public static List<Response> getShipmentStatus(List<Request> requests) {
List<Response> responses = new List<Response>();
for (Request r : requests) {
responses.add(lookup(r));
}
return responses;
}
private static Response lookup(Request r) {
Response res = new Response();
if (r == null || String.isBlank(r.trackingNumber)) {
res.message = 'No tracking number was provided. Ask the user for one.';
return res;
}
if (Limits.getCallouts() >= Limits.getLimitCallouts()) {
res.message = 'The lookup could not be run because too many requests were made at once. Try again.';
return res;
}
HttpRequest req = new HttpRequest();
req.setEndpoint(
'callout:Shipping_API/shipments/' +
EncodingUtil.urlEncode(r.trackingNumber.trim(), 'UTF-8')
);
req.setMethod('GET');
req.setTimeout(8000);
try {
HttpResponse resp = new Http().send(req);
Integer code = resp.getStatusCode();
if (code == 200) {
Map<String, Object> body =
(Map<String, Object>) JSON.deserializeUntyped(resp.getBody());
Object status = body.get('status');
if (status == null) {
res.message = 'The shipping service replied without a status.';
} else {
res.status = String.valueOf(status);
res.message = 'Shipment ' + r.trackingNumber.trim() + ' is ' + res.status + '.';
}
} else if (code == 404) {
res.message = 'No shipment was found for tracking number ' + r.trackingNumber.trim() + '.';
} else {
res.message = 'The shipping service is unavailable right now (HTTP ' + code + ').';
}
} catch (CalloutException e) {
res.message = 'The shipping service did not respond in time.';
} catch (JSONException e) {
res.message = 'The shipping service sent a reply that could not be read.';
}
return res;
}
}Points to notice:
callout=trueon@InvocableMethoddeclares that the method makes a callout. Set it whenever the method does, because other tools that run invocable methods use it to decide how to execute the method.setTimeout(8000)is shorter than the 10-second default. Pick a value that fits the agent conversation, not the maximum the platform allows.- The tracking number is URL-encoded. It comes from a language model and ultimately from a user, so treat it as untrusted input before putting it in a path.
- Every failure path fills
messagewith a sentence the agent can relay. The description ofmessagetells the agent to use it for failures. CalloutExceptioncovers timeouts and connection failures.JSONExceptioncovers a bad body. Anything else, such as a coding bug, is allowed to surface so that it shows up in logs.
The flow of one request
Ordering callouts and DML
If an action must both call out and write data, do the callout first and the DML after. Reversing the order throws the uncommitted work error.
// Correct order inside one action
HttpResponse resp = new Http().send(req); // 1. callout
insert new Task(Subject = 'Checked shipment', WhoId = contactId); // 2. DMLIf you need DML before the callout, you have two choices. Move the callout into a separate action, so the agent calls the two actions in sequence. Or hand the callout to asynchronous Apex such as a Queueable class that implements Database.AllowsCallouts. The second option means the agent cannot report the callout result in the same turn. Splitting into two actions is usually clearer, and it matches the guideline of keeping each action focused.
Bulk callouts: what to do with a list
The example makes one callout per request. This is acceptable when the external API has no bulk endpoint and the agent sends one request at a time, which is the normal case for a conversation. It is risky when a flow can pass in hundreds of items.
You have three options, in order of preference:
- Use a bulk endpoint on the external service. Send all tracking numbers in one request and match the results back to the requests by position or key. This uses one callout whatever the list size.
- Check
Limitsbefore each call, as the example does, and return a "try again" message for requests that cannot be served. - Document the cap in the action description so callers know the intended volume.
Whichever option you choose, keep the rule that the output list has one response per request, in the same order. A skipped request that produces no response breaks that contract.
Also watch the heap. A callout response is held in memory, and a large JSON body parsed with deserializeUntyped can use several times its size. If the service can return big payloads, ask it for only the fields you need.
Testing callouts
Apex tests cannot make real HTTP requests. Without a mock, the test fails with "Methods defined as TestMethod do not support Web service callouts". You supply a fake with Test.setMock and a class that implements HttpCalloutMock.
@IsTest
private class GetShipmentStatusActionTest {
private class FakeService implements HttpCalloutMock {
private Integer code;
private String body;
FakeService(Integer code, String body) {
this.code = code;
this.body = body;
}
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(code);
res.setBody(body);
return res;
}
}
private class TimingOutService implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
throw new CalloutException('Read timed out');
}
}
private static GetShipmentStatusAction.Response run(String trackingNumber) {
GetShipmentStatusAction.Request req = new GetShipmentStatusAction.Request();
req.trackingNumber = trackingNumber;
return GetShipmentStatusAction.getShipmentStatus(
new List<GetShipmentStatusAction.Request>{ req }
)[0];
}
@IsTest
static void returnsStatusOnSuccess() {
Test.setMock(HttpCalloutMock.class, new FakeService(200, '{"status":"In transit"}'));
Test.startTest();
GetShipmentStatusAction.Response res = run('ABC123');
Test.stopTest();
Assert.areEqual('In transit', res.status);
}
@IsTest
static void explainsNotFound() {
Test.setMock(HttpCalloutMock.class, new FakeService(404, '{}'));
GetShipmentStatusAction.Response res = run('ABC123');
Assert.isNull(res.status);
Assert.isTrue(res.message.contains('No shipment was found'));
}
@IsTest
static void explainsTimeout() {
Test.setMock(HttpCalloutMock.class, new TimingOutService());
GetShipmentStatusAction.Response res = run('ABC123');
Assert.isNull(res.status);
Assert.areEqual('The shipping service did not respond in time.', res.message);
}
@IsTest
static void asksForTrackingNumberWhenBlank() {
GetShipmentStatusAction.Response res = run(' ');
Assert.isTrue(res.message.contains('No tracking number'));
}
}The blank-input test needs no mock because the method returns before it reaches the callout. Test each failure path, not just the success path, because those are the paths where the agent will otherwise have nothing to say.
Common errors
- Uncommitted work pending. DML ran before the callout. Reorder, split the action, or go asynchronous.
- Callouts not supported in test. The test lacks
Test.setMock. - Unauthorized endpoint. The URL is not covered by a named credential or remote site setting. Use
callout:with a named credential. - Works for admins only. The running user lacks permission for the external credential.
- Too many callouts: 101. The method makes a callout per request without checking the limit or using a bulk endpoint.
- Agent invents an answer after a failure. The action threw an exception or returned an empty response. Return a clear message instead.
Exercise
A flow passes 150 requests, each with a tracking number, to the shipment action above. The shipping service has no bulk endpoint. What happens to requests 101 to 150, and why is returning a message for them better than letting the transaction fail?
Show answer
The transaction reaches the limit of 100 callouts. Because the method checks Limits.getCallouts() against Limits.getLimitCallouts() before each call, requests 101 to 150 return a response with a message such as "too many requests were made at once. Try again." and no status. If the method did not check, the 101st callout would throw an uncatchable System.LimitException and the whole transaction would fail, including the first 100 results. Returning a message keeps one response per request in order and lets the caller retry only the unserved items.
Exercise
Your action must create a Case record and then notify an external system about it. Which order do you use inside one method, and what do you do if the notification must happen before the Case is created?
Show answer
Do the callout first and the DML second, because DML before a callout throws "You have uncommitted work pending." If the notification must come first and cannot be reordered, split the work into two actions that the agent calls in sequence, or run the callout in a Queueable that implements Database.AllowsCallouts.