Python SDK
Official kestrelmq Python SDK (PyPI) with sync KestrelMQ and async AsyncKestrelMQ httpx clients, RFC 9457 errors, and verify_webhook_signature with secret rotation support.
kestrelmq is the official Python client for KestrelMQ: send events and verify outbound webhook signatures.
- Python 3.10+, typed (
py.typed) - One runtime dependency:
httpx - Sync
KestrelMQand asyncAsyncKestrelMQclients verify_webhook_signaturebuilt on the standard library (hmac,hashlib) with constant-time comparison and secret rotation support
PyPI · Source on GitHub · MIT License
Installation
pip install kestrelmqConfiguration
| Argument | Environment variable | Default |
|---|---|---|
api_key | KESTRELMQ_API_KEY | required (kmq_live_...) |
base_url | KESTRELMQ_BASE_URL | http://localhost:3000 |
timeout | 10.0 seconds | |
workspace_id | sent as X-Workspace-Id when set | |
http_client | your own httpx.Client / httpx.AsyncClient |
base_url may include or omit the /v1 suffix. Self-hosted stacks started with ./scripts/selfhost-up.sh serve the API on http://localhost:8080. A client you pass through http_client= (custom transports, proxies, connection pooling) is not closed by the SDK.
Send events (send_event)
from kestrelmq import KestrelMQ, KestrelAPIError
with KestrelMQ(api_key="kmq_live_...", base_url="http://localhost:8080") as mq:
try:
receipt = mq.send_event(
"order.paid",
{"order_id": "ord_9812", "amount": 4900},
recipient={"email": "ada@example.com"},
idempotency_key="order-paid-ord_9812",
)
print(receipt["eventId"], receipt["deliveryIds"])
except KestrelAPIError as err:
# RFC 9457 Problem Details
print(err.status, err.type, err.detail, err.errors)
if err.status in (429, 503) and err.retry_after is not None:
print(f"retry after {err.retry_after}s")send_event calls POST /v1/events and returns the 202 Accepted body as a SendEventResponse typed dict.
| Parameter | Type | Description |
|---|---|---|
event | str | Event name, e.g. order.paid. |
payload | dict | JSON-serializable payload, validated against the event schema. |
recipient | dict | None | Used by routing rules and templates. |
deliver_at | str | datetime | None | ISO 8601 string or datetime for scheduled delivery. |
idempotency_key | str | None | Sent as the Idempotency-Key header and in the body. A repeat returns the original event with idempotentReplay: True. |
Async client (AsyncKestrelMQ)
AsyncKestrelMQ has the same constructor and send_event signature, built on httpx.AsyncClient:
import asyncio
from kestrelmq import AsyncKestrelMQ
async def main() -> None:
async with AsyncKestrelMQ() as mq: # reads KESTRELMQ_API_KEY / KESTRELMQ_BASE_URL
await mq.send_event("user.signup", {"user_id": "u_1"})
asyncio.run(main())Errors
| Exception | When |
|---|---|
KestrelAPIError | Non-2xx response. Fields: status, type, title, detail, instance, errors, retry_after, request_id. |
KestrelTimeoutError | No response within timeout. |
KestrelMQError | Base class of both. |
Verify webhook signatures (verify_webhook_signature)
KestrelMQ signs "{timestamp}.{raw_body}" with HMAC-SHA256 using your workspace signing secret and sends X-KestrelMQ-Timestamp (Unix seconds) and X-KestrelMQ-Signature (v1=<hex>, or v1=<new>,v1=<old> during a secret rotation grace window).
import os
from kestrelmq import verify_webhook_signature
ok = verify_webhook_signature(
payload=raw_body, # str | bytes, exactly as received
signature_header=headers["X-KestrelMQ-Signature"],
secrets=os.environ["KESTRELMQ_SIGNING_SECRET"], # str | list[str]
tolerance_seconds=300,
timestamp=headers["X-KestrelMQ-Timestamp"],
)- Returns
Trueif anyv1=entry matches any secret. Pass a list (["whsec_new...", "whsec_old..."]) while you roll out a rotation. - Rejects timestamps more than
tolerance_secondsfrom now in either direction (replay protection). timestampmay be omitted when the header carries it inline (t=<unix>,v1=<hex>). Conflicting timestamps are rejected.- Uses
hmac.compare_digest. Malformed input returnsFalseand never raises.
Verify the raw body
Parsing and re-serializing JSON changes the bytes and breaks the signature. Read request.get_data() (Flask) or await request.body() (FastAPI) before parsing.
import os
from flask import Flask, abort, request
from kestrelmq import verify_webhook_signature
app = Flask(__name__)
@app.post("/webhooks/kestrelmq")
def kestrelmq_webhook():
if not verify_webhook_signature(
request.get_data(),
request.headers.get("X-KestrelMQ-Signature", ""),
os.environ["KESTRELMQ_SIGNING_SECRET"],
timestamp=request.headers.get("X-KestrelMQ-Timestamp"),
):
abort(401)
event = request.get_json()
return "", 204The same verifier works for generic system alert webhooks, which are signed with the same workspace secret. In the dashboard Delivery Inspector → Verify Signature tab, you can also generate a standalone Python, Node.js, or Go verification snippet populated with any attempt's x-kestrelmq-signature, x-kestrelmq-timestamp, and raw body.