Skip to contentSkip to navigationSkip to topbar
Page toolsOn this page
Looking for more inspiration?Visit the

Respond to Incoming Phone Calls


Learn to handle and answer inbound calls with Twilio Programmable Voice by serving a TwiML document in response to the Twilio HTTP webhook request when a call is received. You can use this guide to create self-service automation and build inbound contact centers.

See Related reference documentation to learn more about the TwiML elements used in this guide.


Complete the prerequisites

complete-the-prerequisites page anchor

Complete the Twilio prerequisites

complete-the-twilio-prerequisites page anchor

Complete the language prerequisites

complete-the-language-prerequisites page anchor

Select your programming language and complete the prerequisites:

PythonNode.jsPHPC# or .NETJavaRuby
  • Install Python 3.3 or later(link takes you to an external page).
  • Install Flask(link takes you to an external page) and the Twilio Python Helper Library(link takes you to an external page). Using pip(link takes you to an external page), run the following command:
    pip install flask twilio
  • Install and set up ngrok(link takes you to an external page).

Get credentials and set as environment variables

get-credentials-and-set-as-environment-variables page anchor

Extract your credentials from your Twilio account then save these credentials as environment variables.

Twilio ConsoleLegacy Console
  1. Go to the Twilio Console(link takes you to an external page). The Let's get building page appears.

  2. Click API keys and Auth tokens. The API keys & auth tokens page appears with the Auth Tokens tab selected.

  3. Scroll to your Account SID.

  4. Click the copy button next to your Account SID.

  5. Run the following command, replacing YOUR_ACCOUNT_SID with your Account SID.

    macOS TerminalWindows command linePowerShell
    export TWILIO_ACCOUNT_SID=YOUR_ACCOUNT_SID

    This command creates an environment variable on your development system for your account SID.

  6. To display the Auth Token, click the eye button in the Primary auth token box.

  7. Highlight and copy the Auth Token.

  8. Run the following command, replacing YOUR_AUTH_TOKEN with your Authentication Token.

    macOS TerminalWindows command linePowerShell
    export TWILIO_AUTH_TOKEN=YOUR_AUTH_TOKEN

    This command creates an environment variable on your development system for your auth token.


Respond to an incoming call

respond-to-an-incoming-call page anchor

When a Twilio phone number receives an incoming call, Twilio sends an HTTP request to your web app. This request asks for instructions on how you want the call handled. Your web app responds with an TwiML document. Twilio takes the instruction set from that document and performs an action. This might include saying some arbitrary text, playing an MP3 file, or recording the call audio.

To respond to an inbound call, send a response request to Twilio using one of these helper libraries.

PythonNode.jsPHPC# or .NETJavaRuby

Python only requires the Twilio Python helper library as noted in the prerequisites.

Respond to an incoming call with TwiMLLink to code sample: Respond to an incoming call with TwiML
1
from flask import Flask
2
from twilio.twiml.voice_response import VoiceResponse
3
4
app = Flask(__name__)
5
6
7
@app.route("/voice", methods=['GET', 'POST'])
8
def voice():
9
"""Respond to incoming phone calls with a 'Hello world' message"""
10
# Start our TwiML response
11
resp = VoiceResponse()
12
13
# Read a message aloud to the caller
14
resp.say("Hello world!")
15
16
return str(resp)
17
18
if __name__ == "__main__":
19
app.run(debug=True)

TwiML response document

twiml-response-document page anchor
1
<?xml version="1.0" encoding="UTF-8"?>
2
<Response>
3
<Say>Hello world!</Say>
4
</Response>

Create dynamic responses to incoming calls

create-dynamic-responses-to-incoming-calls page anchor

The previous section provided code that responds to an incoming call with a pre-defined TwiML document. Using the data Twilio sends to your app through webhooks, you can change what gets presented to the user on the other end of the phone call. You can write custom code that gathers additional server-side data that builds your response to your user.

To create a custom response to an inbound call, send a response request to Twilio using one of these helper libraries.

PythonNode.jsPHPC# or .NETJavaRuby

Python only requires the Twilio Python helper library as noted in the prerequisites.

