A comprehensive, production-ready Python wrapper around the WhatsApp Web API that provides strongly-typed interfaces, comprehensive error handling, automatic retries, and full test coverage.
This project is a Python wrapper for the Node.js-based WhatsApp REST API located in the whatsapp-api/
directory. The underlying API is a REST wrapper for the whatsapp-web.js library, designed to be used as a Docker container and to provide easy integration with non-Node.js projects.
The core WhatsApp API server (located in whatsapp-api/
) provides:
- REST API Endpoints: Complete WhatsApp Web functionality via HTTP endpoints
- Docker Support: Ready-to-use Docker container for easy deployment
- Session Management: Multiple WhatsApp sessions with QR code authentication
- Media Support: Send/receive images, videos, documents, and audio files
- Group Management: Create groups, manage participants, and handle group settings
- Real-time Callbacks: WebSocket callbacks for incoming messages and status changes
For detailed information about setting up and running the underlying API server, see the WhatsApp API README.
Before using this Python wrapper, you need to have the WhatsApp API server running:
# Navigate to the WhatsApp API directory
cd whatsapp-api
# Run with Docker Compose
docker-compose pull && docker-compose up
The API server will be available at http://localhost:3000
with documentation at http://localhost:3000/api-docs/
.
The underlying WhatsApp API server supports a comprehensive range of WhatsApp Web functionalities:
Messaging:
- Send text, image, video, audio, and document messages
- Send contact and location messages
- Send button and list messages
- Message reactions and replies
- Download media attachments
Session Management:
- Multiple concurrent WhatsApp sessions
- QR code authentication
- Session health monitoring
- Automatic session recovery
Chat & Contact Management:
- Retrieve all chats and contacts
- Block/unblock contacts
- Archive/unarchive chats
- Check if number is registered on WhatsApp
Group Operations:
- Create and manage groups
- Add/remove participants
- Promote/demote administrators
- Group invite management
Profile & Status:
- Update profile picture and status
- Get user presence information
- Send typing/recording indicators
For a complete list of available endpoints and features, visit the API documentation at http://localhost:3000/api-docs/
when the server is running.
- 🚀 Full API Coverage: Complete implementation of all WhatsApp Web API endpoints
- đź”’ Type Safety: Fully typed with Pydantic models for request/response validation
- 🛡️ Error Handling: Comprehensive error handling with custom exceptions
- 🔄 Automatic Retries: Built-in retry logic with exponential backoff for transient failures
- 📊 Logging: Detailed logging for debugging and monitoring
- đź§Ş Well Tested: Comprehensive test suite with unit and integration tests
- đź“– Documentation: Complete API documentation and examples
This Python wrapper is built with the following key components:
- HTTP Client: Uses
httpx
for robust HTTP communication with retry mechanisms - Data Validation:
Pydantic
models ensure type safety for all requests and responses - Error Handling: Custom exception hierarchy for different error types
- Retry Logic:
tenacity
library provides automatic retries with exponential backoff - Testing: Comprehensive test suite using
pytest
with unit and integration tests
whatsapp_api_wrapper/
├── __init__.py # Main package exports
├── client.py # WhatsAppAPI client class
├── models.py # Pydantic models for requests & responses
├── exceptions.py # Custom exception classes
├── utils.py # Utility functions and helpers
└── py.typed # Type hints marker file
tests/ # Pytest test suites
├── unit/ # Unit tests
└── integration/ # Integration tests
pip install whatsapp-api-py
# Clone the repository
git clone https://github.com/a3ro-dev/whatsapp_api_wrapper.git
cd whatsapp_api_wrapper/whatsapp-api-py
# Install the package
pip install -e .
# Install with development dependencies
pip install -e ".[dev]"
# Install all optional dependencies
pip install -e ".[all]"
from whatsapp_api_wrapper import WhatsAppAPI
from whatsapp_api_wrapper.models import TextMessage
# Initialize the client
api = WhatsAppAPI(
api_key="your-api-key", # Optional, can be None for local development
base_url="http://localhost:3000" # Your WhatsApp API server URL
)
# Start a session
session_id = "my-session-123"
session_status = api.start_session(session_id)
print(f"Session started: {session_status.success}")
# Get QR code for initial setup
qr_response = api.get_qr_code(session_id)
print(f"QR Code: {qr_response.qr}")
# Send a text message
message_request = TextMessage(
to="[email protected]", # Phone number with @c.us suffix
body="Hello from Python!"
)
response = api.send_message(session_id, message_request)
print(f"Message sent: {response.success}, ID: {response.messageId}")
# Get all chats
chats = api.get_chats(session_id)
for chat in chats.chats:
print(f"Chat: {chat.name} ({chat.id})")
# Get all contacts
contacts = api.get_contacts(session_id)
for contact in contacts.contacts:
print(f"Contact: {contact.name} ({contact.number})")
from whatsapp_api_wrapper.models import MediaMessage
# Send an image
media_request = MediaMessage(
to="[email protected]",
media="base64-encoded-image-data", # or URL to image
type="image",
caption="Check out this photo!",
filename="photo.jpg"
)
response = api.send_message(session_id, media_request)
from whatsapp_api_wrapper.models import GroupActionRequest
# Create a group
group_request = GroupActionRequest(
name="My Python Group",
participants=["[email protected]", "[email protected]"]
)
group_response = api.create_group(session_id, group_request)
# Add participants to the group
add_request = GroupActionRequest(
chatId=group_response.groupId,
participants=["[email protected]"]
)
api.add_participants(session_id, add_request)
from whatsapp_api_wrapper.exceptions import (
WhatsAppAPIError,
WhatsAppConnectionError,
WhatsAppHTTPError,
WhatsAppSessionError,
WhatsAppRateLimitError
)
try:
response = api.send_message(session_id, message_request)
except WhatsAppSessionError as e:
print(f"Session error: {e.message}")
except WhatsAppRateLimitError as e:
print(f"Rate limited. Retry after: {e.retry_after} seconds")
except WhatsAppConnectionError as e:
print(f"Connection failed: {e.message}")
except WhatsAppHTTPError as e:
print(f"HTTP error {e.status_code}: {e.message}")
except WhatsAppAPIError as e:
print(f"API error: {e.message}")
# Use as a context manager for automatic cleanup
with WhatsAppAPI(base_url="http://localhost:3000") as api:
api.start_session(session_id)
# ... do work ...
# Session automatically closed
import httpx
# Custom HTTP client with specific timeout and headers
custom_client = httpx.Client(
timeout=60.0,
headers={"User-Agent": "My-Custom-Agent"}
)
api = WhatsAppAPI(
api_key="your-api-key",
base_url="http://localhost:3000",
timeout=60,
max_retries=5,
backoff_factor=2.0,
session=custom_client
)
)
start_session(session_id)
- Start a new WhatsApp sessionget_session_status(session_id)
- Get session statusget_qr_code(session_id)
- Get QR code for session setupget_qr_code_image(session_id)
- Get QR code as PNG imagerestart_session(session_id)
- Restart a sessionterminate_session(session_id)
- Terminate a sessionterminate_inactive_sessions()
- Terminate all inactive sessionsterminate_all_sessions()
- Terminate all sessions
send_message(session_id, request)
- Send various types of messagesdelete_message(session_id, request)
- Delete a messageforward_message(session_id, request)
- Forward a messagereact_to_message(session_id, request)
- React to a messagedownload_media(session_id, request)
- Download media from a message
get_chats(session_id)
- Get all chatsget_chat_by_id(session_id, request)
- Get specific chatarchive_chat(session_id, request)
- Archive a chatunarchive_chat(session_id, request)
- Unarchive a chatmute_chat(session_id, request)
- Mute a chatunmute_chat(session_id, request)
- Unmute a chatpin_chat(session_id, request)
- Pin a chatunpin_chat(session_id, request)
- Unpin a chatclear_messages(session_id, request)
- Clear chat messagesdelete_chat(session_id, request)
- Delete a chatfetch_messages(session_id, request)
- Fetch chat messagessearch_messages(session_id, request)
- Search messages
get_contacts(session_id)
- Get all contactsget_contact_by_id(session_id, request)
- Get specific contactblock_contact(session_id, request)
- Block a contactunblock_contact(session_id, request)
- Unblock a contactget_blocked_contacts(session_id)
- Get blocked contactsis_registered_user(session_id, request)
- Check if number is registeredget_number_id(session_id, request)
- Get WhatsApp ID for numberget_profile_pic_url(session_id, request)
- Get profile picture URLget_contact_about(session_id, request)
- Get contact's about text
create_group(session_id, request)
- Create a new groupadd_participants(session_id, request)
- Add group participantsremove_participants(session_id, request)
- Remove group participantspromote_participants(session_id, request)
- Promote to admindemote_participants(session_id, request)
- Demote from adminget_invite_code(session_id, request)
- Get group invite coderevoke_invite(session_id, request)
- Revoke group inviteleave_group(session_id, request)
- Leave a groupset_group_subject(session_id, request)
- Set group nameset_group_description(session_id, request)
- Set group descriptionset_group_picture(session_id, request)
- Set group picturedelete_group_picture(session_id, request)
- Delete group picture
set_status(session_id, request)
- Set status messageset_display_name(session_id, request)
- Set display nameset_profile_picture(session_id, request)
- Set profile picturesend_presence_available(session_id, request)
- Set presence as availablesend_presence_unavailable(session_id, request)
- Set presence as unavailable
send_seen(session_id, request)
- Mark messages as seensend_state_typing(session_id, request)
- Send typing indicatorsend_state_recording(session_id, request)
- Send recording indicator
The wrapper provides comprehensive error handling with specific exception types:
WhatsAppAPIError
- Base exception for all API errorsWhatsAppConnectionError
- Network connectivity issuesWhatsAppHTTPError
- HTTP errors (4xx, 5xx status codes)WhatsAppValidationError
- Request/response validation errorsWhatsAppSessionError
- Session-related errorsWhatsAppRateLimitError
- Rate limiting errors (429 status)WhatsAppAuthenticationError
- Authentication errors (403 status)WhatsAppNotFoundError
- Resource not found errors (404 status)
Run the test suite:
# Run all tests
pytest
# Run with coverage
pytest --cov=whatsapp_api_wrapper
# Run only unit tests
pytest -m unit
# Run only integration tests
pytest -m integration
# Clone the repository
git clone https://github.com/a3ro-dev/whatsapp_api_wrapper.git
cd whatsapp_api_wrapper/whatsapp-api-py
# Install in development mode
pip install -e ".[dev]"
# Install pre-commit hooks
pre-commit install
# Format code
black whatsapp_api_wrapper/ tests/
isort whatsapp_api_wrapper/ tests/
# Type checking
mypy whatsapp_api_wrapper/
# Linting
flake8 whatsapp_api_wrapper/ tests/
- Python 3.10+
- WhatsApp Web API server (from
../whatsapp-api/
directory) running athttp://localhost:3000
- This is the underlying Node.js API that this wrapper communicates with
- Must be running before using this Python wrapper
- Optional: API key for authentication
# Navigate to the WhatsApp API directory (from the project root)
cd ../whatsapp-api
# Start the API server with Docker
docker-compose pull && docker-compose up
# The server will be available at http://localhost:3000
# API documentation will be at http://localhost:3000/api-docs/
httpx
- Modern HTTP clientpydantic
- Data validation and serializationtenacity
- Retry logic with exponential backoff
- Bulk Operations: Enhanced support for bulk message sending with rate limiting and queue management
- Concurrency: Improved concurrent session handling for high-throughput applications
- Async Support: Full async/await support using
httpx.AsyncClient
for better performance - Advanced Retry Strategies: Configurable retry strategies for different error types
- Webhook Support: Built-in webhook handling for real-time message callbacks
- Message Templates: Template system for common message types and formats
This project is licensed under the MIT License - see the LICENSE file for details.
IMPORTANT: This wrapper uses WhatsApp Web protocol through the underlying API server. WhatsApp does not allow bots or unofficial clients on their platform. Use this wrapper at your own risk - there's no guarantee you won't be blocked by WhatsApp for using unofficial API methods.
This project is for educational and development purposes. Always comply with WhatsApp's Terms of Service and local regulations when using this tool.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Make your changes
- Add tests for your changes
- Ensure all tests pass (
pytest
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
This project is not affiliated with WhatsApp or Meta. Use at your own risk and ensure compliance with WhatsApp's Terms of Service.