💬 WhatsApp API @ Best Rate | Zero Setup Fee → 99.9% Uptime OTP Delivery — Try FREE Demo! 🏆 10,000+ Registered Businesses — 2,000+ Enterprise Clients Served 🚀 API Integration in Under 5 Minutes 🏅 Verified Business Badge with RCS Messaging 💬 WhatsApp API @ Best Rate | Zero Setup Fee → 99.9% Uptime OTP Delivery — Try FREE Demo! 🏆 10,000+ Registered Businesses — 2,000+ Enterprise Clients Served 🚀 API Integration in Under 5 Minutes 🏅 Verified Business Badge with RCS Messaging
Talk to Sales: India 1800 102 1822
OTP

OTP SMS API in Python: Send and Verify OTP with Flask and Django

SMSGatewayHub 6 views
Quick answer

To use an OTP SMS API in Python, generate a 6-digit code with the secrets module, store only a hash of it with a 5-minute expiry, and send it with one requests.get() call to the SMSGatewayHub SendSMS endpoint with channel=OTP, your API key, DLT entity ID and OTP template ID. An ErrorCode of 000 means the OTP was accepted. Your Flask or Django app then verifies the code the user types against the stored hash. OTP SMS costs ₹0.185 to ₹0.245 per SMS + GST, with 2-6 second typical delivery.

Key takeaways

  • One send function: requests + secrets, a 10-second timeout and the JobId logged for every OTP.
  • Flask: two routes, /send-otp and /verify-otp, with the hashed code kept server-side.
  • Django: a cache-backed store (Redis or the default cache) with expiry, attempt counter and resend cooldown.
  • Verification is yours: the code never leaves your server; SMSGatewayHub only delivers it.
  • Rate limits matter: cap sends per number and per IP to stop SMS pumping and brute force.

If you only need the basic HTTP call, start with our PHP and Python HTTP API guide. This article goes further: a reusable Python send function, a complete Flask flow, a Django view backed by the cache, and the production details (timeouts, logging, limits) that keep a login screen working under real traffic.

What do you need before you call the OTP SMS API from Python?

Every OTP in India passes TRAI DLT scrubbing, so the request must carry your registered IDs. Get these ready first:

ItemWhere you get itRequest parameter
API keyYour SMSGatewayHub panel after sign-upAPIKey
DLT entity IDYour DLT portal (DLT registration)EntityId
Transactional sender ID (6 letters)Registered header on DLTsenderid
Approved OTP template IDDLT template approval (template process)dlttemplateid
Python packagespip install requests (+ Flask or Django)-

Keep the API key in an environment variable, never in source code or a front-end bundle.

How do you write a reusable OTP send function in Python?

This function generates nothing by itself. It sends whatever code your app passes in, so the same function serves sign-up, login and payment flows. The text must match your approved DLT template exactly, with only the variable part changing.

import os
import logging
import requests

log = logging.getLogger("otp")

SMS_URL = "https://www.smsgatewayhub.com/api/mt/SendSMS"
API_KEY = os.environ["SGH_API_KEY"]
SENDER_ID = os.environ.get("SGH_SENDER_ID", "ABCDEF")
ENTITY_ID = os.environ["SGH_ENTITY_ID"]
TEMPLATE_ID = os.environ["SGH_OTP_TEMPLATE_ID"]


def send_otp_sms(number: str, otp: str) -> dict:
    """Send one OTP. Returns the parsed JSON reply. Raises on network errors."""
    params = {
        "APIKey": API_KEY,
        "senderid": SENDER_ID,
        "channel": "OTP",
        "DCS": "0",
        "flashsms": "0",
        "number": number,               # e.g. 9198XXXXXXXX
        "text": f"{otp} is your OTP to log in to ABC App. Do not share it. - ABC",
        "route": "1",
        "EntityId": ENTITY_ID,
        "dlttemplateid": TEMPLATE_ID,
    }
    r = requests.get(SMS_URL, params=params, timeout=10)
    r.raise_for_status()
    data = r.json()
    if data.get("ErrorCode") == "000":
        log.info("otp accepted number=%s job=%s", number[-4:], data.get("JobId"))
    else:
        log.warning("otp rejected number=%s code=%s msg=%s",
                    number[-4:], data.get("ErrorCode"), data.get("ErrorMessage"))
    return data

A successful reply looks like this:

{ "ErrorCode": "000", "ErrorMessage": "Success", "JobId": "20047",
  "MessageData": [ { "Number": "9198XXXXXXXX", "MessageId": "..." } ] }

ErrorCode 000 means the OTP was accepted for delivery. Store the JobId: you match it with the delivery report later to decide whether to resend or switch channel. Full parameters and the Swagger reference are in the developer API docs, and the response fields are explained in our OTP REST API reference.

