Developer Guide

Python SMS Gateway Integration

No SDK needed: the API is plain HTTPS + JSON, so the requests library is all you install. Tested examples for scripts, bulk sending, Django, Flask and async code.

🐍

Just requests

pip install requests is the only install. There is no SDK: you POST JSON over HTTPS with your API key in the Authorization header.

🔄

Async Ready

Use httpx.AsyncClient in FastAPI or any other asyncio code.

🧩

Any Framework

Copy-ready views for Django and Flask below. Nothing to add to INSTALLED_APPS.

Quick Start

Install & Send Your First SMS

Get a free API key + 100 test SMS: create an account and create a key under API & Integrations → API Management. Verified businesses also get 100 free SMS to test with. You also need an approved DLT sender ID and template; replace ACMEIN and the message below with yours.

Terminal
pip install requests
export SMS_API_KEY="your-api-key"
Python — sms.py
# sms.py: a small helper around the REST API. No SDK needed: requests + JSON.
import os
import requests

API_URL = "https://whitelabled.securesmsc.com/api/v2"
API_KEY = os.environ["SMS_API_KEY"]
HEADERS = {"Authorization": f"Bearer {API_KEY}", "Accept": "application/json"}


class SMSError(Exception):
    def __init__(self, status, result):
        self.status = status
        # Most specific first: error_code (e.g. TEMPLATE_MISMATCH), then error, then message
        self.code = result.get("error_code") or result.get("error")
        self.errors = result.get("errors") or []
        self.retry_after = result.get("retry_after")
        super().__init__(f"HTTP {status}, {self.code}: {result.get('message')}")


def _post(path, payload):
    resp = requests.post(f"{API_URL}{path}", headers=HEADERS, json=payload, timeout=30)
    try:
        result = resp.json()
    except ValueError:
        result = {"message": resp.text[:200]}
    if resp.status_code != 200 or not result.get("success"):
        raise SMSError(resp.status_code, result)
    return result["data"]


def send_sms(recipient, message, sender_id="ACMEIN", route="transactional"):
    """One number. Returns {"message_id", "queue_id", "status", "estimated_delivery"}."""
    return _post("/sms/send", {"sender_id": sender_id, "recipient": recipient,
                               "message": message, "route": route})


def send_bulk(recipients, message, sender_id="ACMEIN", route="transactional"):
    """1 to 1,000 numbers. Returns counts and one result per number."""
    return _post("/sms/send-bulk", {"sender_id": sender_id, "recipients": recipients,
                                    "message": message, "route": route})


if __name__ == "__main__":
    try:
        data = send_sms("9876543210", "Your OTP for login is 482913. It is valid for 10 minutes. -Acme")
        print(f"Message ID: {data['message_id']}")
        print(f"Status:     {data['status']}")  # "queued"
    except SMSError as err:
        print("Not sent:", err)

Base URL https://whitelabled.securesmsc.com/api/v2, header Authorization: Bearer YOUR_API_KEY, JSON fields sender_id, recipient and message. A queued SMS returns HTTP 200 with "success": true and a message_id. Every endpoint is in the API documentation.

Before the first call: each API key is locked to the first IP address that uses it; calls from any other IP then get HTTP 403 "IP address not allowed". Add your server IPs (or an IPv4 CIDR range) under API & Integrations → API Management → IP Whitelisting first, and use a separate key per server or integration. GET calls (balance, status) are off for new keys until you tick "Allow GET Method".

Bulk Sending

Send Bulk SMS

The same text to 1 to 1,000 numbers in one request. Your balance must cover every number: if it doesn't, nothing is sent, but the reply is still HTTP 200 with every result marked failed, so check each result.

Python — bulk_send.py
# bulk_send.py: one request for up to 1,000 numbers
from sms import send_bulk, SMSError

phones = ["9876543210", "9876543211", "9876543212"]

try:
    data = send_bulk(phones, "Dear customer, our office is closed on 14 Nov for Diwali. -Acme")
except SMSError as err:
    print("Bulk send failed:", err)
else:
    print(f"Queued: {data['successful']}/{data['total_recipients']}")
    # If the balance is short, every number fails but success is still true: check each result
    for r in data["results"]:
        if r["status"] == "failed":
            print(f"  Failed: {r['recipient']} — {r['error']}")
Django

Django Integration

Save the helper above as sms.py in your project and call it from a view. Set SMS_API_KEY in the server environment, not in settings.py.

Python — views.py
# views.py
import json
import logging
import secrets
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from sms import send_sms, SMSError   # the helper above, saved in your project

logger = logging.getLogger(__name__)

