A production-ready, highly scalable RESTful API for managing WhatsApp Business message workflows. Built with Flask and PostgreSQL, this system is designed to handle webhook events, message processing, and analytics for customer communication platforms.
This API serves as the backend infrastructure for WhatsApp Business integrations, enabling businesses to receive, process, track, and analyze customer messages at scale. It was developed to solve real-world problems involving high-volume message processing for a WhatsApp Business automation platform.
Built during my Software Development Internship at Yashas AI, a company specializing in WhatsApp Business API automation and AI chatbots.
When businesses use the WhatsApp Business API, they require a robust system to:
- Receive incoming messages reliably via webhooks.
- Persist messages securely and track their lifecycle (pending/processed/failed).
- Filter and search through vast amounts of conversation history.
- Perform batch operations to process or fail multiple messages instantly.
- Monitor team performance, message volume, and peak operational hours.
- Enterprise Database: Backed by PostgreSQL using SQLAlchemy ORM for reliable data persistence and ACID compliance.
- Message Lifecycle Management: Strict state machine logic ensuring messages transition correctly between
pending,processed, andfailedstates. - Bulk Processing Engine: "Selective" and "Blanket" modes to process or fail thousands of messages with a single HTTP request.
- Real-time Analytics: Aggregates queue health, unique sender metrics, and busiest hour calculations natively via PostgreSQL functions.
- Strict Validation Layer: Built-in safeguards ensuring correct Indian phone number formats and payload integrity.
- Modular Architecture: Clean separation of concerns across Routes, Services, Models, and Utilities for maximum maintainability.
- Secure Configuration: Environment variables (
.env) protect sensitive database credentials.
- Framework: Flask (Python 3.9+)
- Database: PostgreSQL
- ORM: SQLAlchemy
- Environment Management: python-dotenv
- Testing: Automated testing via
pytestandpytest-flask - CI/CD: Automated deployment via Render, Continuous Integration via GitHub Actions
- Containerization: Docker & Docker Compose
The codebase follows a professional modular structure:
whatsapp-message-queue-api/
β
βββ .github/
β βββ workflows/
β βββ ci.yml # GitHub Actions CI/CD Pipeline
β
βββ app.py # Application Factory & Database Initialization
βββ run.py # Server Entry Point
βββ config.py # Environment & Configuration Variables
βββ .env # Secret Database Credentials (Git Ignored)
βββ .gitignore # Excludes Python cache and environments from Git
βββ requirements.txt # Python Dependencies
βββ Dockerfile # Container Blueprint for the API
βββ docker-compose.yml # Container Orchestration (API + PostgreSQL)
βββ .dockerignore # Excludes unnecessary files from the container
β
βββ models/
β βββ message_model.py # SQLAlchemy Models & Schema Definitions
βββ routes/
β βββ message_routes.py # HTTP Endpoint Definitions
βββ services/
β βββ message_service.py # Core Business Logic & Database Transactions
βββ tests/
β βββ conftest.py # Pytest Configuration & Fake Database
β βββ test_app.py # Automated Gatekeeper Test Suite
βββ utils/
βββ helpers.py # Reusable Helper Functions
βββ validators.py # Strict Payload Validation Logic
The fastest way to run this API is using Docker. You do not need to install Python or PostgreSQL on your machine.
- Clone the repository
git clone https://github.com/yourusername/whatsapp-message-queue-api.git
cd whatsapp-message-queue-api- Run the application
docker-compose up --buildThe API will start at http://localhost:5000 and a PostgreSQL database will be automatically provisioned.
Prerequisites
- Python 3.9 or higher
- PostgreSQL installed and running locally
- Git
git clone https://github.com/yourusername/whatsapp-message-queue-api.git
cd whatsapp-message-queue-apiCreate a .env file in the root directory to store your PostgreSQL credentials:
touch .envInside the .env file, add your database connection string:
DATABASE_URI="postgresql://username:password@localhost/whatsapp_queue"
pip install -r requirements.txtpython run.pyThe API will start locally at http://localhost:5000
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/messages |
Ingest a new incoming message (Webhook target) |
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/messages |
Retrieve all messages (Supports ?status= and ?phone= filters) |
| GET | /api/messages/<id> |
Fetch a specific message by its ID |
| GET | /api/messages/search?query= |
Full-text substring search across all messages |
| Method | Endpoint | Description |
|---|---|---|
| PATCH | /api/messages/<id>/process |
Mark a specific message as processed |
| PATCH | /api/messages/<id>/fail |
Mark a specific message as failed |
| DELETE | /api/messages/delete/<id> |
Permanently remove a message from the database |
| Method | Endpoint | Description |
|---|---|---|
| PATCH | /api/messages/bulk-process |
Process multiple messages (Send message_ids array, or leave blank to process all) |
| PATCH | /api/messages/bulk-fail |
Fail multiple messages (Send message_ids array, or leave blank to fail all) |
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/messages/stats |
Retrieve queue metrics, sender counts, and peak hours |
The API returns descriptive JSON errors with standardized HTTP status codes:
400 Bad Request: Validation failures (e.g., "Phone number must be 10 digits").404 Not Found: Resource does not exist.415 Unsupported Media Type: Invalid Content-Type headers.500 Internal Server Error: Unexpected database transaction failures (triggers automatic rollback).
- Database Migrations: Transitioning from an in-memory SQLite prototype to a production PostgreSQL database.
- Separation of Concerns: Abstracting business logic away from the routing layer into dedicated service modules.
- Continuous Integration: Implemented a robust automated testing pipeline using
pytestand GitHub Actions to act as a gatekeeper against regression bugs. - UTC Time Standardization: Implementing professional timezone architecture by storing raw UTC numbers in the database and calculating local offsets (IST) only at the serialization layer.
- Transaction Safety: Enforcing
db.session.commit()anddb.session.rollback()to prevent database corruption during failed requests.
(If this MVP were to be scaled to a massive production level, these are the architectural improvements I would implement next)
- Caching Layer: Redis caching for the
/statsendpoint to reduce database load during high-traffic periods. - Throttling: Rate limiting (e.g., 100 messages per hour per sender) using Flask-Limiter to prevent spam.
- Intelligent Routing: Priority assignment based on NLP sentiment analysis of the message content.
This is a professional portfolio project, but suggestions are always welcome! Feel free to:
- Fork the repository
- Create a feature branch
- Submit a pull request
MIT License - feel free to use for learning purposes.
Author: Riya Chaleria
LinkedIn: Riya Chaleria
Email: riyachaleria@gmail.com
Built with β€οΈ during my Software Development Internship at Yashas AI