Flask OTP verification with the Fast2SMS OTP widget (Python)

This guide adds Flask OTP verification to a Python web app with the Fast2SMS OTP widget. The kit gives you a /f2s-otp route that keeps your API key on the server and calls Fast2SMS Smart OTP, and a drop-in browser box for the number and the code. Visitors verify by SMS or WhatsApp, and your Flask view checks a signed token before it trusts the number.

Download the Python Flask OTP widget kit (zip)fast2sms-otp-widget-python-flask.zip · 48 KBDownload .zip

We tested this kit with Python 3.12.10 and Flask 3.1.3 against a mock copy of the Fast2SMS API, so no real SMS was sent: 47 of 47 browser and API checks and 7 of 7 unit tests passed.

Before you start

  • A Fast2SMS account with wallet balance, and an approved DLT OTP template (SMS) or WhatsApp Authentication/Utility template.
  • Python 3 with Flask 3. The OTP logic in f2s_otp_core.py uses only the standard library, so there is nothing else to install.

Set up Flask OTP verification

  1. Create a Smart OTP template and copy its OTP ID

    In the panel, open Smart OTP > OTP Template List and click Add OTP Template. On the SMS Channel tab, pick your DLT entity, sender and approved OTP template, then click the variable that should carry the code. For WhatsApp, use the WhatsApp Channel tab with an approved Authentication or Utility template. Tick SET FALLBACK TEMPLATE if you want the other channel as a backup, then click Assign OTP Template.

    Copy the 10-character OTP ID from the new card. It decides the channel, the template and the fallback for every code the widget sends.

    Add OTP Template window on the SMS Channel tab with entity, sender and DLT template chosen and Variable 1 selected
    Pick the entity, sender and DLT template, then the variable that carries the OTP.
  2. Copy your API key

    Under Utility in the left menu, click API Key. Click View (the panel first asks for an OTP sent to your registered mobile) and copy the Authorization Key. Check that API Access is switched on. This key will live only in your backend’s settings, never in a page or an app.

    API Key page with the masked Authorization Key, View and Reset buttons and the API Access switch turned on
    Copy the Authorization Key. API Access must be on.
  3. Install and fill in .env

    Unzip the kit, then run:

    pip install -r requirements.txt
    cp .env.example .env

    Set the three required values in .env. app.py reads the file at start; values already in the environment win.

    FAST2SMS_API_KEY=YOUR_API_KEY
    F2S_OTP_ID=YOUR_OTP_ID
    F2S_TOKEN_SECRET=at-least-32-random-characters
  4. Run the demo

    Run python app.py and open http://127.0.0.1:5000. You see a login box and a sign-up form that needs a verified number. If a setting is missing, the app exits and prints which one.

  5. Add the route and the widget to your own app

    Copy f2s_otp_core.py next to your app and add the endpoint, as in the kit’s app.py:

    import json, os
    from flask import make_response, request
    from f2s_otp_core import OtpEndpoint, load_config
    
    # app = your existing Flask(__name__) app
    otp =OtpEndpoint(load_config(os.environ))  # raises ConfigError if a required setting is missing
    
    @app.route("/f2s-otp", methods=["GET", "POST", "OPTIONS"])
    def f2s_otp():
        body = request.get_json(silent=True) if request.method == "POST" and request.is_json else None
        status, headers, out = otp.handle(
            request.method, dict(request.headers), body,
            ip=otp.client_ip(request.remote_addr, request.headers), host=request.host)
        resp = make_response("" if out is None else json.dumps(out), status)
        resp.headers.update(headers)
        return resp

    Put f2s-otp-widget.min.js in your static folder and add the widget to a template:

    <script src="{{ url_for('static', filename='f2s-otp-widget.min.js') }}" defer></script>
    <div data-f2s-otp data-endpoint="/f2s-otp"></div>
  6. Check the token in your view

    Add data-f2s-protect data-endpoint="/f2s-otp" to a form and the widget adds a hidden f2s_token after verification. Check it on the server:

    from flask import abort
    
    @app.post("/signup")
    def signup():
        v = otp.verify_token(request.form.get("f2s_token"), mobile=request.form.get("phone"))
        if v is None:
            abort(403)
        # v["mobile"] is the verified 10-digit number. A token works only once.
        ...

    For OTP login, look up the user by v["mobile"] and log them in here, never from the browser event alone.

OTP Report with total, delivered, read, failed, sent and pending counts and a table of recent SMS and WhatsApp OTPs
Delivery shows here, not in the widget.