ℹ️
Log only the last four digits of the phone number and never log the OTP itself. Logs are read by more people than your database.

How do you build send and verify OTP routes in Flask?

The Flask version keeps the hashed code in a small server-side store. For a single process, a dictionary works for testing; in production use Redis so every worker sees the same codes. The example below uses Redis.

import hmac
import hashlib
import os
import secrets
import time

import redis
from flask import Flask, request, jsonify

from otp_sms import send_otp_sms   # the function above

app = Flask(__name__)
r = redis.Redis.from_url(os.environ.get("REDIS_URL", "redis://localhost:6379/0"))
PEPPER = os.environ["OTP_PEPPER"].encode()   # long random secret

OTP_TTL = 300        # 5 minutes
RESEND_GAP = 45      # seconds between sends
MAX_SENDS = 3        # per number per 15 minutes
MAX_TRIES = 5        # wrong codes before the code is burned


def h(number: str, otp: str) -> str:
    return hmac.new(PEPPER, f"{number}:{otp}".encode(), hashlib.sha256).hexdigest()


@app.post("/send-otp")
def send_otp():
    number = (request.json or {}).get("number", "")
    if not (number.isdigit() and len(number) == 12 and number.startswith("91")):
        return jsonify(ok=False, error="Enter a valid Indian mobile number"), 400
    if r.exists(f"otp:gap:{number}"):
        return jsonify(ok=False, error="Please wait before asking for a new code"), 429
    sends = r.incr(f"otp:sends:{number}")
    if sends == 1:
        r.expire(f"otp:sends:{number}", 900)
    if sends > MAX_SENDS:
        return jsonify(ok=False, error="Too many codes requested. Try again later"), 429

    otp = f"{secrets.randbelow(900000) + 100000}"
    r.setex(f"otp:hash:{number}", OTP_TTL, h(number, otp))
    r.delete(f"otp:tries:{number}")
    r.setex(f"otp:gap:{number}", RESEND_GAP, 1)

    data = send_otp_sms(number, otp)
    if data.get("ErrorCode") != "000":
        return jsonify(ok=False, error="Could not send the code. Try again"), 502
    return jsonify(ok=True, expires_in=OTP_TTL)


@app.post("/verify-otp")
def verify_otp():
    body = request.json or {}
    number, code = body.get("number", ""), body.get("otp", "")
    stored = r.get(f"otp:hash:{number}")
    if not stored:
        return jsonify(ok=False, error="Code expired. Request a new one"), 400
    tries = r.incr(f"otp:tries:{number}")
    if tries > MAX_TRIES:
        r.delete(f"otp:hash:{number}")
        return jsonify(ok=False, error="Too many wrong attempts"), 429
    if not hmac.compare_digest(stored.decode(), h(number, code)):
        return jsonify(ok=False, error="Wrong code"), 400
    r.delete(f"otp:hash:{number}", f"otp:tries:{number}")   # one use only
    # mark the user as verified / create the session here
    return jsonify(ok=True)

Three details make this safe. The code is stored as an HMAC with a secret pepper, so a database or Redis dump does not reveal live codes. hmac.compare_digest compares in constant time. And the code is deleted after one successful use or after five wrong attempts.

How do you send and verify OTP in Django with the cache framework?

Django already has a cache layer, so you do not need a new table. Point CACHES at Redis in production and the views below work across all workers.

# otp/views.py
import hmac, hashlib, json, secrets
from django.conf import settings
from django.core.cache import cache
from django.http import JsonResponse
from django.views.decorators.http import require_POST

from .sms import send_otp_sms

TTL, GAP, MAX_TRIES = 300, 45, 5


def _hash(number, otp):
    return hmac.new(settings.OTP_PEPPER.encode(), f"{number}:{otp}".encode(),
                    hashlib.sha256).hexdigest()


@require_POST
def send_otp(request):
    number = json.loads(request.body or "{}").get("number", "")
    if not (number.isdigit() and len(number) == 12):
        return JsonResponse({"ok": False, "error": "Invalid number"}, status=400)
    if not cache.add(f"otp:gap:{number}", 1, GAP):      # add() fails if key exists
        return JsonResponse({"ok": False, "error": "Wait before resending"}, status=429)
    otp = f"{secrets.randbelow(900000) + 100000}"
    cache.set(f"otp:{number}", {"h": _hash(number, otp), "t": 0}, TTL)
    data = send_otp_sms(number, otp)
    ok = data.get("ErrorCode") == "000"
    return JsonResponse({"ok": ok}, status=200 if ok else 502)


