Transactional SMS in
Python & Django
Integrate NepalOTP into your Python backend to programmatically dispatch system alerts, order updates, and critical notifications reliably using Celery and Requests.
import requests from django.conf import settings def send_sms_alert(phone: str, message: str) -> dict: payload = {'phone': phone, 'message': message} headers = {'Authorization': f'Bearer {settings.NEPALOTP_API_KEY}'} response = requests.post( 'https://nepalotp.com/api/v1/sms/send', json=payload, headers=headers, timeout=5 ) return response.json()
Whether you are using a full-stack framework like Django, a micro-framework like FastAPI, or writing a simple background worker script, communicating with NepalOTP via Python is highly ergonomic. Our infrastructure utilizes standard REST architecture and accepts clean JSON payloads.
In this advanced guide, we will cover how to send transactional SMS alerts. Crucially, we will implement this using asynchronous task queues (Celery) so that network requests to the telecom API never block your main Django web thread.
Initial Setup
Python's industry-standard requests library is required to interact with the API. Install it via pip:
pip install requests celery redis
Add your API credentials securely to your Django settings.py file, pulling from your environment variables:
import os NEPALOTP_API_KEY = os.environ.get('NEPALOTP_API_KEY', '') NEPALOTP_BASE_URL = 'https://nepalotp.com/api/v1'
Building the Helper Service
Create a dedicated helper module services.py inside your Django app directory to handle API communication:
import requests from django.conf import settings class NepalOTPClient: def __init__(self): self.api_key = settings.NEPALOTP_API_KEY self.base_url = settings.NEPALOTP_BASE_URL self.headers = { 'Authorization': f'Bearer {self.api_key}', 'Content-Type': 'application/json' } def send_sms(self, phone: str, message: str) -> dict: payload = {'phone': phone, 'message': message} response = requests.post( f'{self.base_url}/sms/send', json=payload, headers=self.headers, timeout=5 ) response.raise_for_status() return response.json()
Asynchronous Background Queue (Celery)
Never execute synchronous network requests inside a Django HTTP request-response cycle. Wrap the SMS dispatch inside a Celery task:
from celery import shared_task from .services import NepalOTPClient @shared_task(bind=True, max_retries=3) def send_async_sms(self, phone: str, message: str): try: client = NepalOTPClient() return client.send_sms(phone, message) except Exception as exc: # Retry task automatically with exponential backoff raise self.retry(exc=exc, countdown=5)
Ship Python SMS in 5 mins
Claim your free developer key with 100 test credits. No credit card required.
Get API Key →Start verifying users today.
Get your API key in minutes. Test in sandbox. Ship when you're ready.