📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials API Design Webhooks

Webhooks

5 min read Quiz at the end
Webhooks push events to registered URLs — sign with HMAC and respond 200 fast, process async.

Webhooks

import httpx, json, hmac, hashlib

# Send webhook with HMAC signature
def send_webhook(url, event, data, secret):
    payload   = json.dumps({"event":event,"data":data})
    sig       = hmac.new(secret.encode(),payload.encode(),hashlib.sha256).hexdigest()
    httpx.post(url, content=payload, headers={
        "Content-Type": "application/json",
        "X-Signature":  "sha256=" + sig,
    })

# Receive and verify
@app.post("/webhooks/stripe")
async def receive(req: Request, bg: BackgroundTasks):
    body = await req.body()
    sig  = req.headers.get("X-Signature","")
    exp  = "sha256=" + hmac.new(SECRET.encode(),body,hashlib.sha256).hexdigest()
    if not hmac.compare_digest(sig, exp):
        raise HTTPException(400,"Invalid signature")
    bg.add_task(process, json.loads(body))
    return {"received":True}  # return 200 fast!
Topic Quiz · 1 questions

Test your understanding before moving on

1. When receiving a webhook, why should you respond 200 immediately and process async?
💡 Webhook providers retry on non-200 responses — acknowledge fast, process in background to avoid retries.