Back to Blog
Language How-Tos

How to Receive an Inbound Call with TwiML in Twilio Using Python

Build a Python Flask webhook that handles inbound Twilio calls and responds with TwiML to play messages, gather input, or connect callers.

DA
Danial A
Senior Twilio Consultant, Telphi Consulting
June 22, 2026
8 min read
Twilio
Python
How-To
Code
How to Receive an Inbound Call with TwiML in Twilio Using Python

This tutorial builds a Flask webhook that Twilio calls whenever your phone number receives an inbound voice call, responding with TwiML instructions that control the caller's experience. It targets developers who need to program what happens when someone calls their Twilio number, from playing a greeting to routing the call. You will build a route that greets callers, collects a keypad digit, and branches based on their input.

Prerequisites and Setup

You need Python 3.7 or higher, Flask, and the Twilio SDK installed with pip install twilio flask. Expose your local server with ngrok using ngrok http 5000 and copy the HTTPS forwarding URL. In the Twilio Console, navigate to your phone number's configuration, scroll to the Voice section, and set the webhook URL for incoming calls to your ngrok URL followed by /answer. Make sure the HTTP method is set to POST, which is the default Twilio uses for voice webhooks.

pip install twilio flask

# Run ngrok in a separate terminal
ngrok http 5000
# Paste https://xxxx.ngrok.io/answer into Twilio Console voice webhook

The Complete Code

The Flask route returns TwiML XML that Twilio interprets in real time during the call. The Gather verb tells Twilio to play a prompt and collect DTMF digits from the caller's keypad, then POST them to an action URL. The action route reads the Digits field from the form POST and returns different TwiML based on the value. Returning a Dial verb connects the caller to another number, while Say reads a text message back to them.

from flask import Flask, request
from twilio.twiml.voice_response import VoiceResponse, Gather, Dial

app = Flask(__name__)

@app.route("/answer", methods=["POST"])
def answer():
    resp = VoiceResponse()
    gather = Gather(num_digits=1, action="/handle-key", method="POST")
    gather.say("Press 1 for sales, or press 2 for support.", voice="alice")
    resp.append(gather)
    resp.say("We did not receive your input. Goodbye.")
    return str(resp), 200, {"Content-Type": "text/xml"}

@app.route("/handle-key", methods=["POST"])
def handle_key():
    digit = request.form.get("Digits", "")
    resp = VoiceResponse()
    if digit == "1":
        resp.say("Connecting you to sales now.", voice="alice")
        dial = Dial()
        dial.number("+15559991111")
        resp.append(dial)
    elif digit == "2":
        resp.say("Connecting you to support now.", voice="alice")
        dial = Dial()
        dial.number("+15559992222")
        resp.append(dial)
    else:
        resp.say("Invalid option. Goodbye.")
        resp.hangup()
    return str(resp), 200, {"Content-Type": "text/xml"}

if __name__ == "__main__":
    app.run(port=5000, debug=True)

Testing and Debugging

Call your Twilio number and listen for the greeting to confirm Twilio is reaching your webhook. If the call connects but you hear nothing, check the ngrok terminal for the POST to /answer and verify Flask is returning a 200 with Content-Type: text/xml. If Twilio reports error 11200 in the Console, it means your webhook returned a non-2xx status or an invalid TwiML response. Use the Twilio Console Call Logs to see the full TwiML execution trace including which verbs ran and whether any errors occurred during call processing.

Taking It Further

Add a timeout attribute to the Gather verb to control how many seconds Twilio waits for input before falling through to the next TwiML instruction. Use input="speech" or input="dtmf speech" on the Gather verb to accept spoken words as well as keypad presses, enabling natural language call routing. Log every inbound call to a database with the caller's number, timestamp, and selected menu option for analytics and compliance. For complex call flows with many branches, split the TwiML logic across multiple Flask routes with a shared configuration dictionary for the menu structure.

Contact Telphi Consulting to design and implement custom inbound call handling systems for your business phone numbers.

Share this article:
0 views

Ready to Transform Your Business Communications?

Get a free consultation with our VoIP experts and discover how we can help you save costs, improve efficiency, and scale your business.

Comments (0)

Join the discussion and share your thoughts (AI-moderated for quality)

Protected by AI moderation

Be the first to comment

No comments yet. Share your thoughts below.