The Twilio platform makes adding voice, SMS, and VoIP capabilities to your applications ridiculously simple. This helper library for node aims to make it even easier. This documentation page code and format is adapted from the awesome/utilitary format used to document the popular Backbone and Underscore JavaScript frameworks, created by Jeremy Ashkenas and other open source contributors.
The twilio-node project is hosted on GitHub. You can report bugs and discuss features on the issues page, on Freenode in the #twilio channel, or send tweets to @kevinwhinnery.
twilio-node is available as an npm package. Install the latest version with:
npm install twilio
To begin using Twilio to make voice calls, send SMS, and create VoIP clients, you first need to sign up for an account. After signing up, you will be able to access an account SID and auth token which will be used to authenticate requests to the Twilio back end. This information can be found on your dashboard:
With these credentials, you can begin to use this node module, as in the following example:
//require the Twilio module and create a REST client
var client = require('twilio')('ACCOUNT_SID', 'AUTH_TOKEN');
//Send an SMS text message
client.sendSms({
to:'+16515556677', // Any number Twilio can deliver to
from: '+14506667788', // A number you bought from Twilio and can use for outbound communication
body: 'word to your mother.' // body of the SMS message
}, function(err, responseData) { //this function is executed when a response is received from Twilio
if (!err) { // "err" is an error received during the request, if any
// "responseData" is a JavaScript object containing data received from Twilio.
// A sample response from sending an SMS message is here (click "JSON" to see how the data appears in JavaScript):
// http://www.twilio.com/docs/api/rest/sending-sms#example-1
console.log(responseData.from); // outputs "+14506667788"
console.log(responseData.body); // outputs "word to your mother."
}
});
//Place a phone call, and respond with TwiML instructions from the given URL
client.makeCall({
to:'+16515556677', // Any number Twilio can call
from: '+14506667788', // A number you bought from Twilio and can use for outbound communication
url: 'http://www.example.com/twiml.php' // A URL that produces an XML document (TwiML) which contains instructions for the call
}, function(err, responseData) {
//executed when the call has been initiated.
console.log(responseData.from); // outputs "+14506667788"
});
//Loop through a list of SMS messages sent from a given number
client.listSms({
from:'+16512223333'
}, function (err, responseData) {
responseData.smsMessages.forEach(function(message) {
console.log('Message sent on: '+message.dateCreated.toLocaleDateString());
console.log(message.body);
});
});
More examples can be found in the "spec" directory of this project on GitHub, as Jasmine unit tests.
RestClient exposes the REST API of Twilio, but takes care of content negotiation and HTTP requests for you. The client object is intended to mirror the API pretty directly, so the existing REST API reference will be a good source of information on what each function does. The major resources and available methods for the REST API will be described here, along with shorthand where it exists.
How This API is Structured
The RestClient API is intended to be self-documenting, mapping very closely to the actual
REST API. Once you have created a client object,
the object structure looks very much like the Twilio REST URIs, using a chained JavaScript syntax:
// Create a client:
var client = require('twilio')('ACCOUNT_SID', 'AUTH_TOKEN');
//Get a list of calls made by this account
// GET /2010-04-01/Accounts/ACCOUNT_SID/Calls
// alias for get is "list", if you prefer
client.calls.get(function(err, response) {
response.calls.forEach(function(call) {
console.log('Received call from: ' + call.from);
console.log('Call duration (in seconds): ' + call.duration);
});
});
//Get a list of calls made by this account, from this phone number
// GET /2010-04-01/Accounts/ACCOUNT_SID/Calls?From=+16513334455
client.calls.get({
from:'+16513334455'
}, function(err, response) {
response.calls.forEach(function(call) {
console.log('Received call from: ' + call.from);
console.log('This call\'s unique ID is: ' + call.sid);
});
});
//Get data for a specific call
// GET /2010-04-01/Accounts/ACCOUNT_SID/Calls/abc123...
client.calls('abc123...').get(function(err, call) {
console.log('This call\'s unique ID is: ' + call.sid);
console.log('This call was created at: ' + call.dateCreated);
});
//Get data for a specific call, for a specific account
// GET /2010-04-01/Accounts/AC.../Calls/abc123...
client.accounts('AC...').calls('abc123...').get(function(err, response) {
response.calls.forEach(function(call) {
console.log('Received call from: ' + call.from);
console.log('This call\'s unique ID is: ' + call.sid);
});
});
// Create (send) an SMS message
// POST /2010-04-01/Accounts/ACCOUNT_SID/SMS/Messages
// "create" and "update" aliases are in place where appropriate on PUT and POST requests
client.sms.messages.post({
to:'+16515559999',
from:'+14503334455',
body:'word to your mother.'
}, function(err, text) {
console.log('You sent: '+ text.body);
console.log('Current status of this text message is: '+ text.status);
});
// Delete a TwiML application
// DELETE /2010-04-01/Accounts/ACCOUNT_SID/Applications/APP...
client.applications('APP...').delete(function(err, response, nodeResponse) {
//DELETE requests do not return data - if there was no error, it worked.
err ? console.log('There was an error') : console.log('it worked!');
});
Any resource request you make can be done for a specific subaccount as well. This lets you track usage of calls, text messages, etc. for different users of your application. By default, all requests are made using the "master" account, but using the "accounts" resource allows you to make all the same requests, but for a specific account:
var client = require('twilio')('ACCOUNT_SID', 'AUTH_TOKEN'),
SOME_SUBACCOUNT_SID = 'AC...';
//Send a text message, associated with the given subaccount
client.accounts(SOME_SUBACCOUNT_SID).sms.messages.create({
to:'+16512223333',
from:'+14505556677',
body:'word to your subaccount mother.'
}, function(err, text) {
console.log('You sent: '+ text.body);
console.log('Current status of this text message is: '+ text.status);
});
//This REST call using the master/default account for the client...
client.makeCall({
to:'+16512223333',
from:'+14505556677',
url:'http://example.com/someTwiml.php'
}, function(err, call) {
console.log('This call\'s unique ID is: ' + call.sid);
console.log('This call was created at: ' + call.dateCreated);
});
//...is the same as...
client.accounts(ACCOUNT_SID).calls.create({
to:'+16512223333',
from:'+14505556677',
url:'http://example.com/someTwiml.php'
}, function(err, data) {
console.log('This call\'s unique ID is: ' + call.sid);
console.log('This call was created at: ' + call.dateCreated);
});
twilio.RestClienttwilio.RestClient([accountSid, authToken, clientOptions])
Creates a new REST client object, using the given account SID and auth token, as available on your
Twilio dashboard when
create an account and log in.
These credentials are used to authorize your requests
to the Twilio back end. REST clients can be created for
subaccounts,
but requests will then only be authorized to access resources associated with that subaccount.
If you omit the accountSid and authToken parameters, the module will attempt
to initialize the client with environment variables, as found in process.env.TWILIO_ACCOUNT_SID and
process.env.TWILIO_AUTH_TOKEN. For production web applications, storing account crendentials in
environment variables can be useful, so that sensitive information is never checked in to source control.
Example:
//Two-liner
var twilio = require('twilio');
var client = new twilio.RestClient('ACCOUNT_SID', 'AUTH_TOKEN');
//Two-liner, with environment variables set
var twilio = require('twilio');
var client = new twilio.RestClient();
//One-liner
var client = require('twilio')('ACCOUNT_SID', 'AUTH_TOKEN');
//One-liner, with environment variables set
var client = require('twilio')();
requestclient.request(requestOptions[, callback])
Makes an authenticated HTTP request against the Twilio back end. Typically, an end user
WILL NOT use this function, but rather one of the resource-specific functions or
shorthand functions.
Example:
var twilio = require('twilio');
var client = new twilio.RestClient('ACCOUNT_SID', 'AUTH_TOKEN');
client.request({
url:'/Accounts',
method:'GET'
}, function (error, responseData, nodeClientResponse) {
//work with response data
});
The following is a listing of REST resources surfaced in the RestClient. Supported list and instance functions are shown here, which should map 1:1 to the supported HTTP methods in the Twilio REST API (plus "create" and "update" aliases as relevant).
Resource Request Argument Format
All requests on Twilio REST resources follow the same format. The first argument to a RestClient
resource function is an optional JavaScript object hash of either query parameters for a GET or
POST/PUT parameters which will be form-encoded and sent along with the request. The second
(or maybe only) argument is a callback which receives the same arguments as the
callback function in the direct request API. An example of the request format is below.
Typically, Twilio REST APIs use upper-cased parameter names. When using this client module, you can omit the
upper-case first character if you wish.
Examples:
//A sample request with both POST parameters, and a callback
client.sms.messages.create({
//For an "update", "create", "post", or "put" request these properties are form-encoded and sent to Twilio:
to:'+16515554466',
from:'+14503334455',
body:'word to your mother.'
}, function(err, responseData) { //this function is executed when a response is received from Twilio
if (!err) { // "err" is an error received during the request, if any
// "responseData" is a JavaScript object containing data received from Twilio.
// A sample response from sending an SMS message is here (click "JSON" to see how the data appears in JavaScript):
// http://www.twilio.com/docs/api/rest/sending-sms#example-1
console.log(responseData.from); // outputs "+14506667788"
console.log(responseData.body); // outputs "word to your mother."
// you can also access the raw node.js http.ClientResponse object:
// http://nodejs.org/api/http.html#http_http_clientresponse
console.log(responseData.nodeClientResponse.statusCode); //outputs "200" if the request was successful
}
});
//A sample request with no parameters, just a callback
client.accounts('AC...').calls.get(function (err, response) {
response.calls.forEach(function(call) {
console.log('Received call from: ' + call.from);
console.log('This call\'s unique ID is: ' + call.sid);
});
});
accountsclient.accounts([accountSid])
Accesses Account resources via the REST interface.
Refer to the official REST API documentation
for response data format and usage examples.
Instance Functions:
availablePhoneNumbersclient.availablePhoneNumbers([IsoCountryCode]).[Local/TollFree]
Accesses AvailablePhoneNumbers
resources via the REST interface. Accessed primarily through Subresources for local and
tollFree numbers.
Refer to the official REST API documentation
for response data format and usage examples.
List Functions:
outgoingCallerIdsclient.outgoingCallerIds([callerIdSid])
Accesses OutgoingCallerIds
resources via the REST interface.
Refer to the official REST API documentation
for response data format and usage examples.
Instance Functions:
incomingPhoneNumbersclient.incomingPhoneNumbers([incomingNumberSid])
Accesses IncomingPhoneNumbers
resources via the REST interface. Includes subresources for local and toll free numbers.
Refer to the official REST API documentation
for response data format and usage examples.
Instance Functions:
sms.messagesclient.sms.messages([messageSid])
Accesses SMS/Messages
resources via the REST interface.
Refer to the official REST API documentation
for response data format and usage examples.
Instance Functions:
sms.shortCodesclient.sms.shortCodes([messageSid])
Accesses SMS/ShortCodes
resources via the REST interface.
Refer to the official REST API documentation
for response data format and usage examples.
Instance Functions:
applicationsclient.applications([applicationSid])
Accesses Applications
resources via the REST interface.
Refer to the official REST API documentation
for response data format and usage examples.
Instance Functions:
connectAppsclient.connectApps([applicationSid])
Accesses Connect Apps
resources via the REST interface.
Refer to the official REST API documentation
for response data format and usage examples.
Instance Functions:
Instance Functions:
callsclient.calls([callSid])
Accesses Calls
resources via the REST interface.
Refer to the official REST API documentation
for response data format and usage examples.
Instance Functions:
conferencesclient.conferences([conferenceSid])
Accesses Conference
resources via the REST interface.
Refer to the official REST API documentation
for response data format and usage examples.
Instance Functions:
queuesclient.queues([queueSid])
Accesses Queues
resources via the REST interface.
Refer to the official REST API documentation
for response data format and usage examples.
Instance Functions:
recordingsclient.recordings([recordingSid])
Accesses Recordings
resources via the REST interface.
Refer to the official REST API documentation
for response data format and usage examples.
Instance Functions:
transcriptionsclient.transcriptions([transcriptionSid])
Accesses Transcriptions
resources via the REST interface.
Refer to the official REST API documentation
for response data format and usage examples.
Instance Functions:
notificationsclient.notifications([notificationSid])
Accesses Notification
resources via the REST interface.
Refer to the official REST API documentation
for response data format and usage examples.
Instance Functions:
usage.recordsclient.usage.records([recordSid])
Accesses Usage Records
resources via the REST interface.
Refer to the official REST API documentation
for response data format and usage examples.
Instance Functions:
usage.triggersclient.usage.triggers([triggerSid])
Accesses Usage Triggers
resources via the REST interface.
Refer to the official REST API documentation
for response data format and usage examples.
Instance Functions:
When your Twilio application needs to respond to an incoming SMS message or voice call input, the developer gives Twilio instructions on what to do using a special XML instruction set called "TwiML". The TwimlResponse object makes creating a proper TwiML XML string very easy. The resulting TwiML string can be rendered to the end user using the node.js HTTP server APIs directly, or using a higher level web framework like express.
Constructornew twilio.TwimlResponse()
Create a TwiML
response, which can later be serialized to XML.
Example:
var twilio = require('twilio');
var resp = new twilio.TwimlResponse();
TwiML Basics
The TwimlResponse object provides JavaScript functions to construct the
TwiML verbs that are appropriate
for the given parent node. Each JavaScript function takes the following arguments, in any order:
var twilio = require('twilio');
var resp = new twilio.TwimlResponse();
resp.say('Welcome to Twilio!');
resp.say('Please let us know if we can help during your development.', {
voice:'woman',
language:'en-gb'
});
console.log(resp.toString());
/**
Outputs the following:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say>Welcome to Twilio!</Say>
<Say voice="woman" language="en-gb">Please let us know if we can help during your development.</Say>
</Response>
*/
Rendering the actual XML document is done with the toString function. The following node program would render a TwiML document when a request was received to the HTTP server running on port 1337:
var http = require('http'),
twilio = require('twilio');
http.createServer(function (req, res) {
//Create TwiML response
var twiml = new twilio.TwimlResponse();
twiml.say('Hello World!');
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
}).listen(1337, '127.0.0.1');
console.log('TwiML servin\' server running at http://127.0.0.1:1337/');
Chaining Syntax
You can add multiple nodes to a TwiML document in a single statement by chaining function calls:
var twilio = require('twilio');
var resp = new twilio.TwimlResponse();
resp.say('Welcome to Twilio!')
.pause({ length:3 })
.say('Please let us know if we can help during your development.', {
voice:'woman',
language:'en-gb'
})
.play('http://www.example.com/some_sound.mp3');
console.log(resp.toString());
/**
Outputs the following:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say>Welcome to Twilio!</Say>
<Pause length="3"></Pause>
<Say voice="woman" language="en-gb">Please let us know if we can help during your development.</Say>
<Play>http://www.example.com/some_sound.mp3</Play>
</Response>
*/
Nesting TwiML Nodes
Some TwiML verbs have other nouns or verbs nested within them. You can create these nested structures
by passing a function to a parent node, which will be executed in the context of the parent node.
Within this callback function, this will refer to the parent node, which will have JavaScript
functions that map to the allowed syntax for child nodes of the parent:
var twilio = require('twilio');
var resp = new twilio.TwimlResponse();
resp.say('Welcome to Acme Customer Service!')
.gather({
action:'http://www.example.com/callFinished.php',
finishOnKey:'*'
}, function() {
this.say('Press 1 for customer service')
.say('Press 2 for British customer service', { language:'en-gb' });
});
console.log(resp.toString());
/**
Outputs the following:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say>Welcome to Acme Customer Service!</Say>
<Gather action="http://www.example.com/callFinished.php" finishOnKey="*">
<Say>Press 1 for customer service.</Say>
<Say language="en-gb">Press 2 for British customer service.</Say>
</Gather>
</Response>
*/
Alternately, the first argument to the child node building function is also a reference to the parent node, so the following code is equivalent:
var twilio = require('twilio');
var resp = new twilio.TwimlResponse();
resp.say('Welcome to Acme Customer Service!')
.gather({
action:'http://www.example.com/callFinished.php',
finishOnKey:'*'
}, function(node) { //note the use of the "node" variable in the anonymous function
//Now you can use this reference as well, if using "this" wrankles you
node.say('Press 1 for customer service')
.say('Press 2 for British customer service', { language:'en-gb' });
});
console.log(resp.toString());
/**
Outputs the following:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say>Welcome to Acme Customer Service!</Say>
<Gather action="http://www.example.com/callFinished.php" finishOnKey="*">
<Say>Press 1 for customer service.</Say>
<Say language="en-gb">Press 2 for British customer service.</Say>
</Gather>
</Response>
*/
Using Twilio Client requires the use of a capability token, which enables client access to Twilio's VoIP platform. These capability tokens can be used either in the browser or in native apps for iOS and Android. This utility is intended to allow node.js applications the ability to generate these capability tokens on the server side. For a complete node example using the express web framework, check out the examples on GitHub.
Constructornew twilio.Capability(accountSid, authToken)
Create a capability token generator for use with Twilio Client.
Example:
var twilio = require('twilio');
var capability = new twilio.Capability(ACCOUNT_SID, AUTH_TOKEN);
allowClientIncomingcapability.allowClientIncoming(clientName)
Add a capability to the token generator which will allow incoming calls to the given clientName.
Example:
var twilio = require('twilio');
var capability = new twilio.Capability(ACCOUNT_SID, AUTH_TOKEN);
//Create a capability token for a client named "jenny"
capability.allowClientIncoming('jenny');
var token = capability.generate();
allowClientOutgoingcapability.allowClientOutgoing(twimlAppSid)
Add a capability to the token generator which will allow the client to make outgoing calls,
using the TwiML app with the given
twimlAppSid
Example:
var twilio = require('twilio');
var capability = new twilio.Capability(ACCOUNT_SID, AUTH_TOKEN);
//Create a capability token using the TwiML app with sid "AP123"
capability.allowClientOutgoing('AP123');
var token = capability.generate();
generatecapability.generate([timeout])
Generate a capability token with the configured permissions, which by default will expire
after one hour.
Example:
var twilio = require('twilio');
var capability = new twilio.Capability(ACCOUNT_SID, AUTH_TOKEN);
//Create a capability token using the TwiML app with sid "AP123", that expires in two minutes
capability.allowClientOutgoing('AP123');
var token = capability.generate(120);
validateRequesttwilio.validateRequest(authToken, header, url, params)
When Twilio sends a request to your web app, it sends a special header called X-Twilio-Signature.
This header is a hashed value that we can use on the server side to confirm that a request has indeed
originated from Twilio. More details on this security measure are located
here.
This function will return a boolean indicating whether or not, given the request URL, POST/GET parameters,
and your auth token, a request was actually sent from Twilio.
Example:
var twilio = require('twilio'),
http = require('http'),
qs = require('querystring');
http.createServer(function (req, res) {
if (req.method == 'POST') {
var body = '';
req.on('data', function (data) {
body += data;
});
req.on('end', function () {
var POST = qs.parse(body);
//validate incoming request is from twilio using your auth token and the header from Twilio
var token = 'YOUR_TWILIO_AUTH_TOKEN',
header = req.headers['x-twilio-signature'];
//validateRequest returns true if the request originated from Twilio
if (twilio.validateRequest(token, header, 'http://twilio-raw.herokuapp.com', POST)) {
//generate a TwiML response
var resp = new twilio.TwimlResponse();
resp.say('hello, twilio!');
res.writeHead(200, { 'Content-Type':'text/xml' });
res.end(resp.toString());
}
else {
res.writeHead(403, { 'Content-Type':'text/plain' });
res.end('you are not twilio - take a hike.');
}
});
}
else {
res.writeHead(404, { 'Content-Type':'text/plain' });
res.end('send a POST');
}
}).listen(80);
validateExpressRequesttwilio.validateExpressRequest(request, authToken)
This is a helper function which decomposes an Express request object
and uses validateRequest to determine if the request was sent by Twilio. Returns true
if the request was sent by Twilio.
Example:
var express = require('express'),
http = require('http'),
path = require('path'),
twilio = require('twilio');
var app = express();
app.configure(function () {
/* Configure your express app... */
});
//Twilio request authentication
app.post('/twiml', function(req, res) {
if (twilio.validateExpressRequest(req, 'YOUR_TWILIO_AUTH_TOKEN')) {
var resp = new twilio.TwimlResponse();
resp.say('express sez - hello twilio!');
res.type('text/xml');
res.send(resp.toString());
}
else {
res.send('you are not twilio. Buzz off.');
}
});
Usage of the Twilio platform requires a valid account SID and auth token. You can sign up and receive those credentials here.
The official Twilio docs are located here.
Helper libraries are available for a variety of environments and programming langauges - check out Twilio's GitHub repository here.
1.1.0 —
Mar. 18, 2013 —
Diff
1.0.1 —
Mar. 9, 2013 —
Diff
1.0.0 —
Mar. 6, 2013
0.8.0 —
Feb. 12, 2013
Added in a bit of sugar to alias underscore-separated properties in Twilio REST responses to camel case to make it more JavaScripty. So data.smsMessages is aliases to data.sms_messages. Also, auto-parsing Date objects for any response properties called:
All underscore-separated values are the raw values passed back by Twilio in JSON.
0.7.1 —
Jan. 3, 2013
0.7.0 —
Dec. 28, 2012
0.6.2 —
Dec. 27, 2012
0.6.1 —
Dec. 21, 2012
0.6.0 —
Dec. 20, 2012
0.5.0 —
Dec. 19, 2012 —