Updated on November 10, 2026
A WhatsApp webhook in FastAPI needs to do three things in the right order: read the raw body with await request.body(), validate the X-Hub-Signature-256 header with HMAC-SHA256 and the app secret, and return 200 immediately, leaving processing for later with BackgroundTasks or a queue. Anything slow (AI, CRM, a remote database) stays out of the response path.
This article picks up where the WhatsApp bot with Python and FastAPI leaves off: there you build the bot from scratch; here the focus is making the webhook asynchronous, secure and resilient to redeliveries, duplicates and process crashes.
Why responding fast matters
According to Meta’s webhooks overview, when delivery fails (a response other than 200, or a connection error), Meta retries with decreasing frequency for up to 7 days, and those retries can produce duplicate notifications. The webhook endpoint page adds that a single POST can carry up to 1,000 batched updates, with no guarantee of batching, and asks you to handle each request individually and deduplicate on your side.
In practice, a handler that calls an AI model before responding becomes a duplicate factory: the response is delayed, the delivery is considered failed, the event comes back and the bot replies twice. If you use Vectalk, the Hub also requires 200 within 20 seconds, according to the Vectalk webhooks documentation.
Webhook structure
# main.py
import hashlib
import hmac
import json
import os
from contextlib import asynccontextmanager
import httpx
from fastapi import BackgroundTasks, FastAPI, HTTPException, Query, Request
from fastapi.responses import PlainTextResponse
VERIFY_TOKEN = os.environ["WA_VERIFY_TOKEN"]
APP_SECRET = os.environ["META_APP_SECRET"].encode()
SEND_URL = os.environ["WA_SEND_URL"] # Meta or Vectalk
TOKEN = os.environ["WA_TOKEN"]
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.http = httpx.AsyncClient(
timeout=15,
headers={"Authorization": f"Bearer {TOKEN}"},
)
yield
await app.state.http.aclose()
app = FastAPI(lifespan=lifespan)
A single httpx.AsyncClient created in the lifespan reuses connections across requests. Creating a new client for every message works, but opens a TLS connection per send.
Want to try it while you read? Create a Vectalk account and send your first message through the official API. Create free account →
GET: endpoint verification
Meta verifies the endpoint with a GET carrying hub.mode, hub.verify_token and hub.challenge. If the token matches, respond 200 with the bare challenge. Since the names contain dots, use alias:
@app.get("/webhook", response_class=PlainTextResponse)
async def verify(
mode: str | None = Query(None, alias="hub.mode"),
token: str | None = Query(None, alias="hub.verify_token"),
challenge: str | None = Query(None, alias="hub.challenge"),
):
if mode == "subscribe" and token and hmac.compare_digest(token, VERIFY_TOKEN):
return challenge or ""
raise HTTPException(status_code=403)
PlainTextResponse matters: if FastAPI returns the challenge as JSON ("123" with quotes), verification fails.
POST: signature over the raw body
Meta signs every event with X-Hub-Signature-256: sha256=<hash>, an HMAC-SHA256 of the body using the app secret, according to the webhook endpoint page. In FastAPI, that means not declaring a Pydantic model as the endpoint parameter: the framework would consume and parse the body before you could get the original bytes. Take the Request and read await request.body():
def valid_signature(raw: bytes, header: str | None) -> bool:
if not header:
return False
expected = "sha256=" + hmac.new(APP_SECRET, raw, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, header)
@app.post("/webhook")
async def receive(request: Request, background: BackgroundTasks):
raw = await request.body()
if not valid_signature(raw, request.headers.get("x-hub-signature-256")):
raise HTTPException(status_code=401)
payload = json.loads(raw)
await save_raw_event(payload) # fast: just stores it
background.add_task(process_event, payload, request.app.state.http)
return {"ok": True}
hmac.compare_digest compares in constant time. If you want Pydantic validation, do it after the signature check: WebhookPayload.model_validate_json(raw). The signature walkthrough in other languages is in how to validate the webhook signature.
BackgroundTasks: what it does and what it doesn’t
According to the FastAPI Background Tasks documentation, tasks registered with add_task(func, *args, **kwargs) run after the response is sent, in the same process as the application. The function can be async def or a regular def. The documentation itself recommends bigger tools, such as Celery, for heavy computation that needs to run across multiple processes or servers.
That sets the limits clearly:
| Situation | Is BackgroundTasks enough? | Alternative |
|---|---|---|
| Reply with fixed text, mark as read | Yes | — |
| Call AI or a CRM with a few seconds of latency | Yes, at low volume | A queue when volume grows |
| Long processing (transcription, OCR, reports) | No | Celery, RQ, ARQ or a managed queue |
| Event that can’t be lost during a deploy or crash | Only if the event is stored first | Store it and reprocess from the database |
The point that bites most: after the 200, Meta considers the event delivered. If the process restarts mid-task (deploy, out of memory, autoscaling), the work is gone and there will be no redelivery. That’s why the example calls save_raw_event before responding. A simple write to a local database takes milliseconds and lets you reprocess whatever was left pending.
Also watch out for blocking code inside async def: a synchronous database call or a requests.post inside an async function blocks the event loop and delays every other webhook. Use async libraries (httpx, asyncpg) inside async def functions.
Idempotent processing
async def process_event(payload: dict, http: httpx.AsyncClient) -> None:
for entry in payload.get("entry", []):
for change in entry.get("changes", []):
value = change.get("value", {})
for msg in value.get("messages", []):
if not await mark_as_seen(msg["id"]):
continue # duplicate: already processed
if msg.get("type") == "text":
await reply(http, msg["from"], "We got your message. We'll reply shortly.")
for st in value.get("statuses", []):
await update_status(st["id"], st["status"], st["timestamp"])
async def reply(http: httpx.AsyncClient, to: str, body: str) -> None:
r = await http.post(SEND_URL, json={
"messaging_product": "whatsapp",
"to": to,
"type": "text",
"text": {"body": body},
})
r.raise_for_status()
mark_as_seen needs storage shared across processes. An in-memory set() won’t do if you run more than one Uvicorn worker or more than one replica. Two common options:
# Option 1: Redis (SET NX with expiry)
async def mark_as_seen(wamid: str) -> bool:
return bool(await redis.set(f"wa:{wamid}", 1, nx=True, ex=7 * 24 * 3600))
# Option 2: Postgres with a unique index
# INSERT INTO wa_inbound (wamid, ...) VALUES ($1, ...) ON CONFLICT (wamid) DO NOTHING
# and check whether a row was inserted
The 7-day expiry matches the maximum redelivery window Meta describes. The fields for each message type are in webhook payload examples, and the sent, delivered, read, failed cycle in message status via webhook.
When to swap BackgroundTasks for a queue
With a queue, the webhook only validates and publishes; separate workers consume:
@app.post("/webhook")
async def receive(request: Request):
raw = await request.body()
if not valid_signature(raw, request.headers.get("x-hub-signature-256")):
raise HTTPException(status_code=401)
await queue.enqueue("process_event", raw.decode()) # ARQ, RQ, Celery, SQS...
return {"ok": True}
The switch pays off when processing takes more than a few seconds, when you need retries with controlled backoff, or when a message spike (a campaign, for example) could saturate the web process. If the bottleneck is sending replies, respect the per-number pace described in WhatsApp API throughput and rate limits.
Testing the signature locally
body='{"object":"whatsapp_business_account","entry":[]}'
signature=$(printf '%s' "$body" | openssl dgst -sha256 -hmac "$META_APP_SECRET" | sed 's/^.* //')
curl -i -X POST http://localhost:8000/webhook \
-H "Content-Type: application/json" \
-H "X-Hub-Signature-256: sha256=$signature" \
-d "$body"
You should get 200; with one character changed in the body, 401. To expose your local server to Meta (which requires HTTPS with a valid certificate), see how to test the webhook locally with ngrok.
How to do this with Vectalk
Vectalk is a proxy for the official Cloud API, so only the variables change. To send, use WA_SEND_URL=https://apis.vectalk.com.br/api/messages with Authorization: Bearer and the same JSON, as in the Vectalk quickstart. With an instance token, the phone_number_id is resolved automatically; with an organization token (the global token from Settings (Configurações) → API Tokens), include phone_number_id in the body, according to the authentication page.
To receive, register your FastAPI URL with POST https://apis.vectalk.com.br/api/webhooks (instance_id, url, name). The Hub forwards the same payload Meta sends and expects 200 within 20 seconds, so process_event doesn’t change. The Vectalk documentation doesn’t describe a signature header on the forwarded request: protect the route with your own secret in the registered URL (for example, ?key=... checked with hmac.compare_digest) and confirm with the team through the contact page. To get started, create your account.
Other stacks: WhatsApp API with Ruby on Rails and WhatsApp API with Next.js. For the big picture, see the official WhatsApp API guide.
Frequently asked questions
Can I declare a Pydantic model as the endpoint parameter?
You can, but then you lose the original bytes and the signature can no longer be verified. Take Request, validate the signature over await request.body() and only then convert with model_validate_json.
Does BackgroundTasks run in a separate process?
No. The FastAPI documentation makes it clear that tasks run in the same process as the application, whether async def or regular def, so a process crash takes the task with it. And, according to the Starlette documentation, tasks run in order and, if one raises an exception, the following ones are not executed. That’s why process_event should handle its own errors.
How many Uvicorn workers should I use?
It depends on the load, but with more than one worker, deduplication must live in Redis or the database, never in memory.
What should I return when the signature doesn’t match?
A code other than 200, such as 401. Monitor that number: a wave of 401s usually means the app secret was changed without updating the server.
Do I need to return anything in the POST body?
No. Meta only looks at the 200 status. A short JSON like {"ok": true} helps with your own logs.
Official sources consulted on November 10, 2026: Meta: create a webhook endpoint, Meta: webhooks overview, Meta: send messages, FastAPI: Background Tasks, Starlette: Background Tasks, Vectalk: quickstart, Vectalk: authentication, Vectalk: webhooks.
Try the official WhatsApp API today
Create your account, generate a token and send your first message with the quick-start guide. Same payloads and webhooks as Meta's Cloud API.
