メニュー

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.

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 Runtime 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

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.

Twilio Runtime also has Services, which are containers for your Functions, Assets, and Environments within Twilio Runtime. 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, choose 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.

Optional configuration for Run Function

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

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

名前 概要
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 can choose to re-try the request or fail out of the flow.

Reattempting an outbound request

You may want to reattempt a request to an external service or Twilio Runtime 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.

{% if flow.variables.count %}
{{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

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:

レスポンス Recommendation 注釈
Status Code 200 または 204 3xx redirection is supported. 4xx or 5xx status code will transition to failed in the Widget
ContentType 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.

How to access Variables from your Function

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

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

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.

Variables from all return types

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

{{widgets.MY_WIDGET_NAME.body}}

The full response body returned from the Function.

ContentType

{{widgets.MY_WIDGET_NAME.content_type}}

The content type of the Function's response.

Status Code

{{widgets.MY_WIDGET_NAME.status_code}}

The status code returned from the Function.

Example: Random Number Generator

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.

The body of the Generate Random Number Function, which takes the min and max values that Studio passed in

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}}.

Debugging Functions

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.

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 all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Stack Overflow Collective or browsing the Twilio tag on Stack Overflow.

フィードバックくださりありがとうございます!

Please select the reason(s) for your feedback. The additional information you provide helps us improve our documentation:

Sending your feedback...
🎉 Thank you for your feedback!
Something went wrong. Please try again.

Thanks for your feedback!

Refer us and get $10 in 3 simple steps!

ステップ1

Get link

Get a free personal referral link here

ステップ2:

Give $10

Your user signs up and upgrade using link

ステップ3

Get $10

1,250 free SMSes
OR 1,000 free voice mins
OR 12,000 chats
OR more