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:
    sent = await client.messages.send_text(phone_number_id, to="15551234567", body="Hola!")
    for msg in kapso.parse(raw_body, headers.get("x-webhook-event")):
        await client.messages.reply_text(msg, "Got it", quote=True)  # same number, same sender

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.
  • Sending: text, image, video, audio and voice notes, documents, stickers, locations, contact cards, reactions, reply buttons, lists, CTA links, location requests, WhatsApp Flows and templates, plus mark_read with a typing indicator. Each takes a phone number, a BSUID or msg.sender, and checks WhatsApp's limits before sending. send_raw sends any other payload as is, unchecked.
  • client.media.upload(): upload a file (bytes, path or open file) and get the media ID to send it with.
  • KapsoClient and KapsoSyncClient: the same API, async or sync (for threads and scripts). API errors raise KapsoError with status_code, code, the provider's message and request_id, never the API key. The message is Kapso's or Meta's text and can quote what you sent: log status_code, code and request_id instead.

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.

Sending messages

from kapso import Button, KapsoClient, ListRow, ListSection

async with KapsoClient(api_key) as client:
    m = client.messages
    await m.mark_read(pnid, msg.message_id, typing=True)  # blue ticks + "typing…"
    await m.send_text(pnid, msg.sender, "Hola!", reply_to=msg.message_id)
    await m.send_buttons(
        pnid, msg.sender, "Confirm the order?", [Button(id="yes", title="Yes"), Button(id="no", title="No")]
    )
    await m.send_list(
        pnid,
        msg.sender,
        "How should we ship it?",
        button="Options",
        sections=[ListSection(rows=[ListRow(id="express", title="Express", description="1-2 days")])],
    )

    media_id = await client.media.upload(pnid, "quote.pdf")  # MIME type from the name
    await m.send_document(pnid, msg.sender, media_id, filename="quote.pdf", caption="Your quote")
    await m.send_template(pnid, "15551234567", "order_update", "en_US", body=["Ana", "#1234"])
  • Who to send to. to is a phone number, a business-scoped user ID (BSUID, e.g. US.1349…), or msg.sender. A BSUID goes in Meta's recipient field, never in to; a Sender sends both its phone and its BSUID when it has both (Meta uses the phone). Replying with msg.sender keeps working for users who hide their number behind a username.
  • What comes back. Every send returns a SendResult: message_id (the WAMID that status webhooks refer to) and Meta's status when it gives one. accepted means Meta took the message, not that it was delivered: watch StatusUpdate for delivered, read or failed.
  • The 24-hour window. Outside 24 hours since the user's last message, only templates go through; anything else raises KapsoError with code=131047.
  • Limits are checked before sending by every typed method: text up to 4096 characters, captions and interactive bodies 1024, 3 buttons with 20-character titles, 10 list rows, and so on. A bad message raises ValueError without a request, and the error states lengths, not your text. send_raw checks nothing: Meta validates the payload.
  • Media. Pass a media ID from client.media.upload() or an https:// link Meta can download. Uploaded media lasts 30 days.
  • Sync code. KapsoSyncClient has the same methods without await: with KapsoSyncClient(api_key) as client: client.messages.send_text(...). It is generated from the async client, so the two never drift.

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, marks each message read with a typing indicator, downloads inbound media, and replies (quoted) 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. The sync client in src/kapso/_sync/ is generated: after changing client.py, messages/resource.py or media/resource.py, run uv run python scripts/unasync.py. CI runs lint, checks the generated code is current, runs 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.0a4

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.0a4
File Size Uploaded Provenance Actions
kapso_python-0.1.0a4.tar.gz 75.4 kB With provenance Details for kapso_python-0.1.0a4.tar.gz

Built distribution (wheel)

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

Total release size: 124.6 kB

Release files / kapso_python-0.1.0a4.tar.gz

Download URL kapso_python-0.1.0a4.tar.gz
Size 75.4 kB
Tags Source
SHA-256 checksum
How to use checksums
7ae602042deafbd9b95b7106de899ca72a6d69cd2ee9873d9bb386e05e4939d3
BLAKE2b-256 checksum
How to use checksums
93f78fb15e6402a18a4050e8b3efd75677cc73c8e2118accb9b59da45ce73d55
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.0a4-py3-none-any.whl

Download URL kapso_python-0.1.0a4-py3-none-any.whl
Size 49.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cfd05d3bf2dfea7c4933388cc2864ba20c72fb7e1a5393d12587eebfdb3ca939
BLAKE2b-256 checksum
How to use checksums
d642e286f8b1da34631595d3a6b7e2f333d9c763e99d5f55b821d6d77bd16ff0
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.0a4

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.0a4.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