Going live

  • Limits live in memory (MemoryStore), so each process has its own counters. Run one process, for example with waitress: waitress-serve --port=5000 app:app. With several processes or servers, pass a shared store with incr, get, set and delete: OtpEndpoint(config, store=...).
  • Behind nginx or a load balancer: set F2S_TRUST_PROXY=1 so the per-IP limit reads the real visitor IP. Only set it behind a proxy you control.
  • Do not use the Flask development server’s debug mode in production. The kit runs it with debug=False.
  • API Security: if it is on in your account, whitelist your server’s outgoing IP. See IP whitelisting.

Settings

Setting Required Default What it does
FAST2SMS_API_KEY Yes Your API key, the bare key (no Bearer)
F2S_OTP_ID Yes The 10-character OTP ID from the template card
F2S_TOKEN_SECRET Yes 32 or more random characters; signs tickets and tokens
F2S_OTP_IDS No More OTP IDs a page may pick with data-otp-id, comma separated
F2S_ALLOWED_ORIGINS No same site only Other sites whose pages may call this backend
F2S_RESEND_WAIT No 30 Seconds between sends to one number
F2S_LIMIT_PER_NUMBER No 5 Sends per number per hour
F2S_LIMIT_PER_IP No 20 Sends per IP address per hour
F2S_MAX_VERIFY No 5 Wrong codes allowed per code
F2S_TOKEN_TTL No 600 Seconds a verified token stays valid
F2S_OTP_EXPIRY / F2S_OTP_LENGTH No 15 min / 6 digits Code expiry (1 to 10080 minutes) and length (4 to 10)
F2S_CAPTCHA / F2S_CAPTCHA_SECRET No off turnstile or recaptcha, plus its secret key

Sending, resending and cost

Before every paid call, the route checks the page’s origin and the X-F2S-Widget header, then the resend wait and the per-IP and per-number limits. A new code for a number cancels the older one. “Code sent” means Fast2SMS accepted it; delivery shows in Delivery Report.

Resend sends the same code again, it does not make a new one. Fast2SMS allows it within 10 minutes of the first send, and up to 5 sends to one number in that time, counting the first.

Every send and every resend is charged at your Smart OTP rate, and a fallback message on the second channel is charged too. Verify is free. The Test OTP button on a template card is also a real, charged send. See the current rates on the OTP SMS page.

Sending in bulk? For high OTP volumes our team offers discounted rates. Talk to our team or see OTP pricing.

Common problems and fixes

What you see Why Fix
The app exits at start and lists settings A required setting is missing or wrong Set FAST2SMS_API_KEY, F2S_OTP_ID (10 characters) and F2S_TOKEN_SECRET (32 or more).
“We could not send the code right now.” An account or setup problem. Your server log names it: failed reason=... invalid_otp_id: copy the OTP ID again, from the same account as the key. insufficient_balance: recharge with Add Amount. template_inactive: create a new OTP template. Auth error: check the key, switch on API Access, or whitelist the server IP in API Security.
“This page is not allowed to use this OTP service.” The page is on another domain Add its origin (https:// plus the domain, no path) to F2S_ALLOWED_ORIGINS.
“Please wait N seconds…” The resend wait: the widget’s own, or Fast2SMS’s Wait. Change F2S_RESEND_WAIT, or SMS Resend / Time Limit in OTP Settings.
“Too many requests” The per-number or per-IP limit was hit Wait an hour, or raise F2S_LIMIT_PER_NUMBER / F2S_LIMIT_PER_IP.
The code never arrives Sent is not the same as delivered Check Smart OTP > Delivery Report, and use Test OTP on the template card.
Your form handler says “not verified” The token is missing, was used already, is older than 10 minutes, or is for another number Verify again. Check the token once, when the form is submitted.

Frequently asked questions

Does the Flask kit need any Python package besides Flask?

No. The OTP logic uses only the standard library, and requirements.txt lists just Flask.

Can I use the same code with FastAPI or another framework?

The core OtpEndpoint.handle() takes the method, headers, body, IP and host, so it can sit behind any framework. Only the Flask and Django glue is included and tested.

Is there a Django version?

Yes. The Django kit uses the same Python core as a reusable Django app.

I want a full OTP login page in Flask. Which kit?

Use the Flask OTP login starter kit. The widget adds a verify step to pages you already have.

Why did the visitor see a general error?

Account problems such as a wrong OTP ID or low balance show a neutral message to visitors. Your server log has the real reason, for example failed reason=insufficient_balance.

Is verify charged?

No. Each send and each resend is charged; verify is free.