Back to Blog
Language How-Tos

How to Send OTP Verification Codes in Twilio Using Python

Generate and send one-time password codes via Twilio SMS in Python with expiry logic, rate limiting, and verification endpoint setup.

DA
Danial A
Senior Twilio Consultant, Telphi Consulting
June 22, 2026
8 min read
Twilio
Python
How-To
Code
How to Send OTP Verification Codes in Twilio Using Python

This tutorial builds a custom one-time password system using Python and Twilio SMS that gives you full control over code generation, expiry, and verification logic. It targets developers who prefer to manage OTP state in their own database rather than delegating it entirely to the Twilio Verify API. You will generate cryptographically secure codes using Python's secrets module, store them with an expiry timestamp, send them via Twilio SMS, and verify user-submitted codes in a Flask endpoint.

Prerequisites and Setup

You need Python 3.7 or higher, Flask, and the Twilio SDK installed with pip install twilio flask python-dotenv. Configure your Twilio credentials in a .env file with your Account SID, Auth Token, and sending number. The OTP store in this tutorial uses an in-memory dictionary keyed by phone number; in production, replace it with a Redis store or a database table with a TTL index. Install python-dotenv to load environment variables from the .env file in development.

pip install twilio flask python-dotenv

# .env
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_PHONE_NUMBER=+15551234567

The Complete Code

Python's secrets.randbelow() generates a cryptographically secure integer that is zero-padded to six digits to avoid codes starting with zero from shortening. The OTP is stored alongside a creation timestamp and a failed-attempt counter, enabling both expiry and brute-force protection. The verify endpoint rejects codes older than five minutes using a timedelta comparison and increments the attempt counter on each wrong guess. Locking the entry after three failed attempts prevents an attacker from cycling through all million possible six-digit codes.

import os
import secrets
from datetime import datetime, timedelta, timezone
from flask import Flask, request, jsonify
from twilio.rest import Client
from twilio.base.exceptions import TwilioRestException
from dotenv import load_dotenv

load_dotenv()

app    = Flask(__name__)
client = Client(os.environ["TWILIO_ACCOUNT_SID"], os.environ["TWILIO_AUTH_TOKEN"])
FROM   = os.environ["TWILIO_PHONE_NUMBER"]

OTP_STORE: dict = {}
OTP_EXPIRY_MINUTES = 5
OTP_MAX_ATTEMPTS   = 3

def generate_otp() -> str:
    return str(secrets.randbelow(1_000_000)).zfill(6)

@app.route("/otp/send", methods=["POST"])
def send_otp():
    phone = request.json.get("phone", "")
    if not phone:
        return jsonify({"error": "phone is required"}), 400

    code = generate_otp()
    OTP_STORE[phone] = {
        "code":     code,
        "created":  datetime.now(timezone.utc),
        "attempts": 0,
    }

    try:
        client.messages.create(
            body=f"Your Telphi verification code is {code}. It expires in {OTP_EXPIRY_MINUTES} minutes.",
            from_=FROM,
            to=phone,
        )
        return jsonify({"message": "OTP sent"}), 200
    except TwilioRestException as e:
        return jsonify({"error": e.msg}), 500

@app.route("/otp/verify", methods=["POST"])
def verify_otp():
    phone = request.json.get("phone", "")
    code  = request.json.get("code", "")

    entry = OTP_STORE.get(phone)
    if not entry:
        return jsonify({"error": "No OTP requested for this number"}), 404

    if entry["attempts"] >= OTP_MAX_ATTEMPTS:
        return jsonify({"error": "Too many attempts. Request a new code."}), 429

    age = datetime.now(timezone.utc) - entry["created"]
    if age > timedelta(minutes=OTP_EXPIRY_MINUTES):
        del OTP_STORE[phone]
        return jsonify({"error": "Code expired. Request a new one."}), 410

    if code != entry["code"]:
        OTP_STORE[phone]["attempts"] += 1
        remaining = OTP_MAX_ATTEMPTS - OTP_STORE[phone]["attempts"]
        return jsonify({"error": f"Incorrect code. {remaining} attempt(s) remaining."}), 401

    del OTP_STORE[phone]
    return jsonify({"message": "Phone number verified successfully"}), 200

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

Testing and Debugging

POST to /otp/send with a JSON body containing your phone number and verify the SMS arrives within a few seconds. Then POST to /otp/verify with the correct code and confirm a 200 response is returned. Test the wrong-code path three times in a row to trigger the lockout and verify the 429 response fires after the third failed attempt. Wait six minutes after sending a code and verify the 410 expired response is returned when trying to use the old code.

Taking It Further

Replace the in-memory OTP_STORE dict with Redis using the redis-py library and set each key's TTL to match OTP_EXPIRY_MINUTES so expired entries are cleaned up automatically without your code needing to manage them. Add a per-phone rate limit that blocks new OTP requests if the same number has requested more than three codes in the past 15 minutes, preventing SMS flooding abuse. Log every OTP request and verification attempt (but never the code itself) to an audit table for security compliance. Consider using Twilio Verify instead of this custom implementation for built-in fraud monitoring and adaptive verification.

Contact Telphi Consulting to design a secure multi-factor authentication system for your web or mobile application.

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.