Python SMS API Integration Guide

Complete guide to integrate SMS API with Python applications. Django, Flask, and FastAPI examples with best practices.

Python SMS API Integration Guide

Learn how to integrate SMS functionality into your Python applications using our REST API. Compatible with Django, Flask, FastAPI, and other frameworks.

Prerequisites

  • Python 3.6 or higher
  • requests library
  • Valid API key from OnlineSMSService
  • Basic knowledge of Python and HTTP requests

Installation

pip install requests
# or for async support
pip install aiohttp

Basic Integration

Simple SMS Sending

import requests
import json

# SMS Gateway Integration for Python
class SMSGateway:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://api.onlinesmsservice.com"
    
    def send_sms(self, to, message, sender="OTPSMS"):
        url = f"{self.base_url}/send"
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }
        data = {
            "to": to,
            "message": message,
            "sender": sender,
            "type": "transactional"
        }
        
        response = requests.post(url, headers=headers, json=data)
        
        if response.status_code == 200:
            return response.json()
        else:
            raise Exception(f"Failed to send SMS: {response.text}")

# Usage example
sms = SMSGateway("your_api_key_here")
result = sms.send_sms("919876543210", "Your OTP is: 123456")
print(f"SMS sent! Message ID: {result['message_id']}")

Django Integration

# settings.py
SMS_API_KEY = 'your_api_key_here'

# utils/sms.py
from django.conf import settings
import requests

def send_otp(phone, otp):
    url = "https://api.onlinesmsservice.com/send"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {settings.SMS_API_KEY}"
    }
    data = {
        "to": phone,
        "message": f"Your OTP is: {otp}",
        "sender": "OTPSMS",
        "type": "transactional"
    }
    
    response = requests.post(url, headers=headers, json=data)
    return response.status_code == 200

# views.py
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
import random

@csrf_exempt
def send_otp(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        phone = data.get('phone')
        otp = random.randint(100000, 999999)
        
        if send_otp(phone, otp):
            return JsonResponse({'success': True, 'message': 'OTP sent'})
        else:
            return JsonResponse({'success': False, 'message': 'Failed to send OTP'})

Flask Integration

from flask import Flask, request, jsonify
import requests
import random

app = Flask(__name__)

SMS_API_KEY = 'your_api_key_here'

def send_sms(phone, message):
    url = "https://api.onlinesmsservice.com/send"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {SMS_API_KEY}"
    }
    data = {
        "to": phone,
        "message": message,
        "sender": "OTPSMS",
        "type": "transactional"
    }
    
    response = requests.post(url, headers=headers, json=data)
    return response.status_code == 200

@app.route('/send-otp', methods=['POST'])
def send_otp():
    data = request.get_json()
    phone = data.get('phone')
    otp = random.randint(100000, 999999)
    
    if send_sms(phone, f'Your OTP is: {otp}'):
        return jsonify({'success': True, 'message': 'OTP sent'})
    else:
        return jsonify({'success': False, 'message': 'Failed to send OTP'})

if __name__ == '__main__':
    app.run(debug=True)

Ready to Start Integrating SMS?

Get your API key and start sending SMS messages in minutes

Get API Key Try API Playground