Introduction: Python's Versatility in Communication Systems
Python is one of the most popular, versatile, and readable programming languages in the world. It is widely used for web development (with frameworks like Django, Flask, and FastAPI), automation scripting, data engineering, machine learning, and DevOps tooling. Regardless of what you are building, the ability to communicate with users directly on their mobile devices is a common operational necessity. Triggering text messages dynamically from Python code is essential for sending 2FA OTP codes, system alert monitoring notifications, or automated customer notifications.
Connecting your Python code to an external gateway is simple. By using Python's standard libraries or popular third-party modules, developers can implement SMS pipelines quickly. This guide provides a detailed SMS API Python Example, showing how to send messages using the standard requests library, design a reusable Object-Oriented Client class, implement high-performance asynchronous dispatches with httpx, and build a Flask webhook endpoint to handle real-time delivery reports.
Prerequisites: Getting Started
Before writing code, ensure you have gathered the following integration requirements:
- Python Environment: Python 3.7 or higher installed on your system.
- HTTP Libraries: Make sure you have installed the requests library (
pip install requests). For asynchronous examples, install httpx (pip install httpx). - Credentials: Sign up for an account on BlackSMS and get your secure API Key and Sender ID (Header) from the dashboard.
- DLT Details (India): If sending SMS messages to Indian users, obtain your 19-digit Principal Entity ID (PE ID) and template IDs.
Method 1: Synchronous SMS Sending using Python Requests
For quick automation scripts, desktop applications, or standard synchronous web requests, you can use Python's requests library. This example shows how to build the JSON payload, send it to the BlackSMS API endpoint, and handle the response.
import requests
import json
def send_sms():
api_url = "https://api.blacksms.in/v1/send"
api_key = "YOUR_SECURE_API_KEY"
# 1. Define Request Payload
payload = {
"api_key": api_key,
"sender_id": "BLKSMS",
"phone": "919876543210",
"message": "Dear User, 123456 is your security verification code for BlackSMS.",
"pe_id": "1201159123456789012", # 19-digit DLT Principal Entity ID
"template_id": "1207161712345678901" # Approved DLT Template ID
}
headers = {
"Content-Type": "application/json",
"Accept": "application/json"
}
try:
# 2. Trigger HTTP POST request
response = requests.post(api_url, data=json.dumps(payload), headers=headers, timeout=10)
response_data = response.json()
# 3. Check status codes and output responses
if response.status_code == 200 and response_data.get("status") == "success":
print(f"SMS Sent Successfully! Message ID: {response_data.get('message_id')}")
else:
error_msg = response_data.get("message", "Unknown API Error")
print(f"Failed to send SMS (HTTP {response.status_code}): {error_msg}")
except requests.exceptions.Timeout:
print("Error: The connection to the SMS gateway timed out.")
except requests.exceptions.RequestException as e:
print(f"Network Exception occurred: {e}")
if __name__ == "__main__":
send_sms()
Method 2: Object-Oriented Python Client Class
Wrapping API interactions inside a reusable, Object-Oriented class makes your codebase cleaner, highly modular, and easier to test. Here is a production-ready Python client class:
import requests
import re
class BlackSmsClient:
def __init__(self, api_key, sender_id, pe_id=None):
self.api_url = "https://api.blacksms.in/v1/send"
self.api_key = api_key
self.sender_id = sender_id
self.pe_id = pe_id
def send_sms(self, phone, message, template_id):
# Format phone number to clean non-numeric characters
clean_phone = re.sub(r'\D', '', phone)
if len(clean_phone) == 10:
clean_phone = "91" + clean_phone # Add India code by default
payload = {
"api_key": self.api_key,
"sender_id": self.sender_id,
"phone": clean_phone,
"message": message,
"template_id": template_id
}
if self.pe_id:
payload["pe_id"] = self.pe_id
headers = {
"Content-Type": "application/json",
"Accept": "application/json"
}
response = requests.post(self.api_url, json=payload, headers=headers, timeout=8)
if response.status_code != 200:
return {
"success": False,
"error": f"HTTP Error {response.status_code}",
"details": response.text
}
data = response.json()
if data.get("status") == "success":
return {
"success": True,
"message_id": data.get("message_id")
}
else:
return {
"success": False,
"error": data.get("message", "Unknown API Error")
}
# Usage Example:
client = BlackSmsClient(api_key="YOUR_API_KEY", sender_id="BLKSMS", pe_id="1201159123456789012")
result = client.send_sms("9876543210", "Dear User, 123456 is verification...", "1207161712345678901")
print(result)
Method 3: Asynchronous SMS Sending using HTTPX
If you are building fast, async applications using modern frameworks like FastAPI or Torando, synchronous HTTP calls (like requests) block your event loop, degrading performance. You should use an asynchronous HTTP client like httpx to handle concurrent message sending efficiently.
import httpx
import asyncio
async def send_async_sms(phone, message, template_id, pe_id):
api_url = "https://api.blacksms.in/v1/send"
payload = {
"api_key": "YOUR_SECURE_API_KEY",
"sender_id": "BLKSMS",
"phone": phone,
"message": message,
"template_id": template_id,
"pe_id": pe_id
}
async with httpx.AsyncClient() as client:
try:
response = await client.post(api_url, json=payload, timeout=8.0)
data = response.json()
if response.status_code == 200 and data.get("status") == "success":
print(f"Async Success! ID: {data.get('message_id')}")
else:
print(f"Async Failure: {data.get('message')}")
except httpx.RequestError as exc:
print(f"An error occurred while requesting {exc.request.url!r}: {exc}")
# Run async task
# asyncio.run(send_async_sms('919876543210', 'Dear User, 123456...', '1207161712345678901', '1201159123456789012'))
Setting Up a Webhook Endpoint in Flask to Receive DLRs
To capture status reports (DLR) pushed by the BlackSMS gateway, setup an endpoint in your Flask web application. The following script parses incoming status notifications and logs them:
from flask import Flask, request, jsonify
import logging
app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
@app.route('/webhooks/sms-delivery', methods=['POST'])
def handle_sms_webhook():
# Verify JSON data
if not request.is_json:
return jsonify({"error": "Request must be JSON"}), 400
data = request.get_json()
message_id = data.get("message_id")
status = data.get("status")
phone = data.get("phone")
delivered_at = data.get("delivered_at")
if not message_id or not status:
return jsonify({"error": "Missing required parameters"}), 400
logging.info(f"SMS Webhook - ID: {message_id} | Phone: {phone} | Status: {status} | Time: {delivered_at}")
# TODO: Update the message status in your application database
# Example: db.execute('UPDATE sms_logs SET status = %s WHERE message_id = %s', (status, message_id))
return jsonify({"status": "acknowledged"}), 200
if __name__ == '__main__':
app.run(port=5000)
Conclusion: Production-Ready Python SMS Integrations
Integrating SMS alerts into Python is straightforward, whether you're writing automation scripts or building complex web applications. By utilizing class wrappers, handling exception states, and adopting asynchronous HTTP modules for high-throughput scenarios, you can build reliable communication systems. BlackSMS provides low-latency REST APIs designed to support Python environments. Build your integration today and power up your application communications.