@require_POST
def verify_otp(request):
    body = json.loads(request.body or "{}")
    number, code = body.get("number", ""), body.get("otp", "")
    rec = cache.get(f"otp:{number}")
    if not rec:
        return JsonResponse({"ok": False, "error": "Code expired"}, status=400)
    rec["t"] += 1
    if rec["t"] > MAX_TRIES:
        cache.delete(f"otp:{number}")
        return JsonResponse({"ok": False, "error": "Too many attempts"}, status=429)
    if not hmac.compare_digest(rec["h"], _hash(number, code)):
        cache.set(f"otp:{number}", rec, TTL)
        return JsonResponse({"ok": False, "error": "Wrong code"}, status=400)
    cache.delete(f"otp:{number}")
    request.session["phone_verified"] = number
    return JsonResponse({"ok": True})

cache.add() only writes when the key is missing, which gives you a race-free resend cooldown in one line. Put OTP_PEPPER and the SMS credentials in environment variables loaded by settings.py.

Which production settings stop OTP failures and abuse?

SettingRecommended valueWhy
HTTP timeout10 secondsA hung request must not block a web worker.
Code length6 digitsOne million combinations; with 5 attempts brute force fails.
Code validity5 minutesLong enough for 2-6 second delivery plus typing.
Resend gap30-60 secondsStops double taps and pumping scripts.
Sends per number3 per 15 minutesCaps cost if a bot targets one number.
Sends per IP10 per hour (tune to your traffic)Stops one client spraying many numbers.
LoggingJobId + last 4 digitsLets you trace delivery without exposing data.

Do not retry the HTTP call in a loop when you get a non-000 reply: the platform already applies automatic retry with load balancing across operator routes. Retry only on a network error, once, and then show the user a resend button.

✔
Resend should mean a new code. Generate a fresh OTP and overwrite the stored hash every time. Re-sending the old code keeps a leaked code alive. The full resend and verify pattern is in our guide to the verify OTP and resend OTP flow.

Why choose SMSGatewayHub as your OTP SMS API for Python apps?

  • Simple REST over HTTPS: one GET request and a JSON reply, so requests is all you need.
  • Fast delivery: 2-6 seconds typical on priority transactional routes, with automatic retry and load balancing across operator routes.
  • Clear pricing: ₹0.185 to ₹0.245 per OTP SMS + 18% GST, DLT scrubbing included, and you pay only for delivered OTPs. See OTP SMS pricing.
  • Free DLT help: our team helps register your entity, sender ID and OTP templates.
  • Trusted platform: since 2009, 99.9% uptime SLA, ISO 27001 certified.
  • No-code option: OneTap Verify lets users log in with a tap instead of typing a code.
Get 1,000 free SMS credits and send your first OTP from Python today
No credit card. Free DLT registration help. Copy your API key from the panel and run the function above.
Create free account

What are the common errors when sending OTP from Python?

  1. Template mismatch. The message text differs from the approved DLT template by even one word or space, so the operator rejects it. Copy the template exactly and change only the code.
  2. Wrong number format. Send 91 followed by the 10-digit number, digits only.
  3. Promotional header. OTPs must go out under a transactional sender ID registered for the OTP template.
  4. Key in the browser. If a front-end calls the SMS API directly, anyone can read your key and spend your credits. Always call it from Python on the server.
  5. No timeout. requests.get() without timeout can wait forever and exhaust your workers.

Frequently asked questions

How do I send an OTP SMS from Python?

Generate a code with the secrets module, then call https://www.smsgatewayhub.com/api/mt/SendSMS with requests.get(), passing APIKey, senderid, channel=OTP, route=1, number, text, EntityId and dlttemplateid. An ErrorCode of 000 in the JSON reply means the OTP was accepted.

Does the OTP SMS API verify the code for me?

No. Your Python server generates the code, stores a hash with an expiry and checks what the user types. SMSGatewayHub delivers the SMS, so the code never leaves your system.

Should I use Flask or Django for OTP login?

Both work the same way. Flask needs a store such as Redis for the hashed codes; Django can use its built-in cache framework pointed at Redis. The SMS call is identical in both.

How much does an OTP SMS cost?

OTP SMS on SMSGatewayHub costs ₹0.185 to ₹0.245 per SMS plus 18% GST, depending on pack size. DLT scrubbing is included and you pay only for delivered OTPs.

How fast is OTP delivery?

Typical delivery is 2-6 seconds on priority transactional routes, with automatic retry and load balancing across operator routes. Keep the code valid for about 5 minutes.

Related reading: OTP SMS API, OTP REST API reference, OTP SMS API in PHP and Laravel, OTP SMS API with Node.js and React and testing your OTP API.

Sources: SMSGatewayHub OTP SMS API page and developer API documentation (November 2026); Python standard library documentation for secrets and hmac; Flask and Django documentation; TRAI Telecom Commercial Communications Customer Preference Regulations for DLT rules. Prices exclude 18% GST and can change; confirm your rate with sales before purchase.