Send SMS and OTP codes from Python
Send SMS from Python with requests, and send and check one-time codes securely.
This guide sends SMS from a Python application with Fortwave, and uses it to send one-time passwords (OTP). It works the same in Django, Flask, FastAPI or a plain script.
What you need
- An API key.
- An approved sender ID and SMS credits. Until your company is approved, use test mode with the sender
MiraiTestand your verified test number. - Python 3.9 or later and the
requestslibrary.
pip install requestsSet your key
Read the key and sender ID from the environment. Never put the key in code you commit.
FORTWAVE_API_KEY=your-api-key
FORTWAVE_SENDER=MyAppSend an SMS
POST /v1/sms sends one message: phone_number with + and the country code, your approved sender ID (up to 11 letters and digits), and a message of up to 600 characters.
# fortwave.py
import os
import requests
FORTWAVE_SMS_URL = "https://rest.api.fortwave.io/v1/sms"
def send_sms(phone_number: str, message: str) -> dict:
"""Send one SMS and return Fortwave's response with the message id and credits."""
response = requests.post(
FORTWAVE_SMS_URL,
headers={
"Authorization": f"Bearer {os.environ['FORTWAVE_API_KEY']}",
"Accept": "application/json",
},
json={
"phone_number": phone_number,
"sender": os.environ["FORTWAVE_SENDER"],
"message": message,
},
timeout=10,
)
if not response.ok:
raise RuntimeError(f"Fortwave {response.status_code}: {response.json().get('message')}")
return response.json()A successful call returns the message's id, which delivery webhooks use too, with the credits it used (item_count) and the credits left (remaining_items):
{
"id": "01JCX4Q8V6M2R7T9K3N5P1W0YZ",
"item_count": 1,
"remaining_items": 4999,
"status": "queued",
"to": "+25761000000",
"sender": "MyApp",
"message": "Message queued for sending"
}Send and check OTP codes
Your application generates the code; Fortwave delivers it, in under a second on average in Burundi. secrets is Python's cryptographically secure generator, only a hash of the code is stored, and hmac.compare_digest compares it without leaking timing. store is any key-value store you already use, such as Redis, Django's cache or a database table.
# otp.py
import hashlib
import hmac
import secrets
import time
from fortwave import send_sms
TEN_MINUTES = 10 * 60
def _hash(code: str) -> str:
return hashlib.sha256(code.encode()).hexdigest()
def send_otp(store, user_id: str, phone_number: str) -> None:
"""Generate a code, keep only its hash, and send it by SMS."""
code = f"{secrets.randbelow(1_000_000):06d}"
store.set(f"otp:{user_id}", {"hash": _hash(code), "expires_at": time.time() + TEN_MINUTES})
send_sms(phone_number, f"Your verification code is {code}. It expires in 10 minutes.")
def verify_otp(store, user_id: str, code: str) -> bool:
"""True once, for the right code before it expires."""
entry = store.get(f"otp:{user_id}")
if entry is None or entry["expires_at"] < time.time():
return False
matches = hmac.compare_digest(entry["hash"], _hash(code))
if matches:
store.delete(f"otp:{user_id}")
return matchesHandle errors
- 401: the API key is missing, mistyped or revoked.
- 400: the request cannot be sent, for example insufficient credits or a sender ID that is not approved.
messageexplains why. - 422: a field is invalid, such as a phone number for the wrong country.
errorslists each field. - 429: more than 500 sends in a minute from one key. Retry after a short wait.
Next steps
- Know when each message is sent or fails with delivery webhooks.
- Send to up to 500 recipients per request with the bulk and template endpoints in the SMS API reference.
Still need help?
Our team answers Monday to Friday, during business hours (CAT).