CODE WITH SIBIN

Solving Real Problems with Real Code


Sending SMS with Django and Azure Communication Services

This comprehensive guide will walk you through setting up SMS functionality in your Django application using Azure Communication Services.

Step 1: Set Up Azure Communication Services

  1. Create Azure Communication Services resource
  2. Get a phone number with SMS capability
  3. Note your connection string and phone number

Step 2: Django Project Setup

# Create project and app
django-admin startproject sms_api
cd sms_api
python manage.py startapp sms

Step 3: Install Required Packages

pip install azure-communication-sms django-rest-framework python-dotenv

Step 4: Configuration

  1. Create .env file:
AZURE_CONNECTION_STRING=your_connection_string
AZURE_PHONE_NUMBER=+1234567890
  1. Update sms_api/settings.py:
from dotenv import load_dotenv
load_dotenv()

INSTALLED_APPS = [
    ...
    'rest_framework',
    'sms',
]

AZURE_COMMUNICATION = {
    'CONNECTION_STRING': os.getenv('AZURE_CONNECTION_STRING'),
    'PHONE_NUMBER': os.getenv('AZURE_PHONE_NUMBER')
}

Step 5: Create SMS Service Layer

sms/services.py:

from azure.communication.sms import SmsClient
from django.conf import settings

class SMSService:
    @staticmethod
    def send_sms(recipient, message):
        try:
            sms_client = SmsClient.from_connection_string(
                settings.AZURE_COMMUNICATION['CONNECTION_STRING']
            )
            
            response = sms_client.send(
                from_=settings.AZURE_COMMUNICATION['PHONE_NUMBER'],
                to=[recipient],
                message=message
            )
            
            results = []
            for result in response:
                results.append({
                    'successful': result.successful,
                    'message_id': result.message_id,
                    'error_details': result.error_details if not result.successful else None
                })
            
            return {
                'status': 'success',
                'results': results
            }
        except Exception as e:
            return {
                'status': 'error',
                'message': str(e)
            }

Step 6: Create API Views

sms/views.py:

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .services import SMSService

class SendSMSAPIView(APIView):
    def post(self, request):
        recipient = request.data.get('recipient')
        message = request.data.get('message')
        
        if not recipient or not message:
            return Response(
                {'error': 'Both recipient and message are required'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        result = SMSService.send_sms(recipient, message)
        
        if result['status'] == 'error':
            return Response(
                {'error': result['message']},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
        
        return Response(result, status=status.HTTP_200_OK)

Step 7: Configure URLs

sms_api/urls.py:

from django.contrib import admin
from django.urls import path
from sms.views import SendSMSAPIView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/sms/', SendSMSAPIView.as_view(), name='send-sms'),
]

Step 8: Test with Postman

  1. Request Setup:
    • Method: POST
    • URL: http://localhost:8000/api/sms/
    • Headers:
      • Content-Type: application/json
  2. Request Body (raw JSON):
{
    "recipient": "+1234567890",
    "message": "Test message from Django Azure SMS"
}
  1. Successful Response:
{
    "status": "success",
    "results": [
        {
            "successful": true,
            "message_id": "outbound/202402...",
            "error_details": null
        }
    ]
}
  1. Error Responses:
    • Missing parameters (400):
    { "error": "Both recipient and message are required" }
    • SMS send failure (500):
    { "error": "Exception details..." }

Step 9: Add API Documentation (Optional)

Add Swagger/OpenAPI support with drf-yasg:

  1. Install:
pip install drf-yasg
  1. Update urls.py:
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
    openapi.Info(
        title="SMS API",
        default_version='v1',
        description="API for sending SMS via Azure Communication Services",
    ),
    public=True,
    permission_classes=[permissions.AllowAny],
)

urlpatterns = [
    # ... existing paths ...
    path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
]

Step 10: Add Authentication (Recommended)

For production, add token authentication:

  1. Install:
pip install djangorestframework-simplejwt
  1. Update settings.py:
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
}
  1. Update views.py:
from rest_framework.permissions import IsAuthenticated

class SendSMSAPIView(APIView):
    permission_classes = [IsAuthenticated]
    # ... rest of the view ...
  1. Get token (Postman):
    • POST to /api/token/ with username and password
    • Use returned token in Authorization header as Bearer <token>

Step 11: Rate Limiting (Recommended)

Add throttling to prevent abuse:

settings.py:

REST_FRAMEWORK = {
    # ... existing settings ...
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '5/day',
        'user': '100/day'
    }
}

Complete Postman Testing Workflow

  1. Start Django server:
python manage.py runserver
  1. In Postman:
    • Create new collection "Azure SMS API"
    • Add POST request to http://localhost:8000/api/sms/
    • Set headers:
      • Content-Type: application/json
      • (If using auth) Authorization: Bearer <your_token>
    • Set raw JSON body with recipient and message
    • Send and verify response
  2. Test scenarios:
    • Happy path (valid request)
    • Missing parameters
    • Invalid phone number
    • Long message (Azure has 2048 char limit)
    • Unauthorized access (if auth enabled)

This implementation gives you a clean, production-ready REST API for sending SMS via Azure Communication Services that can be easily tested with Postman.

Leave a Reply

Your email address will not be published. Required fields are marked *