Using Twilio API in Node.js
Tags: javascript, node, npm, ubuntu
Published: 2022-03-03 14:12:42

Banner courtesy of [Spencer Gabor](https://dribbble.com/spencergabor)

**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](https://www.twilio.com/pricing).
<br>
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
1. NPM
1. Dotenv

**STEP 1**

Firstly, install twilio library through node package manager (npm). As prerequisites, install [node.js](https://nodejs.org/en/), and [npm](https://www.npmjs.com/). If you are on Ubuntu 20.04, open terminal, and run the following commands.

```
sudo apt install nodejs
sudo apt install npm
```
You can also use different methods to install Node, and npm as shown [here](https://www.digitalocean.com/community/tutorials/how-to-install-node-js-on-ubuntu-20-04).

Make a new directory `mkdir`, and `cd` into that directory. Initialize the directory with: 
```
npm init
```
Then install the node.js twilio library through:

```
npm install twilio
```

**STEP 2**

Sign up to [twilio](https://www.twilio.com/), 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
```

- 
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}
```
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));
```

- 
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](https://en.wikipedia.org/wiki/E.164) 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));
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/edcbabenvg8em3zbn4hm.png)
Select country, and save. 

**Run and Test**
Back in you development environment, save your code, and run it on terminal:
```
node script.js
```
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"
}
```
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.