Skip to main content

kestrelmq (Python SDK)

Official lightweight Python client for KestrelMQ: send events and verify outbound webhook signatures.

  • Python 3.10+
  • One runtime dependency: httpx
  • Sync (KestrelMQ) and async (AsyncKestrelMQ) clients
  • Webhook verification with the standard library (hmac, hashlib), constant-time comparison and secret rotation support
  • Typed (py.typed)

Install

pip install kestrelmq

From a checkout of this repository:

pip install -e packages/python-sdk

Configure

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

base_url may include or omit the /v1 suffix.

Send events

from kestrelmq import KestrelMQ, KestrelAPIError

with KestrelMQ(api_key="kmq_live_...", base_url="http://localhost:3000") as kestrel:
    try:
        receipt = kestrel.send_event(
            "order.paid",
            {"orderId": "ord_9001", "amount": 149.99},
            recipient={"email": "ada@example.com"},
            idempotency_key="order-paid-ord_9001",
        )
        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 == 429 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. Arguments:

  • event: event name, e.g. order.paid.
  • payload: JSON-serializable dict.
  • recipient: optional dict used by routing rules and templates.
  • deliver_at: optional ISO 8601 string or datetime for scheduled delivery.
  • idempotency_key: optional. Sent as the Idempotency-Key header and in the body. A repeated key returns the original event with idempotentReplay: True and creates no new deliveries.

Async

import asyncio
from kestrelmq import AsyncKestrelMQ

async def main() -> None:
    async with AsyncKestrelMQ() as kestrel:  # reads KESTRELMQ_API_KEY / KESTRELMQ_BASE_URL
        await kestrel.send_event("user.signup", {"userId": "u_1"})

asyncio.run(main())

Both clients accept an existing httpx.Client / httpx.AsyncClient through http_client= for custom transports, proxies or connection pooling. A client you pass in is not closed by the SDK.

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

KestrelMQ signs "{timestamp}.{raw_body}" with HMAC-SHA256 using your workspace signing secret and sends:

  • X-KestrelMQ-Timestamp: Unix seconds
  • X-KestrelMQ-Signature: v1=<hex>, or v1=<new>,v1=<old> while a secret rotation grace window is open
  • X-KestrelMQ-Delivery-Id, X-KestrelMQ-Event-Id
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 of secrets to accept both while you roll your own configuration.
  • Rejects timestamps more than tolerance_seconds away from now in either direction (replay protection).
  • timestamp may be omitted if the header carries it inline (t=<unix>,v1=<hex>). Conflicting timestamps are rejected.
  • Comparisons use hmac.compare_digest. Malformed input returns False and never raises.

Always verify the raw body. Parsing and re-serializing JSON changes the bytes and breaks the signature.

Flask

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

FastAPI

import os
from fastapi import FastAPI, HTTPException, Request
from kestrelmq import verify_webhook_signature

app = FastAPI()

@app.post("/webhooks/kestrelmq", status_code=204)
async def kestrelmq_webhook(request: Request) -> None:
    body = await request.body()
    if not verify_webhook_signature(
        body,
        request.headers.get("x-kestrelmq-signature", ""),
        os.environ["KESTRELMQ_SIGNING_SECRET"],
        timestamp=request.headers.get("x-kestrelmq-timestamp"),
    ):
        raise HTTPException(status_code=401)

Development

cd packages/python-sdk
python3 -m venv .venv && . .venv/bin/activate
pip install -e ".[test]"
pytest

License

MIT

Metadata

Release files for kestrelmq 0.1.0

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

Source distribution (sdist)

Source distribution for kestrelmq 0.1.0
File Size Uploaded Provenance Actions
kestrelmq-0.1.0.tar.gz 10.9 kB Without provenance Details for kestrelmq-0.1.0.tar.gz

Built distribution (wheel)

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

Total release size: 20.1 kB

Release files / kestrelmq-0.1.0.tar.gz

Download URL kestrelmq-0.1.0.tar.gz
Size 10.9 kB
Tags Source
SHA-256 checksum
How to use checksums
6ebd1d6af905072b63d4bf23c26ddb66803cb47dc7e7bf61e055386fa8dd8512
BLAKE2b-256 checksum
How to use checksums
f7cff04fe42a3ccb962f699cc31dd1aaf95c0473905ef862597bb5824509fbfa
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.2

Release files / kestrelmq-0.1.0-py3-none-any.whl

Download URL kestrelmq-0.1.0-py3-none-any.whl
Size 9.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0297e5121eb7412e875055b83ace35ced81c0331cb0bda60da17a131084dbe01
BLAKE2b-256 checksum
How to use checksums
f3c59d46395a41c72f08a1dd3e0beb8dcb01523076d3f1fb9f817efd92f5c951
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.2

Security for kestrelmq 0.1.0

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

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