Programmable Voice

Learn how to make and answer phone calls using Twilio's Programmable Voice.

We often need to make phone calls through an application. We can do this by using the Programmable Voice API available in Twilio, which allows us to make and receive phone calls. We can play a default message or provide a customized one once the user picks up the call.

Press + to interact

Make an outgoing phone call

With just a few lines of code, our application can make an outgoing phone call using endpoints available in Twilio.

The base URL to make an outgoing phone call is as follows:

https://api.twilio.com/2010-04-01/Accounts/{TWILIO_ACCOUNT_SID}/Calls.json

Before diving into this endpoint’s request and response fields, let’s discuss Voice Geographic Permissions.

Voice Geographic Permissions

International Voice Dialing Geographic Permissions, also known as Geo Permissions, control which countries and subsets of phone numbers we can dial out to from our Twilio project. If we want to make outbound calls outside of the US, we need to correctly configure the Voice Geographic Permissions, explained below:

  1. Visit the Voice Geographic Permissions page.

  2. Search for the country we want to make a phone call to.

  3. Enable that country (by selecting the checkbox) so Twilio can make phone calls to any phone number in that country.

  4. Click the “Save” button.

Request parameters

The following table details the request parameters we need to define to make an outbound phone call.

Name

Type

Category

Description

From

String

Mandatory

The phone number we will use to make an outbound phone call.

Url

String

Mandatory

The URL that points to some TwiML, which tells Twilio what to do when the recipient answers their phone.

To

String

Mandatory

The phone number we make an outbound phone call to.

Let’s make a phone call using Twilio in the following code widget. We have given the following as the Url, which tells Twilio to read a message using text-to-speech and then to play an MP3:

http://demo.twilio.com/docs/voice.xml

Note: We have to make sure that the desired number we are calling is in the Verified Caller IDs.

Press + to interact
import fetch from "node-fetch";
//Define the header parameter
const header = {
'Authorization': 'Basic ' + Buffer.from('{{ACCOUNT_SID}}'+':'+'{{AUTH_TOKEN}}').toString('base64'),
'Content-Type': 'application/x-www-form-urlencoded',
};
//Define the endpoint url
const url = new URL('https://api.twilio.com/2010-04-01/Accounts/{{ACCOUNT_SID}}/Calls.json');
//Define the body parameters
const body = 'Url=http://demo.twilio.com/docs/voice.xml&To={{YOUR_PHONE_NUMBER}}&From={{TWILIO_PHONE_NUMBER}}';
//Set the API call options
const options = {
method: 'POST',
headers: header,
body: body
};
async function Phonecall() {
try {
const response = await fetch(url, options);
// Custom function for printing the API response
printResponse(response);
} catch (error) {
console.log(`Error: ${err}`);
}
}
Phonecall();

Note: If we do not receive a call within a minute, we can try again.

In the code above, we have the following:

  • Lines 4–7: We define the header parameter, which includes the access tokens.

  • Line 10: We define the endpoint URL and provide the ACCOUNT_SID.

  • Line 13: We define the body parameters and set the message body, source WhatsApp number, and destination WhatsApp number.

  • Lines 16–20: We define the options parameters and set the request type as POST.

  • Lines 22–30: We define the Phonecall function, which calls the endpoint.

  • Line 32: We call the Phonecall function.

Response fields

The details of the attributes found in the response field are given in the table below.

Name

Type

Description

sid

String

The ID associated with the call resource.

date_created

String

The date on which the call resource was created.

date_updated

String

The last date the call resource was updated.

parent_call_sid

String

The SID of the call resource.

account_sid

String

The SID of the account that created the service.

to

String

The phone number that received the phone call.

to_formatted

String

The formatted phone number that received the phone call.

from

String

The Twilio phone number that made the phone call.

from_formatted

String

The formatted Twilio phone number that made the phone call.

status

Enum

The status of the phone call. Expected output is queued, ringing, in-progress, canceled, completed, failed, busy, or no-answer.

start_time

String

The time at which the phone call started.

end_time

String

The time at which the phone call ended. Empty in case the call didn’t end.

duration

String

The length of the call in seconds.

price_unit

String

The currency in which the price of the call is measured.

price

String

The price for the phone call.

direction

String

The direction of the call. Possible output is inbound or outbound-api.

answered_by

String

Distinguishes between a call that was received by a human or an answering machine.

api_version

String

The version of the API used.

group_sid

String

The group SID associated with the call. Empty in case there isn't a group associated with the call.

queue_time

String

The time (in milliseconds) the call was in the waiting queue.

uri

String

The URI of the service, relative to Twilio.

Respond to incoming calls

When our Twilio number receives an incoming phone call, it sends an HTTP request to the webhook URL, asking for instructions on what to do next. By default, it uses this URL:

https://demo.twilio.com/welcome/voice/

We’ll use the following Express application to provide instructions on how to respond to incoming calls. To do this, we need to configure the webhook URL.

Configure the webhook URL

For Twilio to know where to look whenever it receives a new call, we need to configure our Twilio phone number to call our webhook URL. We can do this by following the steps below:

  1. Go to the Active Numbers page in our Twilio account’s dashboard.

  2. Select the Twilio number to which we want to make a call.

  3. Scroll down to the “Voice & Fax” section. In the “A CALL COMES IN” section, select “Webhook” and paste in the URL we want to use. For now, we can put the URL against the “Your app can be found at:” field in the widget at the end of this lesson. To keep it simple, we have given this URL separately below:

Press + to interact
{{EDUCATIVE_LIVE_VM_URL}}
Press + to interact
Configure the voice webhook
Configure the voice webhook
  1. Click the “Save” button to update the webhook URL.

Finally, it’s time to answer our first phone call using Twilio. Click the “Run” button in the following widget to start the server. When the server has started, call the Twilio phone number. We’ll hear a message that we already set up in the following widget in line 11.

const express = require('express');
const VoiceResponse = require('twilio').twiml.VoiceResponse;

const app = express();

// Create a route that will handle Twilio webhook requests, sent as an
// HTTP POST to /voice in our application
app.post('/', (request, response) => {
  // Use the Twilio Node.js SDK to build an XML response
  const twiml = new VoiceResponse();
  twiml.say({ voice: 'alice' }, 'hello world! we have made our first call');

  // Render the response as XML in reply to the webhook request
  response.type('text/xml');
  response.send(twiml.toString());
});

// Create an HTTP server and listen for requests on port 3000
app.listen(3000, () => {
  console.log(
    'Now listening on port 3000. ' +
    'Be sure to restart when you make code changes!'
  );
});
Custom response to incoming phone call