@require_POST
def send_otp(request):
    phone = json.loads(request.body)["phone"]
    otp = secrets.randbelow(900000) + 100000
    # Save a hash of the OTP with an expiry time (session or database) before sending
    try:
        data = send_sms(phone, f"Your OTP for login is {otp}. It is valid for 10 minutes. -Acme")
    except SMSError as err:
        logger.warning("OTP SMS failed: %s", err)
        return JsonResponse({"success": False, "message": "Could not send OTP"}, status=502)
    return JsonResponse({"success": True, "message_id": data["message_id"]})
Flask

Flask Integration

Python — app.py
# app.py
import secrets
from flask import Flask, request, jsonify
from sms import send_sms, SMSError   # the helper above

app = Flask(__name__)

@app.route("/api/send-otp", methods=["POST"])
def send_otp():
    phone = request.get_json()["phone"]
    otp = secrets.randbelow(900000) + 100000
    # Save a hash of the OTP with an expiry time before sending
    try:
        data = send_sms(phone, f"Your OTP for login is {otp}. It is valid for 10 minutes. -Acme")
    except SMSError as err:
        app.logger.warning("OTP SMS failed: %s", err)
        return jsonify(success=False, message="Could not send OTP"), 502
    return jsonify(success=True, message_id=data["message_id"])
Async

Async / FastAPI Support

For async code, such as FastAPI endpoints, use httpx.AsyncClient (pip install httpx). Keep concurrency below your key's rate limit: 60 requests a minute and 10,000 a day by default.

Python — async_example.py
# async_example.py: pip install httpx
import asyncio
import os
import httpx

API_URL = "https://whitelabled.securesmsc.com/api/v2"
HEADERS = {"Authorization": f"Bearer {os.environ['SMS_API_KEY']}", "Accept": "application/json"}

async def send_sms(client, recipient, message, sender_id="ACMEIN"):
    resp = await client.post(f"{API_URL}/sms/send", headers=HEADERS,
                             json={"sender_id": sender_id, "recipient": recipient, "message": message})
    result = resp.json()
    if resp.status_code == 200 and result.get("success"):
        return recipient, result["data"]["status"]
    # Most specific first: error_code, then error, then message
    reason = result.get("error_code") or result.get("error")
    return recipient, f"failed (HTTP {resp.status_code}, {reason}: {result.get('message')})"

async def main():
    async with httpx.AsyncClient(timeout=30) as client:
        # Different text per person, sent concurrently. Same text to many numbers? Use send-bulk.
        tasks = [
            send_sms(client, "9876543210", "Your OTP for login is 482913. It is valid for 10 minutes. -Acme"),
            send_sms(client, "9876543211", "Your OTP for login is 730125. It is valid for 10 minutes. -Acme"),
        ]
        for recipient, status in await asyncio.gather(*tasks):
            print(f"{recipient} → {status}")

asyncio.run(main())
Reference

Error Handling & Response Codes

Errors come back as JSON with "success": false. Read error_code (when present), then error, then message; the SMSError class in the helper does this for you.

Python — Error Handling
from sms import send_sms, SMSError

try:
    data = send_sms("9876543210", "Your OTP for login is 482913. It is valid for 10 minutes. -Acme")
    print("Queued:", data["message_id"])
except SMSError as err:
    if err.status == 401:
        print("Missing, wrong, disabled or expired API key: check SMS_API_KEY")
    elif err.status == 403:
        print("This server's IP is not on the key's IP whitelist (or GET is not allowed):", err)
    elif err.code == "TEMPLATE_MISMATCH":
        print("The text doesn't match an approved DLT template")
    elif err.status == 422:
        print("Bad request:", err.errors)
    elif err.status == 429:
        print(f"Rate limited: retry after {err.retry_after}s")
    elif err.status == 400:
        print("Not sent:", err, err.errors)   # e.g. unapproved sender ID, insufficient credits
    else:
        print("Not sent:", err)
HTTP CodeerrorAction
200—Message queued. For bulk sends, check each result.
400Invalid sender ID / SMS dispatch failedUse an approved sender ID. For dispatch failures, errors gives the reason, e.g. insufficient credits.
401UnauthorizedCheck the API key (missing, wrong, disabled or expired).
403ForbiddenAdd this server's IP under IP Whitelisting, or tick "Allow GET Method" for GET calls.
422Validation failed / Template Verification FailedFix the fields in errors, or match the text to an approved template (TEMPLATE_MISMATCH).
429Rate limit exceededWait retry_after seconds, then retry.
500Internal server errorRetry after a short wait.

Start Sending SMS from Python

There is no sandbox: every call sends a real SMS, so test with your own number. Read every endpoint in the API documentation, or check the per-SMS price.