Docs / SDKs

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.

Updated 2026-12-03~5 min readkestrelmq · PyPI

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 KestrelMQ and async AsyncKestrelMQ clients
  • verify_webhook_signature built on the standard library (hmac, hashlib) with constant-time comparison and secret rotation support

PyPI · Source on GitHub · MIT License

Installation

terminal
pip install kestrelmq

Configuration

ArgumentEnvironment variableDefault
api_keyKESTRELMQ_API_KEYrequired (kmq_live_...)
base_urlKESTRELMQ_BASE_URLhttp://localhost:3000
timeout10.0 seconds
workspace_idsent as X-Workspace-Id when set
http_clientyour 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)

checkout_service.py
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.

ParameterTypeDescription
eventstrEvent name, e.g. order.paid.
payloaddictJSON-serializable payload, validated against the event schema.
recipientdict | NoneUsed by routing rules and templates.
deliver_atstr | datetime | NoneISO 8601 string or datetime for scheduled delivery.
idempotency_keystr | NoneSent 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:

worker.py
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

ExceptionWhen
KestrelAPIErrorNon-2xx response. Fields: status, type, title, detail, instance, errors, retry_after, request_id.
KestrelTimeoutErrorNo response within timeout.
KestrelMQErrorBase 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).

verify.py
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 True if any v1= entry matches any secret. Pass a list (["whsec_new...", "whsec_old..."]) while you roll out a rotation.
  • Rejects timestamps more than tolerance_seconds from now in either direction (replay protection).
  • timestamp may be omitted when the header carries it inline (t=<unix>,v1=<hex>). Conflicting timestamps are rejected.
  • Uses hmac.compare_digest. Malformed input returns False and 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.

app.py
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 "", 204

The 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.