Building apps with Twilio Functions (Beta)

Twilio Functions (Beta) provide a complete runtime environment for executing your Node.js 8.10 scripts. Functions integrates popular package managers like NPM, and provides a low latency Twilio-hosted environment for your application. Read on for more information on how to use Functions with your Twilio project.

Notice: Twilio Functions is currently in beta, and has not yet been finalized. Support requests for beta and pre-release products are generally handled by our engineering team, and as such, response times are not guaranteed. For more information on Support limitations for beta and pre-release products, please see Twilio Beta Product Support.

Getting Started with Functions

Here's an example of what a Functions script looks like:

exports.handler = function(context, event, callback) {
  // code
  // invoke callback function
}

The handler method is the starting point of your function, and accepts the following 3 arguments:

  • The context object includes information about your Runtime, such as configuration variables.
  • The event object includes information about a specific invocation, including HTTP parameters from the HTTP request.
  • The callback Function completes execution of your code.

When writing code for your Function, you can reference the Twilio Node helper library using the Twilio global:

var twiml = new Twilio.twiml.MessagingResponse()

What information is in the Context object?

On the Functions Configuration page in Console, you can configure environmental variables for your app. These key/value pairs are attached to the context parameter.

For example, setting the following key value pairs:
GSG_01_400.png

Results in this context object response:

{
  NAME: 'Phil',
  CITY: 'London'
}

You can also allow your project credentials (Account Sid and Auth Token) to be accessible via the context object. This enables you to invoke the getTwilioClient method on the context object for a fully-initialized Twilio REST API client.

var client = context.getTwilioClient()
client.messages.create({to: '+12025551212', from: '+12065551212', body: "hello world!"})

For more details, please see Enable and Configure Credentials and Environmental Variables with Twilio Functions.

What information is the in the Event object?

GET and POST parameters are attached to the event object. For instance, if an HTTP request to your Function looked like this:

curl -XPOST -d "c=d" https://your-domain-1234.twil.io/path?a=b

The event object would look like this:

{
  a: 'b',
  c: 'd'
}

If a POST parameter and GET parameter have the same name, the POST parameter will take precedence.

How do I use the Callback to return from a Function?

When you're ready to return from your Function, you invoke callback. In non-error situations the first parameter is null and the second parameter is the value you want to return.

If you return a TwiML object, Functions will ensure that this is turned into XML and content-type is set to text/xml.

var twiml = new Twilio.twiml.MessagingResponse()
callback(null, twiml)

If you return a JavaScript object, Functions will convert to JSON and set the content-type to application/json.

callback(null, {token: "abcdef"})

If you return a String, Functions will return a String and set the content-type to text/plain.

callback(null, "OK")

If you return a String as the first parameter, Functions will return the string as text/plain and set the response code to HTTP 500.

callback("NOT OK")

How do I generate TwiML?

If you're building Voice or SMS applications, you'll often want to generate TwiML. There are two kinds of TwiML: Voice TwiML and Messaging TwiML. You can use the Twilio Node helper library to programmatically generate both of these kinds of TwiML.

Voice TwiML

var twiml = new Twilio.twiml.VoiceResponse()
twiml.dial().sip("sip:jack@example.com")
console.log(twiml.toString())
//<Response><Dial><Sip>sip:jack@example.com</Sip></Dial></Response>

Messaging TwiML

var twiml = new Twilio.twiml.MessagingResponse()
twiml.message("Hello SMS")
console.log(twiml.toString())
// <Response><Message>Hello SMS</Message></Response>

How do I call 3rd party REST APIs?

If you want to use 3rd party REST APIs in your Functions, you can leverage the built-in got module. Here's an example of making a GET request:

var got = require('got');
got('https://swapi.co/api/people/?search=r2', {json: true})
.then(function(response) {
console.log(response)
twiml.message(response.body.results[0].url)
callback(null, twiml);
})
.catch(function(error) {
callback(error)
})

Sometimes you'll want to POST data to an API. Here is an example of sending a POST with a JSON payload and setting the Accept header to application/json:

var got = require('got');
var requestPayload = {foo: 'bar'};

got.post('https://your-api.com/endpoint',
{ body: JSON.stringify(requestPayload),
headers: {
'accept': 'application/json'
},
json: true
}).then(function(response) {
console.log(response.body)
callback(null, response.body);

}).catch(function(error) {
callback(error)
});

Note: Due to the asynchronous nature of Node, please remember to execute your callback only after your HTTP request has finished. Executing callback terminates the execution of your Function, including any in-flight async code.

Additional Resources

Have more questions? Submit a request
Powered by Zendesk