Create a dynamic response to an incoming callLink to code sample: Create a dynamic response to an incoming call
1
from flask import Flask, request
2
from twilio.twiml.voice_response import VoiceResponse
3
4
app = Flask(__name__)
5
6
7
@app.route("/voice", methods=['GET', 'POST'])
8
def voice():
9
"""Respond to incoming phone calls and mention the caller's city"""
10
# Get the caller's city from Twilio's request to our app
11
city = request.values['FromCity']
12
13
# Start our TwiML response
14
resp = VoiceResponse()
15
16
# Read a message aloud to the caller
17
resp.say('Never gonna give you up, {}!'.format(city))
18
19
# Play an audio file for the caller
20
resp.play('https://demo.twilio.com/docs/classic.mp3')
21
22
return str(resp)
23
24
if __name__ == "__main__":
25
app.run(debug=True)

Expose your local dev environment to Twilio with ngrok

expose-your-local-dev-environment-to-twilio-with-ngrok page anchor

To use the webhooks in this code sample, Twilio must communicate with your web app. These communications consist of HTTP requests sent between URLs accessible over the internet. Twilio requires access to Internet-addressable, or public, URLs.

(warning)

Protect your webhooks

Twilio supports HTTP Basic and Digest Authentication. This type of authentication protects your TwiML URLs on your web server with an Auth Token. This limits access to the URLs to you and Twilio. Protect your auth tokens as you would your passwords. To learn more, see HTTP authentication.

Create a public URL for your app

create-a-public-url-for-your-app page anchor

Most production systems have a public URL, but development systems might not. To permit Twilio to access your local dev app, use ngrok. To create a public URL for your app, run ngrok at the command line:

ngrok http 3000 --url https://<your-app-name>.ngrok.dev

This command creates a public URL https://<your-app-name>.ngrok.dev. that forwards HTTP requests to your web app listening on localhost:3000.

API output resembles the following:

Configure Twilio connection to your web app

configure-twilio-connection-to-your-web-app page anchor

With your public URL created, configure its connection to Twilio using a webhook.

Twilio ConsoleLegacy Console

If you use the new Twilio Console, follow these steps:

  1. Go to Numbers & senders(link takes you to an external page).
  2. Click your Twilio phone number you want for your app.
  3. Click the Configuration details tab.
  4. Click Messaging > Edit details.
  5. On the Edit messaging configuration dialog, select the Webhook, TwiML Bin, Function, Studio Flow, Proxy Service option.
  6. Under How do you want to set up your primary method?, select Webhook.
  7. Paste your ngrok public URL in the URL box.
    If your ngrok console shows Forwarding https://<your-app-name>.ngrok.dev, paste https://<your-app-name>.ngrok.dev to the URL box.

Use cases for incoming calls with Twilio Programmable Voice

use-cases-for-incoming-calls-with-twilio-programmable-voice page anchor

This guide teaches the basics required for the following use cases:

Create self-service automation with Twilio Programmable Voice

create-self-service-automation-with-twilio-programmable-voice page anchor

You can use this guide to intercept incoming customer calls and immediately present resolution paths. When Twilio triggers a webhook request to your server, you can return a structured TwiML script that handles inquiries without the intervention of human agents, like checking delivery statuses or updating user records.

To learn more advanced features that you can use with self-service automation, see Voice self-service automation.

Create an inbound contact center with Twilio Programmable Voice

create-an-inbound-contact-center-with-twilio-programmable-voice page anchor

You can use this guide as the fundamental entry point for routing and managing callers seeking live assistance. By responding to incoming call webhooks dynamically, your backend application can inspect customer details, query your CRM database, and use intelligent call distribution to pass the caller to the correct department queue.

To learn more advanced features that you can use with inbound contact centers, see Voice inbound contact center.


After following this guide, your web application can successfully listen for, receive, and respond to incoming webhooks triggered by inbound phone calls directed to your Twilio numbers. You can verify that your logic is operational by dialing your provisioned Twilio phone number from a mobile device and confirming that your server executes your specific TwiML voice commands.


Explore the following guides to build on what you've learned in this guide: