Sub topic 5
Designing request and response classes
This chapter assumes you can write Apex classes, inner classes, and collections. It also assumes you know what a Flow variable and an Apex action element are. You should already have seen the @InvocableMethod and @InvocableVariable annotations. Here the focus is on how to shape the data that crosses the boundary between a flow and your Apex code.
Why wrapper classes exist
An invocable method accepts exactly one parameter, and that parameter must be a list. A list of Id or String works when the method needs one value. Most real actions need several values, for example an account Id, a subject, and a due date. Because the signature allows only one parameter, you bundle the values into a wrapper class. The method then takes List<Request>.
The same idea applies to output. A method can return List<Result> so that each input gets its own structured answer, such as a success flag, a created record Id, and an error message.
| Need | Simple signature | Wrapper signature |
|---|---|---|
| One input value | `List<Id>` | Not needed |
| Several input values | Not possible | `List<Request>` |
| One output value per input | `List<String>` | Not needed |
| Several output values per input | Not possible | `List<Result>` |
| No output | `void` | Not needed |
Rules for wrapper classes
Flow can only see a wrapper class that meets these conditions:
- The class must be
publicorglobal. If it is an inner class, the outer class must also be visible to the flow. - The class must have a public no-argument constructor. The default constructor satisfies this, so do not declare a constructor with parameters unless you also declare a no-argument one.
- Each field you want to expose needs the
@InvocableVariableannotation and must bepublicorglobal. Fields without the annotation are invisible to Flow. - Only one class can contain an invocable method per Apex class. You cannot put two
@InvocableMethodmethods in the same class. - The class cannot be generic and cannot use inheritance in a way that hides annotated fields. Declare the annotated fields directly on the wrapper class.
Supported field types include primitives such as String, Integer, Decimal, Boolean, Date, and DateTime, as well as Id, SObjects, generic SObject, and lists of these. A field can also be another Apex-defined class that is itself a valid wrapper with annotated fields. Check the Apex Developer Guide for the current list, because Salesforce extends supported types over time.
The shape of a good request class
Look at the request class from the task creator example.
public class Request {
@InvocableVariable(label='Account Id' description='Account that the task relates to' required=true)
public Id accountId;
@InvocableVariable(label='Task Subject' description='Defaults to Follow up if blank')
public String subject;
}Each annotation carries metadata that Flow Builder shows to the admin who configures the action:
labelis the name shown in the input and output panels. Without it, Flow uses the field name.descriptionis help text. Use it to state defaults, formats, and limits.requiredapplies to inputs. When it istrue, Flow Builder will not let the admin save the action without a value for that field. The default isfalse.
Required is enforced when the flow is saved. It is not enforced at run time. If a flow passes a value that resolves to null, for example a variable that was never assigned, your method still receives a null. You must therefore check for null in Apex even for required fields.
The shape of a good response class
The response class holds one answer per input.
public class Result {
@InvocableVariable(label='Task Id')
public Id taskId;
@InvocableVariable(label='Is Success')
public Boolean isSuccess;
@InvocableVariable(label='Error Message')
public String errorMessage;
}Three habits make response classes easy to use in a flow:
- Include a success flag. A flow Decision element can branch on a Boolean much more easily than on a null check.
- Include an error message field. This lets the flow show the problem on a screen or write it to a log record.
- Include the identifying value, such as the record Id that was created. The flow can then use it in later elements.
The order of results matters. Flow matches each element of the returned list to the interview that supplied the request at the same position. Return exactly as many results as you received requests, in the same order. The next chapter covers the bulk mechanics in detail.
Naming and labeling
Field names are code, and labels are for admins. A good field name like accountId is short and follows Apex style. A good label such as Account Id is written for a person who may never read your class.
Use these conventions:
- Keep labels unique within the class. Two fields with the same label are confusing in Flow Builder.
- Write a description for every field whose purpose is not obvious from the label alone.
- Name the wrapper classes
RequestandResultas inner classes of the invocable class. The qualified name, such asAccountTaskCreator.Request, then tells you which action the wrapper belongs to. - Avoid renaming public fields after the class has been used in flows. Flows reference the fields by name, and a rename can break saved flows.
Inner classes or top-level classes
The example uses inner classes, which keep the wrapper next to the method that uses it. This works well for a single action. A top-level class makes sense when several invocable methods need the same wrapper. Flow shows the same structure in both cases.
| Approach | Strength | Weakness |
|---|---|---|
| Inner classes | Everything for one action lives in one file | Cannot be shared cleanly between actions |
| Top-level classes | Reusable across several actions | More files to maintain and deploy together |
Using SObjects and lists as fields
A field can be an SObject type, for example public Account account;. The flow then passes a whole record variable, and your code can read any field already loaded on it. This is convenient, but two cautions apply:
- Only the fields populated in the flow's record variable are available. Reading an unpopulated field throws a
System.SObjectException. - A generic
SObjectfield accepts any record type, so checkgetSObjectType()before casting.
A field can also be a list, such as public List<Id> contactIds;. Each flow interview can then pass a collection variable. Notice the shape: the method receives a list of requests, and each request holds its own list. That is a list of lists, and your code must loop over both levels.
public with sharing class ContactEmailCollector {
public class Request {
@InvocableVariable(label='Contact Ids' required=true)
public List<Id> contactIds;
}
public class Result {
@InvocableVariable(label='Email Addresses')
public List<String> emails;
}
@InvocableMethod(label='Collect Contact Emails' description='Returns the email addresses for each request.')
public static List<Result> collect(List<Request> requests) {
Set<Id> allIds = new Set<Id>();
for (Request req : requests) {
if (req.contactIds != null) {
allIds.addAll(req.contactIds);
}
}
Map<Id, Contact> contactsById = new Map<Id, Contact>(
[SELECT Id, Email FROM Contact WHERE Id IN :allIds]
);
List<Result> results = new List<Result>();
for (Request req : requests) {
Result res = new Result();
res.emails = new List<String>();
if (req.contactIds != null) {
for (Id contactId : req.contactIds) {
Contact c = contactsById.get(contactId);
if (c != null && c.Email != null) {
res.emails.add(c.Email);
}
}
}
results.add(res);
}
return results;
}
}The method gathers every Id from every request into one set, runs a single query, and then rebuilds one result per request. This pattern keeps the query count constant no matter how many interviews are batched together.
How the pieces connect
The diagram shows how data moves from the flow into your request objects and back.
Common mistakes
- Forgetting
@InvocableVariableon a field. The field does not appear in Flow Builder and the value is never set. - Using a private or protected field. Only
publicandglobalfields can be exposed. - Adding a constructor with parameters and no no-argument constructor. Flow cannot create the object.
- Returning a list of a different size than the input. The flow cannot match results to interviews, and the action fails.
- Treating
required=trueas a null check. Validate in Apex. - Putting logic in the wrapper class. Keep wrappers as plain data holders and put behavior in the method or in a separate service class.
Testing the wrapper shape
Because the wrapper classes are ordinary Apex classes, a test can build them directly, as the bulk test does. A short test can also check null handling for the collector above.
@IsTest
private class ContactEmailCollectorTest {
@IsTest
static void returnsOneResultPerRequestIncludingNulls() {
Account acc = new Account(Name = 'Test Account');
insert acc;
Contact c = new Contact(LastName = 'Smith', Email = '[email protected]', AccountId = acc.Id);
insert c;
ContactEmailCollector.Request withContact = new ContactEmailCollector.Request();
withContact.contactIds = new List<Id>{ c.Id };
ContactEmailCollector.Request withNothing = new ContactEmailCollector.Request();
List<ContactEmailCollector.Result> results =
ContactEmailCollector.collect(new List<ContactEmailCollector.Request>{ withContact, withNothing });
Assert.areEqual(2, results.size(), 'One result per request');
Assert.areEqual(1, results[0].emails.size());
Assert.areEqual('[email protected]', results[0].emails[0]);
Assert.areEqual(0, results[1].emails.size());
}
}Exercises
Exercise
A teammate declares a request class with a constructor public Request(Id accountId) { this.accountId = accountId; } and no other constructor. The class compiles, but the action fails in Flow. What is the likely cause and the fix?
Show answer
Flow creates request objects itself and needs a public no-argument constructor. Declaring a constructor with parameters removes the default one. The fix is to add public Request() {} (or remove the custom constructor) and set the fields through the annotated variables.
Exercise
An invocable method receives 5 requests and returns a list of 4 results because one request was skipped. Why is this a problem, and how should the skipped request be represented?
Show answer
Flow matches results to interviews by position, so the list must have the same size and order as the input. For the skipped request, add a Result at the same position with isSuccess = false and an explanatory errorMessage, or an empty or null output value if that suits the flow.
Exercise
A field is marked required=true, yet the method sometimes receives null for it. How is this possible, and what should the code do?
Show answer
Required is only checked when the flow is saved in Flow Builder. At run time a variable can still resolve to null. The code should check for null or blank values and report a failure in the result for that request instead of assuming the value exists.