Back to Blog
Language How-Tos

How to Receive Incoming SMS with a Webhook in Twilio Using Python

Build a Flask webhook endpoint that receives inbound Twilio SMS, parses the request body, and responds with TwiML in Python.

DA
Danial A
Senior Twilio Consultant, Telphi Consulting
June 22, 2026
8 min read
Twilio
Python
How-To
Code
How to Receive Incoming SMS with a Webhook in Twilio Using Python

This tutorial builds a Flask webhook that Twilio calls every time your number receives an inbound SMS, parses the message fields, and returns a TwiML response. It targets developers building two-way SMS applications where your server must process messages users send to your Twilio number. You will expose a local Flask server via ngrok for testing and configure the Twilio Console to point inbound SMS at your endpoint.

Prerequisites and Setup

You need Python 3.7 or higher, Flask, the Twilio SDK, and ngrok installed and authenticated on your machine. Install the dependencies with pip install twilio flask python-dotenv. Download and install ngrok from the ngrok website, then run ngrok http 5000 to create a public HTTPS tunnel to your local Flask server. Copy the HTTPS forwarding URL that ngrok provides because you will paste it into the Twilio Console as your number's Messaging webhook URL.

pip install twilio flask python-dotenv

# Start ngrok in a separate terminal
ngrok http 5000
# Copy the https://xxxx.ngrok.io URL

The Complete Code

Flask handles the POST that Twilio sends when a message arrives, and the data is available in request.form as standard form fields. The Body field contains the message text, From is the sender's number, and To is your Twilio number. The route must return a valid TwiML XML response; returning an empty <Response /> tells Twilio you handled the message but do not want to reply. Use the MessagingResponse helper from the SDK to construct TwiML without building XML strings by hand.

import os
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse

app = Flask(__name__)

@app.route("/sms", methods=["POST"])
def incoming_sms():
    sender = request.form.get("From", "")
    body   = request.form.get("Body", "").strip()

    print(f"Message from {sender}: {body}")

    resp = MessagingResponse()
    resp.message(f"Got your message: '{body}'. We will reply soon.")
    return str(resp), 200, {"Content-Type": "text/xml"}

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

Testing and Debugging

Start the Flask server with python app.py, then open the Twilio Console, select your number, scroll to Messaging, and set the webhook URL to your ngrok URL followed by /sms. Send a text to your Twilio number from your personal phone and watch the Flask terminal print the sender and body. If Twilio reports a webhook delivery failure in the Console, check that your ngrok tunnel is still running and that the URL path matches your route exactly. Return a proper Content-Type: text/xml header or Twilio will log a warning about an unexpected response format.

Taking It Further

Validate the incoming request signature using RequestValidator from the Twilio SDK to ensure the POST truly came from Twilio and not a spoofed request. Store each inbound message in a database with the sender, body, and timestamp for auditing and analytics. Add keyword detection logic inside the route to branch responses based on what the user wrote, which is the foundation of an SMS bot. For production, deploy the Flask app to a platform with a stable HTTPS URL and remove the ngrok dependency.

Talk to Telphi Consulting about building production-ready inbound SMS handlers with signature validation and persistent message storage.

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.