Skip to contentSkip to navigationSkip to topbar
On this page

Run Function Widget


Studio uses Widgets to represent various parts of Twilio's functionality that can then be stitched together in your Studio Flow to build out robust applications.

(information)

Info

New to Twilio Studio? Check out our Getting Started guide first!

The Run Function Widget allows you to execute Twilio Functions within your Studio Flow.

Run Function widget, re-named to 'keyword_function.' Function widget displays a URL where the function can be found.

Functions are a Twilio Serverless product. They are lightweight, serverless pieces of code that run in the Twilio cloud. By using the Run Function Widget, you can write code for additional business logic that works alongside your other Studio Widgets. See below for an example of a Studio Flow that uses a Function to generate a random number.


Required configuration for Run Function Widget

required-configuration-for-run-function-widget page anchor

The Run Function Widget only requires one piece of information to run properly: the URL of the Function you would like to call.

You may select an existing Function from the Function URL dropdown in the Widget's configuration panel, or create a new Function by clicking on the Create link above the Function URL dropdown menu.

Services are containers for your Functions, Assets, and Environments within Twilio Serverless. If you leave the Service dropdown blank or choose the Default Service option, you will see all the Functions that you have within your account's Default Service.

Run Function widget configuration panel.

If you have an existing Service that contains the Function you would like to run, select that Service from the dropdown menu, select the Environment the Function is in, and then select the Function. Note that if you select a Service that is not Default, you will not see the Create link above the Function URL dropdown menu. To create a new Function within a specific Service, you will need to go to the Services section of the Twilio Console(link takes you to an external page).

(warning)

Warning

Run Function can only invoke Public or Protected Functions. Learn more about Function Visibility.


Optional configuration for Run Function

optional-configuration-for-run-function page anchor

When configuring the Run Function Widget, you may choose to add any number of Function parameters. These are extra parameters that Studio will pass to your Function, expressed as key/value pairs. The Run Function Widget supports string literals as well as variables. The parameters you pass to the Function from Studio will be stored on the Function's event object.

Examples of valid parameters for the Run Function Studio widget. We've set the variable 'my_key' equal to 5, 'test' to the string literal 'hello' and 'name' to a liquid template that checks a prior widget for a user's name {{widgets.request_name.inbound.Body}}.

You can use Liquid Templating Language to add variables as parameters to your Function. Learn more about variables in Studio in the Getting Started guide.


Run Function Transitions

run-function-transitions page anchor

These events trigger transitions from this Widget to another Widget in your Flow. For more information on working with Studio transitions, see this guide.

NameDescriptionExample
SuccessA successful return of your Function.200 OK
FailThe Function does not return or has an error.500 Error

Transitions for both success and failure states should be handled so that your Studio Flow knows what to do if it gets a response back or if the request fails in some way. If the request succeeds, you will likely move on to the next Widget in your Flow. On a Fail state, you can choose to re-try the request or fail out of the flow.

(error)

Danger

Using the Run Function Widget to run custom TwiML in your Flow will cause Studio to give up control of the live voice call when the TwiML is returned. If your use case requires returning control of the call back to your Studio Flow after running your custom TwiML, use the TwiML Redirect Widget to invoke a custom TwiML URL instead of using Run Function.


Reattempting an outbound request

reattempting-an-outbound-request page anchor

You may want to reattempt a request to an external service or Twilio Function if a failure occurs.

Twilio Studio Request Reattempt Loop.

Looping a widget's failure transition back to itself is not an ideal way to implement a retry. This approach eliminates your ability to control the number of repeated requests a user can perform on your services. Additionally, a Flow's Execution will terminate after the same Widget is run 10 times — abruptly ending a user's Execution rather than providing functionality that handles the error.

To properly control retry attempts, you can create a counter within your Flow to keep track of how many requests have been attempted for a particular service and add Widgets to respond based on the result of each retry.

Twilio Studio Request Reattempt Counter.

To create a counter:

  1. Add a Set Variables Widget to create and increment a count variable.

  2. Using Liquid tags, first check if the count variable exists. If it does, set the count value to its current value plus one using the Liquid filter plus: 1. If the count variable does not exist, set the value to one. Copy and paste the below code into the Value field of your count variable.

1
{% if flow.variables.count %}
2
{{flow.variables.count | plus: 1}} {% else %} 1 {% endif %}

The count variable can be accessed anywhere in the Flow using {{flow.variables.count}}.

You can now check the count and continue incrementing or move the Flow forward using a Split Based On… Widget.

Twilio Studio Request Reattempt Split Based On... Widget.
  1. Add a Split Based On… Widget to analyze the {{flow.variables.count}} variable and determine if the number of requests has exceeded the limit you set.
  2. You will now add a condition to the Widget — checking if the variable is equal to the maximum number of requests you specify. In this example, the maximum number has been set to 3.
  3. If the variable being tested is not equal to 3, loop the No Condition Matches transition back to the Run Function Widget that failed. This will result in a retry.
  4. If the variable is equal to 3, use another Widget to handle the failure as you wish. For example, you can use a Send Message Widget to communicate the failure to the customer.

