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.
During invocation the following steps occur:
- Environment Bootstrap - The Twilio Function environment is bootstrapped, and any resources your Function code may rely on are quickly initialized.
- Handler Execution - The Twilio Environment will then execute the
exports.handler()
method and provide the context, event and callback parameters. - Response Emitted - When your Twilio Function code has completed, you call the
callback()
method to emit your response. After executing thecallback()
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 |
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. |
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. |
PATH | String | The path of Twilio Function that is currently being executed. |
Environment Variables
Developers are encouraged to use Environment Variables to separate their code from configuration. Using Twilio Functions, developers can add, remove and update Environment Variables through the Twilio Console. Using Environment Variables ensures that your code is portable and that simple configuration changes can be made instantly. Environment Variables are encrypted and can not be displayed, so they are the preferred way to store API keys, passwords, and any other secrets that your Function needs to use.
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. Currently, it is not possible to access request headers in the function execution context.
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 10 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.
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. |
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. |
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.