Integration guides
Python with FastAPI
Complete path for a Python backend with FastAPI and httpx.
python-fastapi/ of the examples repo (Python 3.10+, fastapi, httpx, uvicorn). Routes as in the Go guide. Files: app/main.py (routes, login stub current_user, config), app/limenia.py (client with retries, request hash), app/signature.py, app/webhooks.py (events, placeholders marked TODO).
cd limenia-examples/python-fastapi
python3 -m venv .venv && .venv/bin/pip install -r requirements-dev.txt
.venv/bin/pytest
.venv/bin/uvicorn app.main:create_app --factory # env from .env, filled in by the userWebhook route and signature check
@app.post("/limenia/webhook")
async def limenia_webhook(request: Request) -> Response:
raw_body = await request.body() # the raw bytes, exactly as signed
if len(raw_body) > 1 << 20:
return Response(status_code=413)
try:
verify_signature(request.headers.get("Limenia-Signature"), raw_body, config.webhook_secrets)
except SignatureError as err:
return JSONResponse({"code": err.code}, status_code=401)
event = json.loads(raw_body)
if processed.seen(event["id"]):
return Response(status_code=204) # duplicate: acknowledge only
try:
await webhooks.handle_event(event)
except Exception:
log.exception("limenia event failed", extra={"event_id": event["id"]})
return Response(status_code=503) # Limenia retries
processed.add(event["id"])
return Response(status_code=204)
def verify_signature(header: str | None, raw_body: bytes, secrets: Sequence[str], now: float | None = None) -> None:
if not header:
raise SignatureError("missing_signature")
timestamp, signatures = None, []
for part in header.split(","):
key, sep, value = part.strip().partition("=")
if not sep:
raise SignatureError("malformed_signature")
if key == "t":
if timestamp is not None:
raise SignatureError("malformed_signature")
timestamp = value
elif key == "v1":
signatures.append(value)
if timestamp is None or not re.fullmatch(r"[0-9]{1,12}", timestamp) or not signatures:
raise SignatureError("malformed_signature")
if abs((time.time() if now is None else now) - int(timestamp)) > 300:
raise SignatureError("timestamp_out_of_range")
signed_payload = timestamp.encode() + b"." + raw_body
for secret in secrets:
expected = hmac.new(secret.encode(), signed_payload, hashlib.sha256).hexdigest().encode()
for signature in signatures:
if hmac.compare_digest(expected, signature.encode()):
return
raise SignatureError("signature_mismatch")The processed-ID set in the example is in memory; use a table with the event ID as primary key in production.
Complaints and reviews
Add routes for complaints and reviews like the report route: user from the login, Idempotency-Key, store the returned ID with the user. See Complaints and Pre-moderation reviews.