Menu

Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

Function Execution

The process of invoking your Twilio Function code is quite simple. By design, the Twilio Function lightweight environment provides developers with all the flexibility they need. Read on to learn about how Twilio Functions runs your code.

Functions Invocation Flow

During invocation the following steps occur:

  1. Environment Bootstrap - The Twilio Function environment is bootstrapped, and any resources your Function code may rely on are quickly initialized.
  2. Handler Execution - The Twilio Environment will then execute the exports.handler() method and provide the context, event and callback parameters.
  3. Response Emitted - When your Twilio Function code has completed, you call the callback() method to emit your response. After executing the callback() method, your Twilio Function execution will be terminated. This includes any asynchronous processes that may still executing.

Handler Method

The handler method is the interface between Twilio Functions and your application logic. You can think of the handler method as the entry point to your application. This is somewhat analogous to a main() function in Java or __init__ in Python.

Twilio Functions will execute your handler method when it is ready to hand off control of execution to your application logic. If your Function Code does not contain a handler method, Twilio Functions will be unable to execute your logic and will emit an HTTP 500.

Handler Arguments

Argument Type Description
context Object Provides information about the current execution environment
event Object Contains the request parameters passed into your Twilio Function
callback Function Function used to complete execution and emit responses
Loading Code Sample...
      
      
      
      
      Twilio Function Handler Method Boilerplate

      Handler Method Boilerplate

      Twilio Function Handler Method Boilerplate

      Context Object

      Twilio Functions provides the context object as an interface between the current execution environment and the handler method. The context object provides access to environment variables and helper methods that can be accessed at execution time.

      Helper Methods

      The context object provides helper methods that preinitialize common utilities and clients that you might find useful when building your application. These helper methods extract all their required configuration from environment variables.

      Method Type Description
      getTwilioClient() Twilio REST Helper If you have enabled the inclusion of your account credentials in your Function, this will return an initialized Twilio REST Helper Library. If you have not included account credentials in your Function, calling this method will result in an error. If your code doesn’t catch this error, it will result in an HTTP 500 response.
      Loading Code Sample...
          
          
          
          
          Example of using built-in Twilio REST Helper

          Use built-in Twilio REST Helper to send an SMS Message

          Example of using built-in Twilio REST Helper

          Default Environment Variables

          The context object provides several environment variables by default. These default environment variables are typically required for initializing one of the helper methods.

          Property Type Description
          ACCOUNT_SID String or null If you have chosen to include your account credentials in your Function, this will return the SID identifying the Account that owns this Function. If you have not chosen to include account credentials in your Function, this value will be null.
          AUTH_TOKEN String or null If you have chosen to include your account credentials in your Function, this will return the Auth Token associated with the owning Account. If you have not chosen to include account credentials in your Function, this value will be null.
          DOMAIN_NAME String The Runtime Domain that is currently serving your Twilio Function.
          Loading Code Sample...
              
              
              
              
              Example of how to access the Default Environment Variables

              Retrieve Runtime Domain from Default Environment Variables

              Example of how to access the Default Environment Variables

              Environmental Variables

              Developers are encouraged to use Environmental Variables to separate their code from configuration. Using Twilio Functions, developers can add, remove and update Environmental Variables through the Twilio Console. Using Environmental Variables ensures that your code is portable and that simple configuration changes can be made instantly.

              Environment Variables

              Loading Code Sample...
                  
                  
                  
                  
                  Example of how to access Environment Variables

                  Retrieve Environment Variables

                  Example of how to access Environment Variables

                  Event Object

                  The event object contains the request parameters passing into your Function. Both POST and GET parameters will be collapsed into the same object. For POST requests, you can pass either form encoded parameters or JSON documents; both will be collapsed into the event object.

                  Callback Function

                  When you have finished processing your request, you need to invoke the callback function to emit a response and complete execution. The callback method will automatically determine the data type of your response and serialize the output appropriately.

                  You must invoke the callback method when your Function is done processing. Failure to invoke the callback will cause your Function to continue running up to the 5 second execution time limit. When your Function reaches the execution time limit, it will be terminated, and a 504 Gateway timeout will be returned to the client.

                  Callback and Asynchronous Limitations

                  It is important to note that when the callback function is invoked, it will terminate all execution of your Function. This includes any asynchronous processes you may have kicked off during during the execution of your handler.

                  For this reason, if you are using libraries that are natively asynchronous, you need to nest your call to the callback function inside the promise handler.

                  Loading Code Sample...
                      
                      
                      
                      
                      Example of how to appropriately use callback() with an asynchronous HTTP request

                      Complete Execution with Asynchronous HTTP Request

                      Example of how to appropriately use callback() with an asynchronous HTTP request
                      Argument Type Description
                      error String or null Error indicating what problem was encountered during execution. This will result in the client receiving a HTTP 500 response with the provided payload.
                      response String, Object or null Successful response generated by the Function. Providing this argument will result in the client receiving a HTTP 200 response containing the provided value.
                      Loading Code Sample...
                          
                          
                          
                          
                          Example of how to return an empty HTTP 200 OK

                          Return a Simple Successful Response

                          Example of how to return an empty HTTP 200 OK
                          Loading Code Sample...
                              
                              
                              
                              
                              Example of how to return an error message with HTTP 500 Error

                              Return an Error Response

                              Example of how to return an error message with HTTP 500 Error
                              Loading Code Sample...
                                  
                                  
                                  
                                  
                                  Example of how to return plaintext with HTTP 200 OK

                                  Return a Successful Plaintext Response

                                  Example of how to return plaintext with HTTP 200 OK
                                  Loading Code Sample...
                                      
                                      
                                      
                                      
                                      Example of how to return TwiML with HTTP 200 OK

                                      Return a Successful TwiML Response

                                      Example of how to return TwiML with HTTP 200 OK
                                      Loading Code Sample...
                                          
                                          
                                          
                                          
                                          Example of how to return JSON in HTTP 200 OK

                                          Return a Successful JSON Response

                                          Example of how to return JSON in HTTP 200 OK

                                          Constructing a Response

                                          In some instances, your Function may need greater control over the response it is going to emit. For those instances, you can use the Twilio Response object included in your Function by default.

                                          By using the Twilio Response object, you will be able to specify the status code, headers, and body of your response. You can begin constructing a custom response by creating a new Twilio Response object, like so:

                                          let response = new Twilio.Response();
                                          

                                          Twilio Response Methods

                                          Method Return Type Description
                                          setStatusCode(int) self Sets the status code in the HTTP response
                                          setBody(mixed) self Sets the body of the HTTP response. Takes either an object or string. When setting the body to anything other than text, make sure to set the corresponding Content-Type header with appendHeader().
                                          appendHeader(string, string) self Adds a header to the HTTP response. The first argument specifies the header name and the second argument the header value.
                                          setHeaders(object) self Sets all of the headers for the HTTP response. Takes an object mapping the names of the headers to the respective values.
                                          Loading Code Sample...
                                              
                                              
                                              
                                              
                                              Example of setting a Status Code using Twilio Response

                                              Set a Status Code in a Response

                                              Example of setting a Status Code using Twilio Response
                                              Loading Code Sample...
                                                  
                                                  
                                                  
                                                  
                                                  Example of building a plaintext response with Twilio Response

                                                  Build a Plaintext Response

                                                  Example of building a plaintext response with Twilio Response
                                                  Loading Code Sample...
                                                      
                                                      
                                                      
                                                      
                                                      Example of building a JSON response with Twilio Response

                                                      Building a JSON Response

                                                      Example of building a JSON response with Twilio Response
                                                      Loading Code Sample...
                                                          
                                                          
                                                          
                                                          
                                                          Example of setting an header using Twilio Response

                                                          Set an HTTP Header in a Response

                                                          Example of setting an header using Twilio Response
                                                          Loading Code Sample...
                                                              
                                                              
                                                              
                                                              
                                                              Example of setting multiple headers using Twilio Response

                                                              Set Multiple HTTP Headers in a Response

                                                              Example of setting multiple headers using Twilio Response

                                                              Need some help?

                                                              We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

                                                              Loading Code Sample...