Run Function's HTTP Response requirements

run-functions-http-response-requirements page anchor

The HTTP response from the Function you call with the Run Function Widget must return a 2xx or 3xx status code within 10 seconds to succeed, and the response body must not exceed 64kB. Below are recommendations for configuring your HTTP response:

ResponseRecommendationNotes
Status Code200 or 2043xx redirection is supported. 4xx or 5xx status code will transition to failed in the Widget
Content Typeapplication/jsonContent-Type header is not required if Status Code is 204 No Content. Other content types are supported, such as plain text or XML. However, only application/json objects (e.g. {"foo":"bar"}) will be automatically parsed into Studio variables.
BodyValid JSONBody content must match the Content-Type header
Response Time10 seconds or lessSince Twilio Functions support up to a 10 second execution limit, Studio will timeout the request at 10 seconds and transition to failed in the widget.
Response SizeMaximum 64kbStudio can only process responses up to 64kb.

See the Function Execution documentation to learn more about how to edit the return value from the Function to return errors, success responses, and different content types.


How to access Variables from your Function

how-to-access-variables-from-your-function page anchor

You may wish to do some work on the data you pass to your endpoint and return more data or variables to work with further along in your Flow.

Returning JSON

returning-json page anchor

If your request returns an object in valid JSON(link takes you to an external page), you will be able to access it via widgets.MY_WIDGET_NAME.parsed

For example, consider a Function that returns the following JSON object:

{"message":"Hi", "person":{"name":"Alex", "age": 40}}

You would be able to access the values within the JSON object using the following variables:

Variable NameValue
widgets.MY_WIDGET_NAME.parsed.message"Hi"
widgets.MY_WIDGET_NAME.parsed.person.name"Alex"
widgets.MY_WIDGET_NAME.parsed.person.age40
(error)

Danger

If your request returns an array of objects, it will not be parsed by your Studio Flow. You should return a JSON object with key/value pairs if you want Studio to parse the return object. Wrap the array within an object to access the array objects.

Variables from all return types

variables-from-all-return-types page anchor

No matter what kind of response your URL returns to Studio, the following variables will be available to your Flow. For more information on working with variables in Studio, see this guide.

Body

body page anchor

{{widgets.MY_WIDGET_NAME.body}}

The full response body returned from the Function.

{{widgets.MY_WIDGET_NAME.content_type}}

The content type of the Function's response.

{{widgets.MY_WIDGET_NAME.status_code}}

The status code returned from the Function.


Example: Random Number Generator

example-random-number-generator page anchor

The following Studio Flow represents an example of working with the Run Function Widget. The Flow is a random number generator. It asks the user for a minimum value and a maximum value, and then passes those two inputs to a Serverless Function that generates a number between those two values. It then returns the random number back to the user.

Overview of a random number generator Studio Flow.

The Flow uses two Send & Wait for Reply Widgets to collect the minimum and maximum values for generating the random number. Then, the Run Function Widget runs a Function called Generate Random Number. It passes the two numbers that the user entered into the Function as parameters. The two variables are:

  • {{widgets.min_value.inbound.Body}}

  • {{widgets.max_value.inbound.Body}}

The Run Function Widget connects to a Generate Random Number Function and passes in the min and max values as parameters.

Below is the code for the Generate Random Number Twilio Function. The min and max Function Parameter values that Studio passes to the Function are stored in the Function's event object. The Function returns a JSON response containing the key number with the randomly generated number as the value.

1
exports.handler = function(context, event, callback) {
2
const min = Math.ceil(event.min);
3
const max = Math.floor(event.max);
4
const randomNum = Math.floor(Math.random() * (max - min + 1)) + min;
5
6
return callback(null, { number: randomNum });
7
};

Finally, the Send Message Widget sends back the randomly generated number. Keys from the JSON object that the Function sends back are parsed into variables. The Send Message Widget accesses the random number through the variable {{widgets.get_num.parsed.number}}.


You can see the return value, return type, and status code that your Function returns to your Studio Flow in the Studio Flow Logs. Access the Logs for a Studio Flow by clicking on Logs next to the Flow in the Console(link takes you to an external page). You will see a list of Executions. Click into an Execution to see the logs for that particular Execution of the Studio Flow.

Click on Flow Data to see the data returned from the Run Function Widget. The Flow Data is a JSON object containing data for every Widget that ran during the Execution. Scroll down until you see the name of your Run Function Widget. You should then see all the data returned to Twilio Studio from the Function.

The Studio Flow logs display the information returned from the Run Function Widget within a specific Execution.

Learn more about debugging Twilio Functions in the Functions documentation.


Want to learn how to use the Run Function Widget in real-world examples? You can follow along with these this step-by-step tutorials to see this Widget in action:

We can't wait to see what you build!

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.