
Security News
TC39 Advances 11 Proposals for Math Precision, Binary APIs, and More
TC39 advances 11 JavaScript proposals, with two moving to Stage 4, bringing better math, binary APIs, and more features one step closer to the ECMAScript spec.
A comprehensive, production-ready Python wrapper around the WhatsApp Web API with strongly-typed interfaces, error handling, and automatic retries
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:
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:
Session Management:
Chat & Contact Management:
Group Operations:
Profile & Status:
For a complete list of available endpoints and features, visit the API documentation at http://localhost:3000/api-docs/
when the server is running.
This Python wrapper is built with the following key components:
httpx
for robust HTTP communication with retry mechanismsPydantic
models ensure type safety for all requests and responsestenacity
library provides automatic retries with exponential backoffpytest
with unit and integration testswhatsapp_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="1234567890@c.us", # 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="1234567890@c.us",
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=["1234567890@c.us", "0987654321@c.us"]
)
group_response = api.create_group(session_id, group_request)
# Add participants to the group
add_request = GroupActionRequest(
chatId=group_response.groupId,
participants=["1111111111@c.us"]
)
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 sessionssend_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 messageget_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 messagesget_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 textcreate_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 pictureset_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 unavailablesend_seen(session_id, request)
- Mark messages as seensend_state_typing(session_id, request)
- Send typing indicatorsend_state_recording(session_id, request)
- Send recording indicatorThe 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/
../whatsapp-api/
directory) running at http://localhost:3000
# 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 backoffhttpx.AsyncClient
for better performanceThis 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.
git checkout -b feature/amazing-feature
)pytest
)git commit -m 'Add amazing feature'
)git push origin feature/amazing-feature
)This project is not affiliated with WhatsApp or Meta. Use at your own risk and ensure compliance with WhatsApp's Terms of Service.
FAQs
A comprehensive, production-ready Python wrapper around the WhatsApp Web API with strongly-typed interfaces, error handling, and automatic retries
We found that whatsapp-api-py demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
TC39 advances 11 JavaScript proposals, with two moving to Stage 4, bringing better math, binary APIs, and more features one step closer to the ECMAScript spec.
Research
/Security News
A flawed sandbox in @nestjs/devtools-integration lets attackers run code on your machine via CSRF, leading to full Remote Code Execution (RCE).
Product
Customize license detection with Socket’s new license overlays: gain control, reduce noise, and handle edge cases with precision.