Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

kapso-python

CI

A Python SDK for Kapso (WhatsApp Business), built from real webhook traffic.

Unofficial, community-built: not affiliated with or endorsed by Kapso. Early and learning-driven (alpha): the API will change.

uv add kapso-python        # or: pip install kapso-python
import kapso

if not kapso.verify(raw_body, headers.get("x-webhook-signature"), secret):
    ...  # reject: 401

for msg in kapso.parse(raw_body, headers.get("x-webhook-event")):
    print(msg.message_id, msg.content.kind, msg.text)

async with kapso.KapsoClient(api_key) as client:
    wamid = await client.messages.send_text(phone_number_id, to="15551234567", body="Hola!")

What works today

  • verify(): checks Kapso's X-Webhook-Signature (HMAC-SHA256 of the raw body) in constant time, without crashing on malformed headers.
  • parse(): the common case. Turns a verified delivery into the list[InboundMessage] a user just sent. Batches are flattened; status events, outbound echoes, imported history and passive messages (handled by another app) are left out.
  • parse_event(): every Kapso WhatsApp event (12, plus UnknownEvent for anything new) as a typed object: MessagesReceived, StatusUpdate, ConversationEvent, ConversationInactive, ContactIdentityChanged, MarketingPreferenceChanged, ThreadOwnershipChanged, ThreadStandby.
  • Typed content: msg.content is one of Text, MediaMessage (image, video, audio, document, sticker), Location, Contacts, InteractiveReply (button or list), FlowReply, QuickReply, Reaction, or Unknown, which keeps the raw message, so a new WhatsApp type never raises. msg.text is what to read: the body, a caption, a voice-note transcript, or the title of the option tapped.
  • Dedup keys: every object an app should act on once has a dedup_key (the WAMID for a message, wamid:status for a status, ...).
  • client.media.download(): the bytes of inbound media, capped in size, checked against WhatsApp's SHA-256, with a fallback to a fresh download URL when Kapso's copy fails.
  • KapsoClient: async client (httpx). client.messages.send_text(...) returns the new message's WAMID; API errors raise KapsoError with status_code, code and Kapso's message, never the API key.

Works with any web framework. All three take the raw body bytes: verify(raw_body, signature, secret), parse(raw_body, event_name) and parse_event(raw_body, headers).

Receiving webhooks

event = kapso.parse_event(raw_body, request.headers)

match event:
    case kapso.MessagesReceived(messages=messages):
        for msg in messages:
            if seen.add_if_new(msg.dedup_key):  # your store: Redis SET NX, a unique DB column, ...
                handle(msg)
    case kapso.StatusUpdate(status="failed", errors=errors):
        log.warning("send failed: %s", [e.code for e in errors])
    case kapso.UnknownEvent():
        pass
  • Verify first, then answer 200 fast. Kapso expects a 200 within 10 seconds and retries otherwise. Do slow work (replies, LLM calls, downloads) after responding, in a background task or queue.
  • Answer 200 even if parsing fails once the signature is valid. A 500 makes Kapso retry the same body, and a webhook that keeps failing gets paused. Log the error and keep the body.
  • Dedup by dedup_key, not by X-Idempotency-Key. The header names a delivery; a message can arrive in more than one delivery (retries, batch fallback).
  • Statuses arrive in any order. A sent can arrive after its delivered, and delivered is skipped when the user reads right away. Store a status as a rank (sent < delivered < read) and only move it forward.
  • Deliveries of different events aren't ordered against each other. conversation.created can arrive after the message that opened the conversation, so don't make message handling wait for it.
  • is_new_conversation means "this inbound message opened the conversation". A conversation your app opens with an outbound message (a template, a follow-up) fires no conversation.created, and the customer's reply has is_new_conversation=False. To reset per-conversation state, watch conversation_id change.
  • ConversationInactive is a ConversationEvent: in a match, put its case first.
  • Privacy: repr() of every domain object leaves out text, phone numbers, names, coordinates and media URLs (Kapso's media URLs work without auth). Log IDs, not objects' fields.

Design

  • Small core. Runtime dependencies are pydantic and httpx only. Framework integrations will be optional extras.
  • No hidden configuration. The library never reads environment variables or .env files. Your app loads its secrets however it likes and passes them in.
  • Distribution vs import name. The project is kapso-python; you import kapso.
  • Organized by API area. kapso/webhooks/ (receiving), kapso/messages/ (sending), more as they're added; domain types in kapso/types.py. Import everything public from kapso itself: the internal layout may change.

Example: FastAPI receiver

examples/fastapi_receiver.py verifies and parses every event, skips repeats by dedup_key, downloads inbound media, and replies to each inbound message with what the SDK understood ("Recibido: image, 71049 bytes descargados"), after answering the webhook, via a background task.

uv sync
cp .env.example .env          # fill in WEBHOOK_SECRET and KAPSO_API_KEY
uv run fastapi dev            # http://127.0.0.1:8000
ngrok http 8000               # public URL for Kapso

In Kapso, add a WhatsApp webhook on your phone number pointing at https://<your-ngrok-url>/webhooks/kapso, subscribed to the events you want (at least whatsapp.message.received), with the same secret as WEBHOOK_SECRET.

The example saves each verified delivery to tests/fixtures/ (gitignored) so real payloads can be replayed in tests.

Development

uv sync
uv run pytest -q              # tests
uv run ruff check .           # lint
uv run ruff format .          # format

Tests run on committed fixtures: Kapso's documented examples (tests/fixtures/docs) and real captures sanitized by scripts/sanitize_fixture.py (tests/fixtures/public). Raw captures contain phone numbers and message text, so they stay gitignored; tests/test_privacy.py checks the committed ones. uv run python scripts/bench_parse.py measures parsing per event, and --check replays every fixture. CI runs lint and tests on Python 3.11 to 3.14 and checks that the built wheel imports.

Releases: bump version in pyproject.toml, update CHANGELOG.md, then publish a GitHub release tagged v<version>; the release workflow publishes to PyPI.

License

MIT: free to use, modify and ship, including commercially.

Metadata

Release files for kapso-python 0.1.0a3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for kapso-python 0.1.0a3
File Size Uploaded Provenance Actions
kapso_python-0.1.0a3.tar.gz 54.0 kB With provenance Details for kapso_python-0.1.0a3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for kapso-python 0.1.0a3
File Interpreter ABI Platform Actions
kapso_python-0.1.0a3-py3-none-any.whl Python 3 none any Details for kapso_python-0.1.0a3-py3-none-any.whl

Total release size: 83.9 kB

Release files / kapso_python-0.1.0a3.tar.gz

Download URL kapso_python-0.1.0a3.tar.gz
Size 54.0 kB
Tags Source
SHA-256 checksum
How to use checksums
f81b85fa2cf0bc285c03dbfb96c1ccd18c2da73c02e9c832944f7d7d64cb466a
BLAKE2b-256 checksum
How to use checksums
9b3a9adcdd9725abc0ed0deeba84c0bf1e24fe382448d911d1c2629b694ca084
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Release files / kapso_python-0.1.0a3-py3-none-any.whl

Download URL kapso_python-0.1.0a3-py3-none-any.whl
Size 29.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0f73f56498997c7b4839ce4db2afcc675691e2b96ebf82e5f439c97311176b35
BLAKE2b-256 checksum
How to use checksums
09046d866eea7435bd88ff69dcc11a9f9c649ce18323f343349f075464f69a5a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Security for kapso-python 0.1.0a3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for kapso_python-0.1.0a3.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page