Send OTP without DLT in Python, with working code
To send OTP without DLT in Python, post the user's number to DiOTP's /v1/otp/send endpoint with the requests library, keep the request_id, then post it with the typed code to /v1/otp/verify. The codes go out on DiOTP's registered header and pre-approved template, so you need no DLT registration of your own. Below is a small client, error handling by code, safe retries and a Flask or Django login view.
By Vivek Singh, Founder, Diorbit TechnologiesUpdated
What do you need before you start?
This guide is for Python developers who want phone verification working today, before any DLT paperwork. DiOTP sends your codes under its own registered DLT entity, the DIORBT header and a pre-approved OTP template, which is how OTP without DLT works. You write the same code you would write for any OTP API, and it keeps working unchanged if you later add your own sender ID.
- Python 3.9 or newer and the requests library (pip install requests).
- A DiOTP account and an API key from the dashboard. A new account gets 10 free test messages, sent only to the mobile number you verified at sign-up.
- The key in an environment variable called DIOTP_API_KEY, set on the server that will make the calls.
Never print the API key, log it, commit it or send it to a browser or mobile app. Anyone who has it can spend your balance. The code below only ever reads it from the environment.
If you want every field and error code in one place, keep the OTP SMS API reference open in another tab while you work through this guide.
How do you send OTP without DLT in Python, step by step?
- Install requests with pip install requests, and set DIOTP_API_KEY in your environment (for example in your process manager or a .env file that is not committed).
- Copy the small client below into diotp_client.py. It wraps both calls and turns every error into an OtpError with a stable code.
- When a user asks for a code, call send_otp() with their number and store the returned request_id in their server-side session.
- When the user types the code, call verify_otp() with the stored request_id and the code. True means the number is verified.
- Map error codes to messages your users understand, and alert your team on account and setup errors.
- Test on your own verified number with the free test messages, then recharge your wallet to send to any Indian mobile number.
A small Python client for send and verify
The client is about fifty lines and has no dependency except requests. It sets a timeout on every call, so a slow network never hangs your worker, and it adds an Idempotency-Key to every send so a retry cannot text your user twice.
diotp_client.py
# diotp_client.py
import os
import uuid
import requests
API_BASE = "https://api-diotp.diorbit.com/v1"
class OtpError(Exception):
"""A DiOTP error. .code is the stable error code, .status the HTTP status."""
def __init__(self, status, code, message="", request_id=None):
super().__init__(f"{status} {code}: {message}")
self.status = status
self.code = code
self.request_id = request_id
def _headers(idempotency_key=None):
# Read the key from the environment. Never print it or log it.
headers = {"Authorization": f"Bearer {os.environ['DIOTP_API_KEY']}"}
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
return headers
def _post(path, body, idempotency_key=None):
res = requests.post(
f"{API_BASE}{path}",
headers=_headers(idempotency_key),
json=body,
timeout=10,
)
data = res.json() if res.content else {}
if not res.ok:
err = data.get("error", {})
raise OtpError(res.status_code, err.get("code", "unknown"), err.get("message", ""), err.get("request_id"))
return data
def send_otp(phone, purpose="login", channel="sms", idempotency_key=None):
"""Send a code. Returns the request_id to store with the user's session."""
body = {"to": phone, "country_code": 91, "channel": channel, "purpose": purpose}
data = _post("/otp/send", body, idempotency_key or str(uuid.uuid4()))
return data["request_id"]
def verify_otp(request_id, code):
"""Check the code the user typed. Returns True, or raises OtpError."""
data = _post("/otp/verify", {"request_id": request_id, "code": str(code)})
return data.get("verified") is TrueTwo details matter. First, the code is sent as a string, so a code that starts with zero keeps its leading zero. Second, the send returns only the request_id. DiOTP generates and stores the code itself; your server never sees it, which keeps it out of your logs, your database and your error reports.
For comparison, these are the raw calls the client makes. Each sample has a Python tab:
curl -X POST https://api-diotp.diorbit.com/v1/otp/send \ -H "Authorization: Bearer $DIOTP_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: 5f2b8c1e-signup-9876543210" \ -d '{ "to": "9876543210", "country_code": 91, "channel": "sms", "purpose": "signup" }'
const res = await fetch("https://api-diotp.diorbit.com/v1/otp/send", { method: "POST", headers: { Authorization: `Bearer ${process.env.DIOTP_API_KEY}`, "Content-Type": "application/json", "Idempotency-Key": crypto.randomUUID(), }, body: JSON.stringify({ to: "9876543210", country_code: 91, channel: "sms", purpose: "signup", }), }); const otp = await res.json(); // Keep otp.request_id: you need it to verify.
import os, uuid, requests res = requests.post( "https://api-diotp.diorbit.com/v1/otp/send", headers={ "Authorization": f"Bearer {os.environ['DIOTP_API_KEY']}", "Idempotency-Key": str(uuid.uuid4()), }, json={ "to": "9876543210", "country_code": 91, "channel": "sms", "purpose": "signup", }, timeout=10, ) otp = res.json() # Keep otp["request_id"]: you need it to verify.
<?php $ch = curl_init("https://api-diotp.diorbit.com/v1/otp/send"); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ "Authorization: Bearer " . getenv("DIOTP_API_KEY"), "Content-Type: application/json", "Idempotency-Key: " . bin2hex(random_bytes(16)), ], CURLOPT_POSTFIELDS => json_encode([ "to" => "9876543210", "country_code" => 91, "channel" => "sms", "purpose" => "signup", ]), ]); $otp = json_decode(curl_exec($ch), true); // Keep $otp["request_id"]: you need it to verify.
curl -X POST https://api-diotp.diorbit.com/v1/otp/verify \ -H "Authorization: Bearer $DIOTP_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "request_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7", "code": "482913" }'
const res = await fetch("https://api-diotp.diorbit.com/v1/otp/verify", { method: "POST", headers: { Authorization: `Bearer ${process.env.DIOTP_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ request_id: requestId, code: codeTheUserTyped }), }); if (res.ok) { // The number is verified: sign the user in. } else { const { error } = await res.json(); // e.g. error.code === "invalid_code" }
res = requests.post(
"https://api-diotp.diorbit.com/v1/otp/verify",
headers={"Authorization": f"Bearer {os.environ['DIOTP_API_KEY']}"},
json={"request_id": request_id, "code": code_the_user_typed},
timeout=10,
)
if res.ok:
pass # The number is verified: sign the user in.
else:
error = res.json()["error"] # e.g. error["code"] == "invalid_code"<?php $ch = curl_init("https://api-diotp.diorbit.com/v1/otp/verify"); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ "Authorization: Bearer " . getenv("DIOTP_API_KEY"), "Content-Type: application/json", ], CURLOPT_POSTFIELDS => json_encode([ "request_id" => $requestId, "code" => $codeTheUserTyped, ]), ]); $body = json_decode(curl_exec($ch), true); $verified = curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200;
How should you handle each error code?
Every error comes back in one envelope, {"error":{"code","message","request_id"}}, and the client raises it as an OtpError. Branch on e.code, never on the message text, which can change. The codes fall into three groups.
Errors your user should see
resend_cooldown (a code went to this number less than 30 seconds ago), phone_hourly_limit (three codes in the last hour), phone_daily_limit (ten in the last 24 hours), and on verify invalid_code, expired, not_pending and too_many_attempts. Show a short, friendly message and, for the verify errors except invalid_code, a button to send a new code.
Errors to retry
Only three: sending_unavailable (503), rate_limited and api_key_minute_limit. Retry them with backoff and the same Idempotency-Key. Retrying anything else cannot change the answer.
Errors for your team
unauthorized (401: the key is missing, wrong or revoked), trial_used_up and insufficient_balance (402), trial_restricted and account_suspended (403), channel_not_enabled, template_not_available and idempotency_key_reused. These mean something is wrong with your setup or account, not with what the user did. Log them at error level and alert someone.
errors.py
# What to tell the user, by error code. Everything else is for your logs.
USER_MESSAGES = {
"resend_cooldown": "Please wait 30 seconds before asking for a new code.",
"phone_hourly_limit": "Too many codes for this number. Please try again later.",
"phone_daily_limit": "Too many codes for this number today. Please try tomorrow.",
"invalid_code": "That code is not right. Please check and try again.",
"expired": "That code has expired. Please ask for a new one.",
"not_pending": "That code can no longer be used. Please ask for a new one.",
"too_many_attempts": "Too many wrong tries. Please ask for a new code.",
"invalid_request": "Please enter a valid 10 digit mobile number.",
}
# Problems with your setup or account, not the user's mistake: alert your team.
ALERT_TEAM = {"unauthorized", "trial_used_up", "insufficient_balance",
"trial_restricted", "account_suspended", "channel_not_enabled",
"template_not_available", "idempotency_key_reused"}
def user_message(err):
return USER_MESSAGES.get(err.code, "We could not send your code right now. Please try again.")The full list, with the HTTP status of each code, is in the error table of the API reference.
How do you retry safely with an Idempotency-Key?
A timeout leaves you unsure whether the code went out. The fix is to generate one Idempotency-Key per user action and reuse it on every retry of that action. If the first attempt succeeded, the API returns the original response: nothing new is sent, nothing is charged again and no limit is used. If it failed, the retry is a real new attempt.
retry.py
import time
import uuid
import requests
from diotp_client import OtpError, send_otp
RETRYABLE = {"sending_unavailable", "rate_limited", "api_key_minute_limit"}
def send_with_retry(phone, purpose="login", attempts=3):
key = str(uuid.uuid4()) # one key for this user action, reused on every retry
for n in range(attempts):
try:
return send_otp(phone, purpose=purpose, idempotency_key=key)
except OtpError as e:
if e.code not in RETRYABLE or n == attempts - 1:
raise
except (requests.Timeout, requests.ConnectionError):
if n == attempts - 1:
raise
time.sleep(2 ** n) # 1s, 2s, 4sKeep the number of attempts small. A user waiting on a login screen will not wait for long backoffs, and if DiOTP cannot send right now, three quick tries tell you that.
A Flask login view that sends and verifies OTP
Here is the whole flow as two Flask routes. The first sends a code and keeps the request_id in the signed session. The second verifies the code and marks the number as verified. The browser only ever talks to your routes, never to DiOTP, so the API key stays on your server.
app.py (Flask)
# app.py (pip install flask requests)
import logging
import os
from flask import Flask, jsonify, request, session
from diotp_client import OtpError, verify_otp
from errors import ALERT_TEAM, user_message
from retry import send_with_retry
app = Flask(__name__)
app.secret_key = os.environ["FLASK_SECRET_KEY"]
log = logging.getLogger("otp")
@app.post("/auth/otp/start")
def start():
phone = "".join(c for c in request.json.get("phone", "") if c.isdigit())[-10:]
try:
session["otp_request_id"] = send_with_retry(phone, purpose="login")
session["otp_phone"] = phone
return jsonify(ok=True)
except OtpError as e:
# Log the code and DiOTP's request_id, never the API key.
level = logging.ERROR if e.code in ALERT_TEAM else logging.INFO
log.log(level, "otp send failed: %s %s %s", e.status, e.code, e.request_id)
return jsonify(ok=False, error=e.code, message=user_message(e)), 400
@app.post("/auth/otp/check")
def check():
request_id = session.get("otp_request_id")
if not request_id:
return jsonify(ok=False, error="no_code", message="Please ask for a code first."), 400
try:
verify_otp(request_id, request.json.get("code", ""))
except OtpError as e:
if e.code == "already_verified":
pass # the number was confirmed earlier; treat it as verified
else:
return jsonify(ok=False, error=e.code, message=user_message(e)), 400
session.pop("otp_request_id", None)
session["verified_phone"] = session.pop("otp_phone")
return jsonify(ok=True)Note what is logged: the HTTP status, the error code and DiOTP's request_id, which is what support needs. Not the key, not the phone number in full and not the code. If you treat already_verified as success, a double tap on the submit button does not show your user an error.
The same flow in Django
views.py (Django)
# views.py (Django: the same flow as two function views)
import json
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from diotp_client import OtpError, verify_otp
from errors import user_message
from retry import send_with_retry
@require_POST
def otp_start(request):
phone = "".join(c for c in json.loads(request.body).get("phone", "") if c.isdigit())[-10:]
try:
request.session["otp_request_id"] = send_with_retry(phone)
except OtpError as e:
return JsonResponse({"ok": False, "error": e.code, "message": user_message(e)}, status=400)
return JsonResponse({"ok": True})
@require_POST
def otp_check(request):
try:
verify_otp(request.session.get("otp_request_id", ""), json.loads(request.body).get("code", ""))
except OtpError as e:
if e.code != "already_verified":
return JsonResponse({"ok": False, "error": e.code, "message": user_message(e)}, status=400)
request.session.pop("otp_request_id", None)
return JsonResponse({"ok": True})In Django, keep the request_id in request.session as shown, and add CSRF protection the way your project already does for JSON endpoints. For a complete Django build with forms, login(), a per-IP limit, Retry-After on every 429 and tests, read OTP verification in Django.
How do you test it, and then go live?
A new account is in test mode. The 10 free test messages are real SMS on the real network, sent only to the number you verified at sign-up. Run through the flow on your own phone and check four things: the code arrives with your company name in the message, verify returns True, a wrong code raises invalid_code, and a second send less than 30 seconds later raises resend_cooldown.
A send to any other number raises trial_restricted (403), and when the test messages run out you get trial_used_up (402). Recharge your prepaid wallet to go live; the same key then sends to any Indian mobile number at ₹0.26 to ₹0.40 per OTP plus 18% GST. Codes blocked by a rate limit are not sent or charged.
Building in another language? The PHP OTP guide and the Node.js OTP verification guide cover the same flow, and the OTP code generator writes the send and verify calls for cURL, PHP, Node.js or Python with your own settings.
Questions and answers
Do I need DLT registration to send OTP from Python?
Not with DiOTP. Your codes are sent under DiOTP's registered DLT entity, the DIORBT header and a pre-approved OTP template. You only need an account and an API key.
Where should I keep the DiOTP API key in a Python app?
In an environment variable called DIOTP_API_KEY on your server, read with os.environ. Never hard-code it, print it, log it or send it to a browser or app.
Which errors should my Python code retry?
Only sending_unavailable, rate_limited and api_key_minute_limit, with backoff and the same Idempotency-Key. Every other error gives the same answer on a retry.
Can I generate the OTP myself in Python and send it?
There is no need. DiOTP generates, stores, expires and checks the code for you. Your server keeps only the request_id, so the code never reaches your logs or database.
Does this work with Django, FastAPI or other frameworks?
Yes. The client uses only requests, so it works in any Python web framework. The pattern is the same: one view sends and stores the request_id, another verifies.
Will my Python code change when I get my own sender ID?
No. You add your entity ID, header and template ID under Sender IDs in the dashboard. The send and verify calls stay exactly the same.
