Sub topic 8
Starting an Autolaunched Flow from Apex and REST
This chapter assumes you know how to build an autolaunched flow with input and output variables, and that you can read simple Apex and HTTP requests. You will start an active autolaunched flow from Apex and from the REST API, read its outputs, and handle the errors that most often appear.
Why call a flow from code
An autolaunched flow has no trigger of its own. Something else must start it. Inside Salesforce, another flow can do that with a Subflow element. Code is the other route. Apex can start a flow from a trigger, a batch job, or a controller. An external system can start one through the REST API.
Calling a flow from code is useful when the logic is owned by an admin in Flow Builder but the entry point must be code or an integration. The flow holds the business rules, and the caller only supplies inputs.
The flow used in this chapter is an autolaunched flow with the API name Close_Stale_Cases. It has these variables:
| Variable | Type | Available for input | Available for output |
|---|---|---|---|
| `accountId` | Text | Yes | No |
| `closedCount` | Number (scale 0) | No | Yes |
The flow finds open cases on the account that have not been touched for a set time, closes them, and stores the number closed in closedCount.
Choosing a calling method
There are several ways to start a flow from code. This chapter covers the two most common. The table compares them with the Subflow element.
| Method | Caller | Result | Typical use |
|---|---|---|---|
| `Flow.Interview` in Apex | Apex code | Read outputs with `getVariableValue` | Triggers, batch jobs, controllers |
| Invocable actions REST endpoint | External system or script | JSON response with outputs | Integrations, middleware |
| Subflow element | Another flow | Output variables assigned back | Reusing logic inside Flow Builder |
Starting a flow from Apex
Apex uses the Flow.Interview class. For each active flow, Apex exposes a class named Flow.Interview.<FlowApiName>. You build a map of input values, pass it to the constructor, and call start().
Map<String, Object> inputs = new Map<String, Object>();
inputs.put('accountId', '001000000000000AAA');
Flow.Interview.Close_Stale_Cases interview = new Flow.Interview.Close_Stale_Cases(inputs);
interview.start();
Integer closedCount = (Integer) interview.getVariableValue('closedCount');
System.debug('Cases closed: ' + closedCount);Walk through what each step does:
- The map keys are the flow variable API names. The values are ordinary Apex values.
- The constructor creates an interview, which is one running instance of the flow. It does not run anything yet.
start()runs the flow synchronously, in the same transaction as the Apex code.getVariableValuereturns anObject, so you cast it to the type you expect.
Things to know about the Apex approach
- Same transaction. The flow shares the caller's transaction. Its DML statements, SOQL queries, and CPU time count against the same governor limits as your Apex. If the flow fails, the exception reaches your code and can roll back your work.
- Active version only. Apex runs the active version of the flow. If no version is active, the class cannot compile in some contexts, and a call at run time fails. Activate the flow first.
- Compile-time dependency. Referencing
Flow.Interview.Close_Stale_Casesas a type ties your Apex to that flow. You cannot delete or rename the flow while code refers to it. - Dynamic names. If the flow name is only known at run time, use
Flow.Interview.createInterview(flowName, inputs). This returns aFlow.Interviewthat you start the same way. You lose compile-time checks, so test it carefully.
Here is the dynamic form:
String flowName = 'Close_Stale_Cases';
Map<String, Object> inputs = new Map<String, Object>{
'accountId' => '001000000000000AAA'
};
Flow.Interview dynamicInterview = Flow.Interview.createInterview(flowName, inputs);
dynamicInterview.start();
Object result = dynamicInterview.getVariableValue('closedCount');
System.debug('Cases closed: ' + result);Bulk behavior from Apex
Each start() call is one interview. If you call it inside a loop over 200 records, you create 200 interviews, and every one runs its own queries and DML. This hits governor limits quickly. Two safer designs exist:
- Pass a collection into the flow. Make the input variable a record collection or a text collection, and let the flow process the whole set with one Get Records and one Update Records.
- Move the loop into a Subflow-free design where the flow is called once per transaction.
The first option is almost always better. Design the flow to accept a collection, as you learned in the chapter on bulk-safe design.
Starting a flow from the REST API
The REST API can run an autolaunched flow through the invocable actions endpoint. The path ends with the flow's API name.
POST /services/data/v60.0/actions/custom/flow/Close_Stale_Cases
Authorization: Bearer <access_token>
Content-Type: application/json
{
"inputs": [
{ "accountId": "001000000000000AAA" }
]
}The request body has one key, inputs, which is an array. Each element in the array is one set of input values, and each set runs the flow once. This is how the REST API supports bulk calls. Sending three elements runs three interviews in one request.
The response is also an array, with one result per input set, in the same order. A successful result looks like this:
[
{
"actionName": "Close_Stale_Cases",
"errors": null,
"isSuccess": true,
"outputValues": {
"closedCount": 4,
"Flow__InterviewStatus": "Finished"
}
}
]Check isSuccess on every element. The HTTP status of the whole request can be 200 even when one input set failed. When isSuccess is false, the errors array holds the error code and message for that input set.
Authentication and permissions
The caller needs an access token for a user, usually from an OAuth flow or a connected app. That user needs:
- API access enabled on their profile or permission set.
- Permission to run flows. This is the "Run Flows" system permission, or the "Flow User" setting on the user record, depending on the org's configuration.
- Access to the objects and fields the flow reads and writes, because the flow runs in the context of the calling user unless the flow is set to run in system mode.
You can list the actions and their input and output definitions with a GET request to /services/data/v60.0/actions/custom/flow. This is a quick way to confirm the flow is exposed and to check the exact variable names.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Invalid type: Flow.Interview.Close_Stale_Cases` | The flow name is wrong, or the flow is not an autolaunched flow. | Check the API name and the flow type. |
| Variable is `null` after `start()` | The variable is not marked "Available for output", or the flow did not reach the step that sets it. | Enable output, and test the paths in Flow Builder. |
| Input appears to be ignored | The variable is not marked "Available for input", or the name is misspelled. | Check the exact API name and its settings. |
| REST returns `NOT_FOUND` | The flow has no active version, or the name in the path is wrong. | Activate a version and check the path. |
| `isSuccess` is `false` with a flow error | A fault in the flow, such as a validation rule failing on update. | Add fault paths and read the error message. |
| `Too many SOQL queries: 101` | Apex calls the flow once per record. | Pass a collection and process records in one interview. |
Choosing between Apex and REST
Use Apex when the caller already runs inside Salesforce and needs the result in the same transaction. Use REST when the caller is outside Salesforce, or when you want each flow run to be independent of other work. Keep in mind that each REST call is its own transaction, so a failure in one request does not roll back others.
Exercise
Your Apex trigger loops over 150 cases and calls new Flow.Interview.Close_Stale_Cases(inputs).start() for each one. The trigger fails with a governor limit error. Describe how you would redesign the flow and the call.
Show answer
Change the flow so that its input is a collection variable, for example a collection of case IDs or account IDs, marked "Available for input". Inside the flow, use one Get Records element and one Update Records element on the whole collection, not inside a loop. In Apex, build the collection once, put it in the input map, and call start() a single time. This uses one interview, so the queries and DML count once instead of 150 times.
Exercise
A REST call to the invocable actions endpoint returns HTTP 200, but the flow did not close any cases. Where do you look, and why?
Show answer
Look at the isSuccess and errors fields in each element of the response array. The request as a whole can return 200 while an individual input set fails. Also confirm that the flow has an active version, and that the calling user has access to the Case object.