Building apps with Twilio Functions

Functions are written in Node.js and are executed in a v6.10 environment. They look like this:

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

The context parameter 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. Finally, callback is the method you call to return from the Function. 

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

var twiml = new Twilio.twiml.MessagingResponse()

You may also require the following NPM modules:

module version  
twilio 3.1.0-alpha-1 docs
got ^6.7.1 docs
lodash ^4.17.4 docs
xmldom ^0.1.27 docs

What information is in the context parameter?

On the Functions/Configuration page, you can set configuration variables for you app. These keys/values are attached to the context parameter. So you if you set the following key value pairs:

key = NAME, value = Phil
key = CITY, value = London

The context parameter will look like this:

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

You can also check a box that will attach your Account Sid and Auth Token to the context object. This will add ACCOUNT_SID and AUTH_TOKEN to the context object. If you do this, you will also be able to invoke a getTwilioClient function on the context object to get a fully-initialized Twilio REST API client.

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

What information is the in the event parameter?

GET and POST parameters are attached to the event parameter. 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 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 HTTP 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. 

Still need help?

Functions is in Public Beta and we have are inviting developers to ask question and get help on the Function Google Group

Have more questions? Submit a request
Powered by Zendesk