Skip to main content

Python client for WhatsApp Business Cloud API with Pydantic validation and async support

Project description

Kapso WhatsApp Cloud API - Python SDK

Python 3.10+ PyPI version License: MIT Tests Code style: ruff Type checked: mypy

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",
) 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",  # 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

๐Ÿงช 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

kapso_whatsapp_cloud_api-0.1.2.tar.gz (42.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

kapso_whatsapp_cloud_api-0.1.2-py3-none-any.whl (47.4 kB view details)

Uploaded Python 3

File details

Details for the file kapso_whatsapp_cloud_api-0.1.2.tar.gz.

File metadata

File hashes

Hashes for kapso_whatsapp_cloud_api-0.1.2.tar.gz
Algorithm Hash digest
SHA256 0ecd2dab9b700378d0e93c8d19509b42ac944db4d8ef15e5731cc4c97b6d8dc4
MD5 e1dd7e86768e15735454872563f503cc
BLAKE2b-256 35ea5d04cba363fa8e40a6e912c8beabb5dd154130ce51d0bd8393f71636309d

See more details on using hashes here.

File details

Details for the file kapso_whatsapp_cloud_api-0.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for kapso_whatsapp_cloud_api-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 cd3f2afbc40d067aa83d76a3d9da2475df796cdc86330dd8ed1c8b06bc6bc719
MD5 eb333cc18c4b696740fb23e8559b95a4
BLAKE2b-256 c70061ad271a657d89511938c21329b0a07e8454ee92ba1351448eaf312c9f8e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page