DEV Community

Cover image for Using Twilio API in Node.js
Samuel Mugane
Samuel Mugane

Posted on

Using Twilio API in Node.js

Banner courtesy of Spencer Gabor

Introduction

APIs (Application programmable interfaces) have revolutionized how data is shared in different sectors across the globe. Developers have a more easier way of accessing data, and providing uniquely, well crafted services to their customers through APIs. Twilio has been a key player in revolutionizing how communication can be leveraged by developers to enhance customer service. Twilio offers programmable voice calls, short-message service (SMS), email service and whatsapp integration as some of the products available to developers. The Twilio API is a pay as you go service, and provides a reliable API for communication. Find more about pricing here.


The article focuses on making programmable voice calls, and sending SMS. Twilio API calls for both voice calls, and SMS are easy to make especially when one is familiar with the node environment. The following steps will have you setup, and running:

Prerequisites

  1. Node.js
  2. NPM
  3. Dotenv

STEP 1

Firstly, install twilio library through node package manager (npm). As prerequisites, install node.js, and npm. If you are on Ubuntu 20.04, open terminal, and run the following commands.

sudo apt install nodejs
sudo apt install npm
Enter fullscreen mode Exit fullscreen mode

You can also use different methods to install Node, and npm as shown here.

Make a new directory mkdir, and cd into that directory. Initialize the directory with:

npm init
Enter fullscreen mode Exit fullscreen mode

Then install the node.js twilio library through:

npm install twilio
Enter fullscreen mode Exit fullscreen mode

STEP 2

Sign up to twilio, and set up a phone number. Under your account info, you'll see your account SID, Auth token, and phone number. Copy them to the clipboard.

STEP 3

In your node development environment, set up a dotenv (.env) file to create environment variables to secure your account SID, and Auth token. As a prerequisite, install dotenv using npm:

npm install dotenv --save
Enter fullscreen mode Exit fullscreen mode
  • In your dotenv file, paste your account SID, and Auth Token in the following format:
TWILIO_ACCOUNT_SID={your account SID}
TWILIO_AUTH_TOKEN={your Auth token}
Enter fullscreen mode Exit fullscreen mode

Ensure no spacing between variable name, equal sign, and value. Also, remove curly braces when keying the values.

  • In your development environment, create script.js file, and paste the following code:
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
require('dotenv').config();
const client = require('twilio')(accountSid, authToken);

client.calls
      .create({
         url: 'http://demo.twilio.com/docs/voice.xml',
         to: '',
         from: ''
       })
      .then(call => console.log(call));
Enter fullscreen mode Exit fullscreen mode
  • Paste your phone number as a string to the from: key, and the phone number your want to call on to: key i.e (area code) – (phone number) or (XXX)- XXX - XXXX . Ensure to follow the E.164 format while entering the phone numbers. For message API calls. Using the following code:
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
require('dotenv').config();
const client = require('twilio')(accountSid, authToken);

client.messages
      .create({
         body: ' ',
         to: '',
         from: ''
       })
      .then(call => console.log(call));
Enter fullscreen mode Exit fullscreen mode

Under body: key, enter your message.

  • N/B To avoid error during call due to Geo restrictions, go back to your twilio account dashboard, on your left tab click on #phone, and go to settings. Click on Geo permissions, search for your country and enable as shown below: Geo permission settings Select country, and save.

Run and Test
Back in you development environment, save your code, and run it on terminal:

node script.js
Enter fullscreen mode Exit fullscreen mode

A JSON response will be logged to your console:

{
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "annotation": null,
  "answered_by": null,
  "api_version": "2010-04-01",
  "caller_name": null,
  "date_created": "Tue, 31 Aug 2010 20:36:28 +0000",
  "date_updated": "Tue, 31 Aug 2010 20:36:44 +0000",
  "direction": "inbound",
  "duration": "15",
  "end_time": "Tue, 31 Aug 2010 20:36:44 +0000",
  "forwarded_from": "+141586753093",
  "from": "+987654321",
  "from_formatted": "+987654321",
  "group_sid": null,
  "parent_call_sid": null,
  "phone_number_sid": "PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "price": "-0.03000",
  "price_unit": "USD",
  "sid": "CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "start_time": "Tue, 31 Aug 2010 20:36:29 +0000",
  "status": "completed",
  "subresource_uris": {
    "notifications": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Notifications.json",
    "recordings": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings.json",
    "feedback": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Feedback.json",
    "feedback_summaries": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/FeedbackSummary.json",
    "payments": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Payments.json",
    "events": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Events.json",
    "siprec": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Siprec.json",
    "streams": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Streams.json"
  },
  "to": "+123456789",
  "to_formatted": "+123456789",
  "trunk_sid": null,
  "uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json",
  "queue_time": "1000"
}
Enter fullscreen mode Exit fullscreen mode

if status is complete, you'll receive a demo call to the number you entered to the to: key.

Conclusion

Twilio has a great use case in automating sending confirmation code through SMS or email to users. The programmable voice allows one to make, and receive calls with no hassle.

Top comments (2)

Collapse
 
mashoado profile image
MashoAdo

Good article...Easy to follow , simple and elaborate explanation on how to intergrate the Twilio Api into your application.πŸ‘Œ

Collapse
 
roguecode25 profile image
Samuel Mugane

Thanks!