How to Send SMS with Azure Communication Services Using Python Flask - Step-by-Step Guide

Explanation of the Sequence Diagram:

  1. User: The user interacts with Postman to test the API by sending an HTTP request.
  2. Postman: Postman sends the HTTP POST request to the Flask application’s /send-sms endpoint.
  3. FlaskApp: The Flask application receives the request and forwards it to Azure Communication Services (ACS) to send the SMS.
  4. ACS: Azure Communication Services processes the request and sends the SMS to the Recipient.
  5. Recipient: The recipient receives the SMS sent via ACS.

In this guide, we'll walk you through the process of sending SMS messages using Azure Communication Services and a Python Flask application. Azure Communication Services (ACS) provides a set of cloud-based APIs for communication, including SMS messaging, that can be integrated into your applications with ease. We’ll demonstrate how to set up a Flask web service to send SMS messages to recipients.

Prerequisites:

  1. You need an Azure account with an Azure Communication Services resource.

  2. Install the following Python libraries:

    • Flask
    • Azure Communication Services SDK

    You can install the required libraries with:

    pip install flask azure-communication-sms

Steps:

  1. Set up an Azure Communication Services resource to get the connection string and a phone number for sending messages.
  2. Implement the Flask app to send SMS.

Code Example:

from flask import Flask, request, jsonify
from azure.communication.sms import SmsClient, SmsSendResult
from azure.communication.sms.models import SmsSendRequest, SmsSendResponse

# Initialize Flask app
app = Flask(__name__)

# Azure Communication Services connection string and sender phone number
connection_string = "your-azure-communication-connection-string"
sender_phone_number = "+1XXXXXXXXXX"  # Your Azure phone number

# Initialize Azure Communication Services SmsClient
sms_client = SmsClient.from_connection_string(connection_string)

@app.route('/send-sms', methods=['POST'])
def send_sms():
    try:
        # Get the recipient phone number and message content from the request
        recipient_phone_number = request.json.get('to')
        message_body = request.json.get('message')

        # Prepare the SMS message
        sms_message = SmsSendRequest(
            from_=sender_phone_number,
            to=[recipient_phone_number],
            message=message_body
        )

        # Send the SMS
        result = sms_client.send(sms_message)

        # Return success message
        if isinstance(result, SmsSendResponse):
            return jsonify({"status": "success", "message": f"Message sent to {recipient_phone_number}"}), 200
        else:
            return jsonify({"status": "error", "message": "Failed to send message"}), 500

    except Exception as e:
        # Handle errors
        return jsonify({"status": "error", "message": str(e)}), 500

if __name__ == '__main__':
    # Run the Flask app
    app.run(debug=True)

Explanation:

  1. Azure Communication Service Connection: The SmsClient.from_connection_string(connection_string) initializes the SMS client using your Azure Communication Services connection string.
  2. Flask API Endpoint: The /send-sms POST endpoint expects a JSON request body with to (recipient phone number) and message (SMS content). It sends an SMS to the recipient using Azure Communication Services.
  3. Error Handling: If any exception occurs during SMS sending, an error response is returned.

Sample JSON Request to Send SMS:

{
  "to": "+1234567890",
  "message": "Hello from Azure Communication Services!"
}

Running the Flask App:

  1. Make sure you’ve set the correct Azure connection string and sender phone number.
  2. Run the Flask app using:
    python app.py
  3. Test it by sending a POST request (using Postman or Curl) to http://127.0.0.1:5000/send-sms.

Example using Curl:

curl -X POST http://127.0.0.1:5000/send-sms -H "Content-Type: application/json" -d '{"to": "+1234567890", "message": "Hello from Azure!"}'

This should send an SMS to the provided phone number using Azure Communication Services.

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example