A Python SDK designed to simplify interaction with the messaging API and webhook functionalities. It ensures seamless message management, automatic signature validation, and provides a robust foundation for developing scalable messaging applications.
- Overview
- Features
- Setup
- Project Structure
- Usage Guide
- Testing
- Architecture Diagram
- Lifecycle with Example
- Future Improvements
The Messaging SDK is a Python library that allows developers to interact with the messaging API effortlessly. It handles authentication, API endpoint management, and webhook processing while ensuring security through HMAC signature validation.
- Provide a seamless developer experience.
- Simplify API interactions with auto-completion and easy-to-use methods.
- Handle webhook signature validation and event processing.
-
SDK Functionalities:
- Send messages with validation.
- List and manage contacts and messages.
- Retry mechanism for transient errors.
-
Webhook Handling:
- Process event notifications.
- Validate requests using HMAC signatures.
-
Environment Configuration:
- Dynamic settings via
.envfile.
- Dynamic settings via
-
Testing:
- Unit, Integration, and End-to-End tests included.
-
Clone the repository:
git clone https://github.com/shiningflash/messaging-sdk.git cd messaging-sdk -
Create a virtual environment and install dependencies:
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install -r requirements.txt
-
Configure environment variables:
- Copy
.env.exampleto.env:cp .env.example .env - Edit
.envand adjust the values.
- Copy
-
Browse the API:
- The repository includes an OpenAPI Specification file located at:
./docs/openapi.yaml. - To explore the API visually, you can use Docker to run the provided tools:
- Ensure Docker is installed on your machine.
- Start the servers:
docker compose up. - The following servers will be available: Swagger UI: http://localhost:8080, Redocly: http://localhost:8090, API Server: http://localhost:3000 (uses a local database).
- The repository includes an OpenAPI Specification file located at:
-
Initialize the SDK:
from sdk.client import ApiClient from sdk.features.messages import Messages # Initialize the API client and Messages module api_client = ApiClient() messages = Messages(api_client) # Send a message response = messages.send_message({ "to": {"id": "contact123"}, # Use the contact ID format for the recipient "content": "Hello, World!", "from": "+987654321" # Sender's phone number }) print(response)
-
List Messages:
# List sent messages with pagination response = messages.list_messages(page=1, limit=10) print(response)
Example Response:
{ "messages": [ { "id": "msg123", "to": { "id": "contact123", "name": "John Doe", "phone": "+1234567890" }, "from": "+987654321", "content": "Hello, World!", "status": "delivered", "createdAt": "2024-12-01T00:00:00Z" } ], "page": 1, "quantityPerPage": 10 }
- Contact Management: Add, update, delete, and list contacts.
- Webhook Integration: Validate and handle webhook payloads with ease.
-
Run the webhook server:
uvicorn src.server.app:app --reload --port 3010
-
Configure the API to send events to your webhook endpoint (e.g.,
http://localhost:3010/webhooks).
-
Run all tests:
pytest
-
Generate a coverage report:
pytest --cov=src --cov-report=term-missing
-
Run specific test modules:
pytest tests/unit/test_sdk/
A detailed overview of the project structure, including descriptions of key files and directories.
.
βββ .github/ # GitHub workflows for CI/CD
β βββ workflows/
β βββ ci.yml # Continuous Integration pipeline configuration
βββ docs/ # Additional documentation
β βββ openapi.yaml # OpenAPI docs
β βββ sdk_usage.md # Comprehensive SDK usage documentation
β βββ webhook_guide.md # Webhook-specific documentation
βββ src/ # Source code directory
β βββ core/ # Core modules for shared logic
β β βββ __init__.py # Core module initialization
β β βββ exceptions/ # Exception handling modules
β β β βββ __init__.py # Consolidated exception imports
β β β βββ api.py # API-specific exceptions
β β β βββ decorators.py # Decorators for exception handling
β β β βββ resource.py # Resource-specific exceptions
β β βββ config.py # Global configuration file for SDK and server
β β βββ logger.py # Logging utilities
β β βββ requests.py # Request helpers for SDK
β β βββ retry.py # Retry logic for transient failures
β β βββ security.py # HMAC validation and signature generation
β β βββ validators.py # Common validation logic
β βββ schemas/ # Schema definitions for request/response
β β βββ __init__.py # Schemas initialization
β β βββ contacts.py # Contact-related schemas
β β βββ errors.py # Error schemas (aligned with OpenAPI specs)
β β βββ messages.py # Message-related schemas
β β βββ webhook.py # Webhook payload schemas
β βββ sdk/ # SDK-related functionalities
β β βββ __init__.py # SDK initialization
β β βββ client.py # API client for interacting with the server
β β βββ features/ # API feature modules
β β βββ __init__.py # Features initialization
β β βββ contacts.py # Contacts-related SDK operations
β β βββ messages.py # Messages-related SDK operations
β βββ server/ # Webhook server implementation
β β βββ __init__.py # Server initialization
β β βββ app.py # Main FastAPI application
β β βββ schemas.py # Schemas specific to the webhook server
βββ tests/ # Testing files for unit, integration, and E2E
β βββ __init__.py # Test package initialization
β βββ conftest.py # Pytest fixtures and test setup
β βββ e2e/ # End-to-End (E2E) tests
β β βββ __init__.py # E2E tests initialization
β β βββ test_contacts_e2e.py # E2E tests for contacts feature
β β βββ test_messages_e2e.py # E2E tests for messages feature
β βββ integration/ # Integration tests
β β βββ __init__.py # Integration tests initialization
β β βββ test_contacts_integration.py # Integration tests for contacts
β β βββ test_messages_integration.py # Integration tests for messages
β β βββ test_webhook.py # Integration tests for webhook functionality
β βββ unit/ # Unit tests for SDK and server
β βββ test_sdk/ # SDK-specific unit tests
β β βββ __init__.py # SDK unit tests initialization
β β βββ test_client.py # Unit tests for API client
β β βββ test_contacts.py # Unit tests for contacts module
β β βββ test_messages.py # Unit tests for messages module
β βββ test_server/ # Server-specific unit tests
β βββ __init__.py # Server unit tests initialization
β βββ test_route.py # Unit tests for API routes
β βββ test_signature_validation.py # Unit tests for signature validation
βββ venv/ # Python virtual environment (not versioned)
βββ .env.example # Example environment variables
βββ docker-compose.yml # Docker Compose configuration
βββ pytest.ini # Pytest configuration
βββ requirements.in # Base Python dependencies
βββ requirements.txt # Locked Python dependencies
βββ README.md # Project documentation and usage guide
βββ setup.py # Setup file to enable 'pip install .'
Here is the comprehensive architectural diagram for better understanding.
+----------------------------------------------------------+
| User |
| (Uses the SDK to send messages, manage contacts, |
| and handle webhook responses programmatically) |
+----------------------------------------------------------+
|
| 1. SDK API Calls
|
+----------------------------------------------------------+
| Messaging SDK |
| |
| +---------------------------------------------+ |
| | Features: | |
| | - `messages.py`: Send/manage messages | |
| | - `contacts.py`: Manage contact lists | |
| +---------------------------------------------+ |
| |
| +---------------------------------------------+ |
| | Utilities: | |
| | - `logger.py`: Logs interactions | |
| | - `validators.py`: Validates signatures | |
| | - `exceptions.py`: Handles errors | |
| | - `retry.py`: Implements retry logic | |
| +---------------------------------------------+ |
| |
| +---------------------------------------------+ |
| | Client (`client.py`): Handles API requests | |
| | - Appends authentication headers | |
| | - Sends REST API calls (e.g., GET, POST) | |
| +---------------------------------------------+ |
+----------------------------------------------------------+
|
| 2. REST API Calls
v
+----------------------------------------------------------+
| API Server |
| |
| +---------------------------------------------+ |
| | Message Queue Simulation: | |
| | - Marks messages as `queued` | |
| | - Simulates delivery or failure | |
| +---------------------------------------------+ |
| |
| +---------------------------------------------+ |
| | Webhook Trigger: | |
| | - Sends event notifications to | |
| | configured Webhook Server URL | |
| +---------------------------------------------+ |
+----------------------------------------------------------+
|
| 3. Webhook Event Notifications
v
+----------------------------------------------------------+
| Webhook Server |
| |
| +---------------------------------------------+ |
| | Endpoints: `/webhooks` | |
| | - Receives POST requests | |
| +---------------------------------------------+ |
| |
| +---------------------------------------------+ |
| | Signature Validation: | |
| | - Validates HMAC signature from | |
| | Authorization header | |
| +---------------------------------------------+ |
| |
| +---------------------------------------------+ |
| | Payload Processing: | |
| | - Parses incoming JSON payload | |
| | - Logs event details | |
| | - Prints payload to console | |
| +---------------------------------------------+ |
| |
| +---------------------------------------------+ |
| | Error Handling: | |
| | - 401 Unauthorized: Invalid Signature | |
| | - 422 Unprocessable Entity: Bad Payload | |
| +---------------------------------------------+ |
+----------------------------------------------------------+
|
| 4. Event Logs/Responses
v
+----------------------------------------------------------+
| Logging |
| |
| - SDK Logs (via `logger.py`): |
| Logs all user interactions, API calls, |
| and errors. |
| |
| - Webhook Server Logs: |
| Logs validated events and signature failures. |
| |
+----------------------------------------------------------+
Here is the comprehensive example for lifecycle of Messaging SDK and Webhook for more understanding.
1. User Sends a Message
+----------------------------------------------------------+
| User |
| - Calls `messages.send_message()` from the SDK |
| |
| Example Code: |
| sdk.messages.send_message( |
| to="+123456789", |
| from_sender="+987654321", |
| content="Hello, World!" |
| ) |
+----------------------------------------------------------+
|
v
2. SDK Sends API Request
+----------------------------------------------------------+
| Messaging SDK |
| |
| - Validates payload (e.g., phone number format). |
| - Prepares headers (`Authorization: Bearer <API_KEY>`). |
| - Sends HTTP POST request to the API. |
| |
| Request: |
| POST /messages |
| Headers: |
| - Authorization: Bearer <API_KEY> |
| Body: |
| { |
| "to": "+123456789", |
| "content": "Hello, World!", |
| "from_sender": "+987654321" |
| } |
+----------------------------------------------------------+
|
v
3. API Server Processes the Message
+----------------------------------------------------------+
| API Server |
| |
| - Marks message as `queued`. |
| - Simulates a delay for processing. |
| - Updates the message status to `delivered` or `failed`.|
| |
| Example Response: |
| { |
| "id": "msg123", |
| "status": "queued", |
| "createdAt": "2024-12-01T10:00:00Z" |
| } |
+----------------------------------------------------------+
|
v
4. API Triggers Webhook Notification
+----------------------------------------------------------+
| Webhook Trigger |
| |
| - Sends a POST request to the configured |
| webhook URL (e.g., `http://localhost:3010/webhooks`). |
| |
| Request: |
| POST /webhooks |
| Headers: |
| - Authorization: Bearer <HMAC-SIGNATURE> |
| Body: |
| { |
| "id": "msg123", |
| "status": "delivered", |
| "deliveredAt": "2024-12-01T12:00:00Z" |
| } |
+----------------------------------------------------------+
|
v
5. Webhook Server Processes the Event
+----------------------------------------------------------+
| Webhook Server |
| |
| - Validates the HMAC signature. |
| - Parses the payload. |
| - Logs and processes the event. |
| |
| Example Log: |
| - "Webhook received: {'id': 'msg123', 'status': 'delivered', |
| 'deliveredAt': '2024-12-01T12:00:00Z'}" |
| |
| Example Processing Code: |
| try: |
| verify_signature(payload, signature, secret) |
| print(f"Message {payload['id']} delivered.") |
| except ValueError: |
| print("Signature validation failed.") |
+----------------------------------------------------------+
|
v
6. Event Logging and Completion
+----------------------------------------------------------+
| Logging |
| |
| - SDK logs the sent message status and errors (if any). |
| - Webhook server logs validated payloads and events. |
| |
| Final Console Output: |
| "Message msg123 delivered." |
+----------------------------------------------------------+
- Add more advanced retry strategies for transient errors.
- Implement caching for frequently used API requests.
- Enhance webhook security with IP whitelisting.
- Extend SDK functionality to support additional API endpoints.