Guides
How to Build a Secure Webhook Receiver in Python
A complete, runnable FastAPI receiver for messaging status webhooks, covering installation, signature verification, validation, idempotency, async job processing and local testing.
- Author
- By TXTPro Editorial Team
- Published
- Reading time
- 12 min read
What you will build
A FastAPI application with one endpoint, POST /webhooks/messaging, that authenticates, validates and deduplicates messaging events, hands them to an asyncio worker and responds immediately. It mirrors the Node.js webhook receiver, so teams using both languages get identical behaviour.
Installation
You need Python 3.10 or later. Create a virtual environment, install FastAPI and Uvicorn (Pydantic is installed with FastAPI), load your environment variables and start the server:
mkdir webhook-receiver && cd webhook-receiver
python3 -m venv .venv
source .venv/bin/activate
pip install fastapi uvicorn
set -a; source .env; set +a # load WEBHOOK_SIGNING_SECRET and WEBHOOK_SIGNATURE_HEADER
uvicorn webhook_receiver:app --port 8000Create .env before the last two commands, with placeholder values replaced:
# .env: keep out of version control.
# Generate a secret with: openssl rand -hex 32
WEBHOOK_SIGNING_SECRET=replace-with-a-random-64-character-hex-string
# Example header name for local testing only. Use the name in your integration documentation.
WEBHOOK_SIGNATURE_HEADER=X-Webhook-SignatureComplete FastAPI webhook receiver
Save this as webhook_receiver.py:
# webhook_receiver.py: generic FastAPI receiver for messaging status webhooks.
# Requires Python 3.10+ and: pip install fastapi uvicorn
# Run with: uvicorn webhook_receiver:app --port 8000
#
# ASSUMPTIONS (generic HMAC sample, not a confirmed TXTPro signing contract):
# 1. The sender signs the exact raw request body with HMAC-SHA256 and a shared secret.
# 2. The hex-encoded signature arrives in the header named by WEBHOOK_SIGNATURE_HEADER.
# 3. Each request carries one JSON event with the fields validated below.
# Replace these with the contract in your TXTPro integration documentation.
import asyncio
import hashlib
import hmac
import json
import logging
import os
from contextlib import asynccontextmanager
from datetime import datetime
from typing import Literal
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field, ValidationError
SECRET = os.environ.get("WEBHOOK_SIGNING_SECRET")
SIGNATURE_HEADER = os.environ.get("WEBHOOK_SIGNATURE_HEADER")
if not SECRET or not SIGNATURE_HEADER:
# Fail closed: refuse to start rather than accept unauthenticated callbacks.
raise SystemExit("Missing WEBHOOK_SIGNING_SECRET or WEBHOOK_SIGNATURE_HEADER. Refusing to start.")
MAX_BODY_BYTES = 64 * 1024
FINAL_STATUSES = {"DELIVERED", "FAILED", "REJECTED", "EXPIRED", "UNDELIVERED"}
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("webhooks")
class WebhookEvent(BaseModel):
model_config = ConfigDict(extra="ignore")
event_id: str = Field(min_length=1, max_length=128)
event_type: str = Field(min_length=1, max_length=64)
message_id: str = Field(min_length=1, max_length=128)
channel: Literal["sms", "rcs", "whatsapp", "voice"]
status: str = Field(min_length=1, max_length=32)
timestamp: datetime
def verify_signature(raw_body: bytes, received: str | None) -> bool:
if not received:
return False
expected = hmac.new(SECRET.encode(), raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, received.strip())
# In-memory stand-ins so the example runs as-is. In production use a database table
# with a unique key on event_id, and a durable queue (for example Redis, SQS or RabbitMQ).
processed_event_ids: set[str] = set()
messages: dict[str, dict] = {} # provider message_id -> {"status": ..., "status_at": ...}
queue: "asyncio.Queue[WebhookEvent]" = asyncio.Queue()
async def worker() -> None:
while True:
event = await queue.get()
try:
await process_event(event)
except Exception as exc:
log.error("processing failed event_id=%s error=%s", event.event_id, type(exc).__name__)
# Move the event to a dead-letter store for review and retry.
finally:
queue.task_done()
@asynccontextmanager
async def lifespan(app: FastAPI):
task = asyncio.create_task(worker())
yield
task.cancel()
app = FastAPI(lifespan=lifespan)
def error(code: str, status_code: int) -> JSONResponse:
return JSONResponse({"error": code}, status_code=status_code)
@app.post("/webhooks/messaging")
async def receive_webhook(request: Request) -> JSONResponse:
if request.headers.get("content-type", "").split(";")[0].strip().lower() != "application/json":
return error("unsupported_media_type", 415)
declared = request.headers.get("content-length", "")
if declared.isdigit() and int(declared) > MAX_BODY_BYTES:
return error("payload_too_large", 413)
raw = await request.body()
if not raw:
return error("empty_body", 400)
if len(raw) > MAX_BODY_BYTES:
return error("payload_too_large", 413)
if not verify_signature(raw, request.headers.get(SIGNATURE_HEADER)):
return error("invalid_signature", 401)
try:
data = json.loads(raw)
except ValueError:
return error("invalid_json", 400)
try:
event = WebhookEvent.model_validate(data)
except ValidationError:
return error("invalid_payload", 422)
if event.event_id in processed_event_ids:
return JSONResponse({"received": True, "duplicate": True})
processed_event_ids.add(event.event_id)
await queue.put(event)
# Log identifiers only: never phone numbers, message text, OTPs or secrets.
log.info("webhook accepted event_id=%s channel=%s status=%s", event.event_id, event.channel, event.status)
return JSONResponse({"received": True})
async def process_event(event: WebhookEvent) -> None:
record = messages.get(event.message_id) # replace with a database lookup
if record is None:
log.warning("unknown message_id event_id=%s", event.event_id)
return
status = event.status.upper()
# Events can arrive out of order: never move a final status back to an interim one.
if record.get("status") in FINAL_STATUSES and status not in FINAL_STATUSES:
return
if record.get("status_at") and record["status_at"] > event.timestamp:
return
record.update(status=status, status_at=event.timestamp) # replace with a database update
The POST endpoint and the raw request body
The endpoint takes the Starlette Request object instead of a Pydantic model parameter. Declaring a model parameter would make FastAPI parse the JSON before your code runs, losing the exact bytes needed for signature verification. Instead, the handler checks the content type and declared size, reads await request.body(), and enforces the 64 KB limit on the actual bytes.
Signature verification
verify_signature computes an HMAC-SHA256 of the raw body with the shared secret and compares it with the received header using hmac.compare_digest, which takes the same time whether the values differ in the first character or the last. Header lookup is case-insensitive, so the configured header name can use any capitalisation.
Payload validation
JSON is parsed only after authentication. Invalid JSON returns 400. The parsed object is then validated by the WebhookEvent model: length limits on identifiers, a fixed set of channels, and an ISO 8601 timestamp parsed into a datetime. Unknown extra fields are ignored rather than rejected, so additional fields added by the sender do not break your endpoint.
Idempotency
Each event ID is checked against the processed set. A repeat returns 200 with duplicate: true, which tells the sender to stop retrying without processing the event twice. The example uses an in-memory set; in production, insert the event ID into a database table with a unique constraint, because memory is lost on restart and is not shared between worker processes.
Async job processing
A FastAPI lifespan handler starts a background asyncio task that consumes an asyncio.Queue. The endpoint puts each new event on the queue and returns at once; the worker looks up the message and updates its status, ignoring out-of-order interim events. For production, replace the in-process queue with a durable one consumed by a separate worker, such as a task queue backed by Redis, RabbitMQ or a cloud queue service.
HTTP response and error handling
| Code | When | Effect |
|---|---|---|
| 200 | Event verified and queued, or a duplicate of an event already received | The sender should stop retrying |
| 400 | Empty body or invalid JSON | Permanent; the request needs fixing |
| 401 | Missing or invalid signature | Rejects unauthenticated callbacks |
| 413 | Body larger than 64 KB | Protects memory and workers |
| 415 | Content type is not application/json | Rejects unexpected formats |
| 422 | Valid JSON that fails schema validation | Permanent; the payload does not match |
Unexpected exceptions in the endpoint are returned as 500 by FastAPI. Failures inside the worker are logged with the event ID and exception type only, never the payload, and are the point at which to move an event to a dead-letter store.
Testing locally
With the server running on port 8000, sign the illustrative payload and send it:
# In a second terminal, load the same .env values first:
set -a; source .env; set +a
BODY='{"event_id":"evt_example_001","event_type":"message.delivered","message_id":"msg_example_123","channel":"sms","status":"DELIVERED","timestamp":"2026-11-08T10:30:00Z"}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$WEBHOOK_SIGNING_SECRET" | sed 's/^.*= //')
# Signed request: expect 200 {"received":true}
curl -i -w '
' -X POST http://localhost:8000/webhooks/messaging \
-H "Content-Type: application/json" -H "$WEBHOOK_SIGNATURE_HEADER: $SIG" --data "$BODY"
# Same request again: expect 200 {"received":true,"duplicate":true}
# Wrong signature: expect 401
curl -i -w '
' -X POST http://localhost:8000/webhooks/messaging \
-H "Content-Type: application/json" -H "$WEBHOOK_SIGNATURE_HEADER: bad" --data "$BODY"Expect 200, then a duplicate response, then 401. Uvicorn logs “unknown message_id” for the test event because the in-memory store is empty. To confirm the fail-closed behaviour, start Uvicorn in a shell without the variables: it stops with “Refusing to start”.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Every request returns 401 | The test signs different bytes from those sent, or the secret differs between terminals | Load the same .env in both terminals and sign the exact body |
| 422 for a payload that looks right | A field fails validation, often the timestamp format or an unknown channel | Log the validation error locations (not values) while testing |
| Duplicates processed after scaling to several workers | Each Uvicorn worker has its own in-memory set | Move deduplication to a shared database |
| Server stops at startup with “Refusing to start” | Environment variables not set in that shell | Run set -a; source .env; set +a before starting |
Security checklist
- Secrets only in environment variables or a secrets manager
- Module refuses to start without authentication configuration
- Signature verified over the raw body with
hmac.compare_digest - Content-type check, body size limit and gateway rate limiting
- Event ID deduplication in shared, durable storage
- Identifiers-only logging
- HTTPS termination in front of Uvicorn, with monitoring of 4xx/5xx rates
See the webhook security guide for the reasoning behind each control, and the Node.js webhook guide for the Express equivalent.
Frequently asked questions
Why not declare a Pydantic model parameter on the FastAPI endpoint?
FastAPI would parse the JSON before your code runs, so you would lose the exact bytes needed to verify a signature. Read the raw body first, verify it, then validate with the model.
Is this Python example compatible with TXTPro production webhooks?
Not as written. The signing scheme is a placeholder: once the callback contract for your account is confirmed, update the verify_signature function, the SIGNATURE_HEADER setting and the WebhookEvent model to match it.
Can I use Flask or Django instead of FastAPI?
Yes. The same steps apply: read the raw body, verify the signature, validate, deduplicate, queue and respond quickly. Only the framework calls differ.
Sources and further reading
Editorial note: This article is written by the TXTPro editorial team (KSVL Solutions) for general information. Regulations and platform policies change; check the linked official sources and seek professional advice for your situation. See our editorial standards.
