This release is a pre-release and may not be stable for production use.
kapso-python
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'sX-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 thelist[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, plusUnknownEventfor anything new) as a typed object:MessagesReceived,StatusUpdate,ConversationEvent,ConversationInactive,ContactIdentityChanged,MarketingPreferenceChanged,ThreadOwnershipChanged,ThreadStandby.- Typed content:
msg.contentis one ofText,MediaMessage(image, video, audio, document, sticker),Location,Contacts,InteractiveReply(button or list),FlowReply,QuickReply,Reaction, orUnknown, which keeps the raw message, so a new WhatsApp type never raises.msg.textis 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:statusfor 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_readwith a typing indicator. Each takes a phone number, a BSUID ormsg.sender, and checks WhatsApp's limits before sending.send_rawsends 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.KapsoClientandKapsoSyncClient: the same API, async or sync (for threads and scripts). API errors raiseKapsoErrorwithstatus_code,code, the provider's message andrequest_id, never the API key. The message is Kapso's or Meta's text and can quote what you sent: logstatus_code,codeandrequest_idinstead.
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 byX-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
sentcan arrive after itsdelivered, anddeliveredis 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.createdcan arrive after the message that opened the conversation, so don't make message handling wait for it. is_new_conversationmeans "this inbound message opened the conversation". A conversation your app opens with an outbound message (a template, a follow-up) fires noconversation.created, and the customer's reply hasis_new_conversation=False. To reset per-conversation state, watchconversation_idchange.ConversationInactiveis aConversationEvent: in amatch, 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.
tois a phone number, a business-scoped user ID (BSUID, e.g.US.1349…), ormsg.sender. A BSUID goes in Meta'srecipientfield, never into; aSendersends both its phone and its BSUID when it has both (Meta uses the phone). Replying withmsg.senderkeeps 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'sstatuswhen it gives one.acceptedmeans Meta took the message, not that it was delivered: watchStatusUpdatefordelivered,readorfailed. - The 24-hour window. Outside 24 hours since the user's last message, only templates go through; anything else raises
KapsoErrorwithcode=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
ValueErrorwithout a request, and the error states lengths, not your text.send_rawchecks nothing: Meta validates the payload. - Media. Pass a media ID from
client.media.upload()or anhttps://link Meta can download. Uploaded media lasts 30 days. - Sync code.
KapsoSyncClienthas the same methods withoutawait: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
pydanticandhttpxonly. Framework integrations will be optional extras. - No hidden configuration. The library never reads environment variables or
.envfiles. Your app loads its secrets however it likes and passes them in. - Distribution vs import name. The project is
kapso-python; youimport kapso. - Organized by API area.
kapso/webhooks/(receiving),kapso/messages/(sending), more as they're added; domain types inkapso/types.py. Import everything public fromkapsoitself: 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)
| 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)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| 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 logRelease 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 logSecurity 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.
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 logA 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.