Python client for WhatsApp Business Cloud API with Pydantic validation and async support
Project description
Kapso WhatsApp Cloud API - Python SDK
A modern, async Python client for the WhatsApp Business Cloud API with Pydantic validation and Kapso proxy support.
โจ Features
- Full WhatsApp Cloud API Support: Messages, templates, media, flows, and more
- Async/Await: Built on httpx for efficient async HTTP operations
- Type Safety: Pydantic v2 models for request/response validation
- Retry Logic: Automatic retries with exponential backoff for transient errors
- Kapso Proxy Integration: Optional enhanced features via Kapso proxy
- Webhook Handling: Signature verification and payload normalization
- Flow Server Support: Handle WhatsApp Flow data exchange server-side
๐ฆ Installation
pip install kapso-whatsapp-cloud-api
Or with uv:
uv add kapso-whatsapp-cloud-api
๐ Quick Start
Sending Messages
from kapso_whatsapp import WhatsAppClient
async def main():
async with WhatsAppClient(access_token="your_token") as client:
# Send a text message
response = await client.messages.send_text(
phone_number_id="123456789",
to="+15551234567",
body="Hello from Python!",
)
print(f"Message sent: {response.message_id}")
# Send an image
await client.messages.send_image(
phone_number_id="123456789",
to="+15551234567",
image={"link": "https://example.com/image.jpg"},
caption="Check this out!",
)
# Send interactive buttons
await client.messages.send_interactive_buttons(
phone_number_id="123456789",
to="+15551234567",
body_text="Choose an option:",
buttons=[
{"id": "opt1", "title": "Option 1"},
{"id": "opt2", "title": "Option 2"},
],
)
Using with Kapso Proxy
from kapso_whatsapp import WhatsAppClient
async with WhatsAppClient(
kapso_api_key="your_kapso_key",
base_url="https://api.kapso.ai/meta/whatsapp",
) as client:
# Access Kapso-specific features
conversations = await client.conversations.list(
phone_number_id="123456789",
status="active",
)
# Query message history
messages = await client.messages.query(
phone_number_id="123456789",
wa_id="15551234567",
)
Webhook Handling
from kapso_whatsapp.webhooks import verify_signature, normalize_webhook
# Verify webhook signature
is_valid = verify_signature(
app_secret="your_app_secret",
raw_body=request.body,
signature_header=request.headers.get("X-Hub-Signature-256"),
)
if not is_valid:
return Response(status_code=401)
# Normalize webhook payload
result = normalize_webhook(request.json())
for message in result.messages:
print(f"From: {message.get('from')}")
print(f"Type: {message.get('type')}")
print(f"Direction: {message.get('kapso', {}).get('direction')}")
for status in result.statuses:
print(f"Message {status.id} is {status.status}")
Template Messages
from kapso_whatsapp import (
WhatsAppClient,
TemplateSendPayload,
TemplateComponent,
TemplateParameter,
)
async with WhatsAppClient(access_token="token") as client:
await client.messages.send_template(
phone_number_id="123456789",
to="+15551234567",
template=TemplateSendPayload(
name="order_confirmation",
language="en_US",
components=[
TemplateComponent(
type="body",
parameters=[
TemplateParameter(type="text", text="John"),
TemplateParameter(type="text", text="ORD-12345"),
],
),
],
),
)
Flow Server-Side Handling
from kapso_whatsapp.server import (
receive_flow_event,
respond_to_flow,
FlowReceiveOptions,
FlowRespondOptions,
)
async def handle_flow_request(request):
# Receive and decrypt flow data
context = await receive_flow_event(FlowReceiveOptions(
raw_body=request.body,
phone_number_id="123456789",
get_private_key=lambda: os.environ["FLOW_PRIVATE_KEY"],
))
print(f"Screen: {context.screen}")
print(f"Form data: {context.form}")
# Respond with next screen
response = respond_to_flow(FlowRespondOptions(
screen="CONFIRMATION",
data={"order_id": "12345", "total": 99.99},
))
return Response(
content=response["body"],
status_code=response["status"],
headers=response["headers"],
)
๐ Resources
The client provides access to various WhatsApp API resources:
| Resource | Description |
|---|---|
client.messages |
Send text, media, templates, interactive messages |
client.media |
Upload, download, and manage media files |
client.templates |
Manage message templates |
client.flows |
Create, publish, and manage WhatsApp Flows |
client.phone_numbers |
Manage phone number settings and business profile |
client.conversations |
List conversations (Kapso proxy only) |
client.contacts |
Manage contacts (Kapso proxy only) |
client.calls |
Call logs and operations (Kapso proxy only) |
๐๏ธ Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ WhatsAppClient โ
โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Config โ โ httpx โ โ Retry Logic โ โ
โ โ (Pydantic) โ โAsyncClient โ โ (exponential backoff) โ โ
โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโ
โผ โผ โผ
โโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ
โ Messages โ โ Media โ โ Templates โ
โ Resource โ โ Resource โ โ Resource โ
โโโโโโโโโโโโโโโโโค โโโโโโโโโโโโโโโโโค โโโโโโโโโโโโโโโโโค
โ โข send_text โ โ โข upload โ โ โข create โ
โ โข send_image โ โ โข download โ โ โข list โ
โ โข send_video โ โ โข get_url โ โ โข get โ
โ โข send_audio โ โ โข delete โ โ โข update โ
โ โข send_doc โ โโโโโโโโโโโโโโโโโ โ โข delete โ
โ โข send_tmpl โ โโโโโโโโโโโโโโโโโ
โ โข interactive โ
โโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโ
โผ โผ โผ
โโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ
โ Flows โ โ PhoneNumbers โ โ Kapso Only โ
โ Resource โ โ Resource โ โ Resources โ
โโโโโโโโโโโโโโโโโค โโโโโโโโโโโโโโโโโค โโโโโโโโโโโโโโโโโค
โ โข create โ โ โข register โ โ Conversations โ
โ โข get โ โ โข get_profile โ โ Contacts โ
โ โข update โ โ โข set_profile โ โ Calls โ
โ โข deploy โ โ โข get_code โ โโโโโโโโโโโโโโโโโ
โ โข publish โ โ โข verify_code โ
โโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ
โ ๏ธ Error Handling
from kapso_whatsapp import WhatsAppClient
from kapso_whatsapp.exceptions import (
WhatsAppAPIError,
RateLimitError,
AuthenticationError,
ValidationError,
)
try:
async with WhatsAppClient(access_token="token") as client:
await client.messages.send_text(...)
except RateLimitError as e:
print(f"Rate limited, retry after {e.retry_after}s")
except AuthenticationError as e:
print(f"Auth failed: {e}")
except ValidationError as e:
print(f"Invalid request: {e}")
except WhatsAppAPIError as e:
print(f"API error {e.code}: {e.message}")
Error Hierarchy
WhatsAppAPIError (base)
โโโ AuthenticationError # 401, invalid tokens
โโโ RateLimitError # 429, rate limits (has retry_after)
โโโ ValidationError # 400, invalid parameters
โโโ NetworkError # Connection failures
โโโ TimeoutError # Request timeouts
โโโ MessageWindowError # 24h window expired
โโโ KapsoProxyRequiredError # Kapso-only feature attempted
โ๏ธ Configuration
client = WhatsAppClient(
access_token="your_token", # Meta access token
# OR
kapso_api_key="your_key", # Kapso API key
base_url="https://api.kapso.ai/meta/whatsapp", # Kapso proxy URL
# Optional configuration
graph_version="v23.0", # Graph API version
timeout=30.0, # Request timeout (seconds)
max_retries=3, # Max retry attempts
retry_backoff=1.0, # Retry backoff multiplier
)
๐ Documentation
- API Reference - Complete API documentation
- Examples - Detailed usage examples
- Webhooks Guide - Webhook integration
- Architecture - System design and diagrams
๐งช Development
# Clone the repository
git clone https://github.com/gokapso/whatsapp-cloud-api-python.git
cd whatsapp-cloud-api-python
# Install dev dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Run linting
ruff check src tests
# Run type checking
mypy src
๐ Requirements
- Python 3.10+
- httpx >= 0.27.0
- pydantic >= 2.0.0
- cryptography >= 42.0.0 (for Flow encryption)
๐ License
MIT License - see LICENSE for details.
๐ Links
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file kapso_whatsapp_cloud_api-0.1.4.tar.gz.
File metadata
- Download URL: kapso_whatsapp_cloud_api-0.1.4.tar.gz
- Upload date:
- Size: 42.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
101b48d4fc23f0a58641c40cda33a7bd4cddf1f36bc974b50d51564473b304a5
|
|
| MD5 |
5e1db628835a89cce3ee3a13f16166e0
|
|
| BLAKE2b-256 |
435dabd07daa40f1c5b6cf51f6edb00037e6bede59be2423d53f3fb3765795a9
|
File details
Details for the file kapso_whatsapp_cloud_api-0.1.4-py3-none-any.whl.
File metadata
- Download URL: kapso_whatsapp_cloud_api-0.1.4-py3-none-any.whl
- Upload date:
- Size: 47.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
216e310f2c91123245af668e7a5a67c97a63908231cc3602bb7efc80406103f3
|
|
| MD5 |
00e30469293f504d6c882d1d9aec4445
|
|
| BLAKE2b-256 |
58c2154788b0121cc8868fb5c4c4672107ede323bfaa2577730303de05c50d22
|