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.
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.
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.
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.
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.
Run Function can only invoke Public or Protected Functions. Learn more about Function Visibility.
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.
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.
These events trigger transitions from this Widget to another Widget in your Flow. For more information on working with Studio transitions, see this guide.
Name | Description | Example |
---|---|---|
Success | A successful return of your Function. | 200 OK |
Fail | The 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.
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.
You may want to reattempt a request to an external service or Twilio Function if a failure occurs.
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.
To create a counter:
Add a Set Variables Widget to create and increment a count
variable.
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.
{{flow.variables.count}}
variable and determine if the number of requests has exceeded the limit you set.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:
Response | Recommendation | Notes |
---|---|---|
Status Code | 200 or 204 | 3xx redirection is supported. 4xx or 5xx status code will transition to failed in the Widget |
Content Type | application/json | Content-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. |
Body | Valid JSON | Body content must match the Content-Type header |
Response Time | 10 seconds or less | Since 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 Size | Maximum 64kb | Studio 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.
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.
If your request returns an object in valid JSON, 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 Name | Value |
---|---|
widgets.MY_WIDGET_NAME.parsed.message | "Hi" |
widgets.MY_WIDGET_NAME.parsed.person.name | "Alex" |
widgets.MY_WIDGET_NAME.parsed.person.age | 40 |
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.
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.
{{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.
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.
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}}
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.
1exports.handler = function(context, event, callback) {2const min = Math.ceil(event.min);3const max = Math.floor(event.max);4const randomNum = Math.floor(Math.random() * (max - min + 1)) + min;56return 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. 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.
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!