Guide

How to receive webhooks in Python minimal receiver → production-ready processing

Start with a minimal “native” receiver, but don’t stop there. In production, reliable webhook handling means verification, retries, idempotency, and backpressure — which is where Hooque simplifies everything.

Building for a specific provider? Browse provider webhook APIs.

TL;DR

  • Treat “receive webhooks in Python” as an ops problem, not just a route handler.
  • Verify the request before parsing/side effects (use a verifySignature(...) stub, then implement provider verification).
  • Return 2xx quickly; move work to a worker/queue to avoid timeouts and retries.
  • Assume retries and design idempotency (dedupe by event id + unique constraints).
  • Log + store raw payloads for replayable debugging.
  • If you need one workflow across many providers, centralize ingest + standardize consumption.

Deep dives: security, retries, queue migration.

Anti-patterns

  • Doing business logic inline in the Python request handler.
  • Parsing/transforming the body before verification (breaks signing inputs).
  • Returning 2xx before authenticity is proven.
  • Skipping idempotency (retries become double side effects).

If you’re triaging a live incident, use the debugging playbook .

Framework shortcuts

If you’re already using a framework, jump straight to the minimal framework receiver, then reuse the same production guidance and Hooque consumer loops.

  1. Django
    How to receive webhooks in Django
  2. Flask
    How to receive webhooks in Flask
  3. FastAPI
    How to receive webhooks in FastAPI

Why it's hard in production

A route handler is the easy part. Supporting multiple senders means multiple security models, spikes, and retry semantics.

Verify authenticity + stop replays

Use a verifySignature(...) stub here, then implement real verification + replay defense for each provider.

Read the guide

Assume retries (duplicates are optional)

Treat every delivery as at-least-once and make side effects idempotent (DB constraints, dedupe keys).

Read the guide

Don’t do work in the request path

Ack fast, process async. Otherwise timeouts, deploys, and spikes turn into missed webhooks.

Read the guide

Debug with real payloads

Save the exact body + headers so you can replay deterministically after a fix.

Read the guide

Add monitoring + alerts early

Track delivered vs rejected, processing latency, queue depth, and error rates.

Read the guide

Iterate locally without losing events

Tunnels help, but durable capture + replay removes the “my laptop was asleep” problem.

Read the guide

Minimal standard-library receiver (Python)

This is a minimal starting point. Keep verifySignature(...) as a stub here, then implement provider-specific verification and replay defense in the security guide .

# Python 3.11+ (stdlib only)
# Run: python webhook_server.py
from http.server import BaseHTTPRequestHandler, HTTPServer


def verify_signature(headers: dict, body: bytes) -> None:
    # don't compromise on security
    # TODO: implement provider-specific signature verification
    return


def process_data(body: bytes) -> None:
    # TODO: your business logic (DB writes, external API calls, etc.)
    return


class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        length = int(self.headers.get("content-length", "0"))
        body = self.rfile.read(length)

        verify_signature(dict(self.headers), body)

        # What happens if it fails or times out?
        # Most providers retry → duplicates unless you designed idempotency.
        process_data(body)

        # IMPORTANT: ack fast; do not do real work inline.
        self.send_response(200)
        self.end_headers()

        # TODO: enqueue / write to a queue / trigger async worker
        print("received webhook bytes:", len(body))


HTTPServer(("0.0.0.0", 3000), Handler).serve_forever()

Hooque turns any webhook into a reliable queue.

Non-obvious scenario: you can’t expose a port

In real deployments, the hardest part is often “where does this endpoint run?” (NAT, corporate networks, locked-down environments, short-lived preview deployments). Hooque decouples inbound receiving from processing so your Python app doesn’t need to be the public receiver.

The easy path: receive with Hooque + consume forever

Hooque turns inbound webhooks into a durable queue. Your code becomes a run-forever worker that pulls or streams events and acks/nacks/rejects explicitly.

  • No need to run a public webhook endpoint in every environment (especially for local dev).
  • Durable capture + replay/inspection so “we missed the webhook” becomes debuggable.
  • Explicit Ack / Nack / Reject lifecycle so retries are under your control.
  • Backpressure and spike absorption: buffer now, process at your pace.
  • One consumption pattern across many senders (even if their security/retry rules differ).

Flow

  1. Provider delivers → Hooque ingest endpoint
  2. Hooque persists payload immediately
  3. Your worker pulls (REST) or streams (SSE)
  4. Your worker ack/nack/rejects explicitly

Hooque REST polling loop (runs forever)

Polling is a good default when you want a simple worker loop. It also works in environments where long-lived connections are unreliable.

# Python 3.11+ (requests)
import json
import os
import time
import requests

NEXT_URL = os.getenv("HOOQUE_QUEUE_NEXT_URL", "https://app.hooque.io/queues/<consumerId>/next")
TOKEN = os.getenv("HOOQUE_TOKEN", "hq_tok_replace_me")

def main():
    # Idiomatic requests: use a Session for persistent keep-alive connections in long-polling loops
    with requests.Session() as session:
        session.headers.update({"Authorization": f"Bearer {TOKEN}"})
        
        while True:
            msg = get_next_message(session)
            if not msg:
                time.sleep(1.0)
                continue
            
            try:
                process_data(msg["payload"], msg["meta"])
                ack(session, msg)
            except Exception as e:
                nack(session, msg, e)

def get_next_message(session) -> dict | None:
    try:
        resp = session.get(NEXT_URL, timeout=30)
        
        if resp.status_code == 204:
            return None
        if resp.status_code >= 400:
            print("next() failed:", resp.status_code, resp.text)
            return None

        meta = json.loads(resp.headers.get("X-Hooque-Meta", "{}"))
        content_type = resp.headers.get("content-type", "")
        raw = resp.text

        payload = json.loads(raw) if "json" in content_type.lower() else raw
        return {"payload": payload, "meta": meta}
    except Exception as e:
        print("Worker connection error:", e)
        return None

def process_data(payload, meta) -> None:
    # Example real-life task: run a script on webhook events.
    # subprocess.run(["./on_webhook.sh"], check=True)
    print("event:", meta.get("messageId"))

def ack(session, msg) -> None:
    try:
        url = msg["meta"].get("ackUrl")
        if url:
            session.post(url, timeout=30)
    except Exception as e:
        print("ack error:", e)

def nack(session, msg, error) -> None:
    try:
        reason = str(error)
        url = msg["meta"].get("nackUrl") or msg["meta"].get("rejectUrl")
        if url:
            session.post(url, headers={"Content-Type": "application/json"}, json={"reason": reason}, timeout=30)
    except Exception as e:
        print("nack error:", e)

if __name__ == "__main__":
    main()

Hooque SSE stream consumer (runs forever)

SSE is great for low-latency processing: keep a connection open, process events as they arrive, and reconnect on disconnects.

# Python 3.11+ (requests) — SSE consumer
import base64
import json
import os
import time
import requests
from typing import Iterator

STREAM_URL = os.getenv("HOOQUE_QUEUE_STREAM_URL", "https://app.hooque.io/queues/<consumerId>/stream")
TOKEN = os.getenv("HOOQUE_TOKEN", "hq_tok_replace_me")

def main():
    # Idiomatic requests: use a Session for persistent connections in long running connections
    with requests.Session() as session:
        session.headers.update({"Authorization": f"Bearer {TOKEN}", "Accept": "text/event-stream"})
        
        for msg in get_message_stream(session):
            try:
                process_data(msg["payload"], msg["meta"])
                ack(session, msg)
            except Exception as e:
                nack(session, msg, e)

def get_message_stream(session) -> Iterator[dict]:
    while True:
        try:
            with session.get(STREAM_URL, stream=True, timeout=60) as resp:
                resp.raise_for_status()
                event = None
                data_lines: list[str] = []

                for line in resp.iter_lines(decode_unicode=True):
                    if line is None or line.startswith(":"):
                        continue
                    if line == "":
                        if event == "message" and data_lines:
                            try:
                                raw_msg = json.loads("\n".join(data_lines))
                                yield {"payload": decode_payload(raw_msg), "meta": raw_msg.get("meta") or {}}
                            except json.JSONDecodeError:
                                pass
                        event = None
                        data_lines = []
                        continue

                    if line.startswith("event:"):
                        event = line.split(":", 1)[1].strip()
                    elif line.startswith("data:"):
                        data_lines.append(line.split(":", 1)[1].lstrip())
                        
        except Exception as err:
            print("stream dropped:", err)
            time.sleep(2.0)

def decode_payload(msg: dict):
    raw = msg.get("payload", "") or ""
    if msg.get("encoding") == "base64":
        raw = base64.b64decode(raw).decode("utf-8", errors="replace")
    if "json" in (msg.get("contentType", "") or "").lower():
        return json.loads(raw)
    return raw

def process_data(payload, meta) -> None:
    # Example real-life task: run a script on webhook events.
    print("event:", meta.get("messageId"))

def ack(session, msg) -> None:
    try:
        url = msg["meta"].get("ackUrl")
        if url:
            session.post(url, timeout=30)
    except Exception as e:
        print("ack error:", e)

def nack(session, msg, error) -> None:
    try:
        reason = str(error)
        url = msg["meta"].get("nackUrl") or msg["meta"].get("rejectUrl")
        if url:
            session.post(url, headers={"Content-Type": "application/json"}, json={"reason": reason}, timeout=30)
    except Exception as e:
        print("nack error:", e)

if __name__ == "__main__":
    main()

FAQ

Quick answers for the questions that come up right before you ship.

What status code should I return for webhooks in Python?

General: Usually return a fast 2xx after validating authenticity and basic schema. Timeouts and 5xx commonly trigger retries.

How Hooque helps: Hooque acknowledges ingest immediately and persists the payload. Your worker acks/nacks/rejects explicitly after processing.

Do I need signature verification in Python?

General: Yes, unless the sender is fully trusted and on a private network. A public endpoint without verification is easy to forge and easy to replay.

How Hooque helps: Hooque can verify at ingest for supported providers or using generic strategies. Either way, your worker receives a normalized meta object and can stay focused on processing.

Why do I see duplicate webhook events in Python?

General: Retries are normal: timeouts, transient network failures, and 5xx responses all produce duplicates. Design idempotency around event ids and side-effect boundaries.

How Hooque helps: Hooque makes delivery outcomes explicit (ack/nack/reject) and provides replay/inspection so you can fix issues without guessing what was received.

How do I test webhooks locally in Python?

General: You can use a tunnel, but local dev still breaks on sleep, VPNs, clock skew, and signature-byte mismatches.

How Hooque helps: With Hooque you can avoid inbound locally: receive events into a durable queue and pull/stream to your laptop, then replay from the UI after changes.

Should I use REST polling or SSE streaming for webhook processing?

General: Use REST polling for simple batch workers and environments without long-lived connections. Use SSE for low-latency “process as it arrives” flows.

How Hooque helps: Hooque supports both: `GET /next` for polling and `GET /stream` for streaming. Both include meta with ready-to-call ack/nack/reject URLs.

Start processing webhooks reliably

Create a webhook endpoint, receive events, then run your worker forever using REST polling or SSE streaming — with explicit ack/nack/reject control.

No credit card required