# Receive WhatsApp webhooks in Python with FastAPI

> Answer the WhatsApp webhook GET, check X-Hub-Signature-256 on the raw body, parse messages with the BSUID fallback and return 200 first in FastAPI.

Published 2026-11-04. Z-API Omni team.

Receive WhatsApp Cloud API webhooks in FastAPI with a GET and a POST on the same path. The GET reads the dotted `hub.*` query keys through `Query(alias=...)` and returns the challenge as plain text. The POST reads `await request.body()`, checks `X-Hub-Signature-256` with `hmac.compare_digest`, schedules the parsing with `BackgroundTasks` and returns 200. The server below needs only `fastapi`, `uvicorn` and the standard library.

## Install and run

FastAPI 0.162.0 and Uvicorn 0.54.0 both require Python 3.10 or later ([fastapi on PyPI](https://pypi.org/project/fastapi/), [uvicorn on PyPI](https://pypi.org/project/uvicorn/), accessed 2026-11-04). Install the two packages by name. The `fastapi[standard]` extra also pulls in fastapi-cli, jinja2, python-multipart and others this server doesn't use.

```bash
pip install fastapi uvicorn
export APP_SECRET="APP_SECRET"
export VERIFY_TOKEN="VERIFY_TOKEN"
uvicorn main:app --port 8000
```

Uvicorn binds to `127.0.0.1` on port `8000` by default ([Uvicorn settings](https://uvicorn.dev/settings/)). In a container, add `--host 0.0.0.0`. Leave `--reload` out of production: FastAPI's deployment page says it "consumes much more resources, is more unstable" ([FastAPI manual deployment](https://fastapi.tiangolo.com/deployment/manually/)). Meta only delivers to HTTPS with a valid certificate, so put a reverse proxy or tunnel with a real certificate in front of port 8000.

## Full FastAPI server

```python
# main.py
import hashlib
import hmac
import json
import os
import traceback
from typing import Annotated

from fastapi import BackgroundTasks, FastAPI, Header, Query, Request, Response
from fastapi.responses import PlainTextResponse

APP_SECRET = os.environ["APP_SECRET"].encode()
VERIFY_TOKEN = os.environ["VERIFY_TOKEN"]

app = FastAPI()
seen: set[str] = set()  # in-memory dedupe for the demo (not thread-safe); use a unique index in production

@app.get("/webhook")
def verify(
    mode: Annotated[str | None, Query(alias="hub.mode")] = None,
    token: Annotated[str | None, Query(alias="hub.verify_token")] = None,
    challenge: Annotated[str | None, Query(alias="hub.challenge")] = None,
):
    if mode == "subscribe" and token == VERIFY_TOKEN and challenge is not None:
        return PlainTextResponse(challenge)
    return Response(status_code=403)

def valid_signature(raw: bytes, header: str | None) -> bool:
    if not header or not header.startswith("sha256="):
        return False
    expected = hmac.new(APP_SECRET, raw, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected.encode(), header[7:].encode("utf-8", "replace"))

@app.post("/webhook")
async def receive(
    request: Request,
    background_tasks: BackgroundTasks,
    x_hub_signature_256: Annotated[str | None, Header()] = None,
):
    raw = await request.body()
    if not valid_signature(raw, x_hub_signature_256):
        return Response(status_code=401)
    try:
        payload = json.loads(raw)
    except ValueError:
        return Response(status_code=400)
    background_tasks.add_task(handle, payload)
    return Response(status_code=200)

def first_time(key: str) -> bool:
    if key in seen:
        return False
    seen.add(key)
    return True

def handle(payload) -> None:
    try:
        process(payload)
    except Exception:
        traceback.print_exc()

def process(payload) -> None:
    if payload.get("object") != "whatsapp_business_account":
        return
    for entry in payload.get("entry", []):
        for change in entry.get("changes", []):
            if change.get("field") != "messages":
                continue
            value = change.get("value", {})
            for msg in value.get("messages", []):
                if not first_time(f"msg:{msg['id']}"):
                    continue
                sender = msg.get("from") or msg.get("from_user_id")
                kind = msg.get("type")
                text = msg.get("text", {}).get("body") if kind == "text" else f"[{kind}]"
                print(f"message {msg['id']} from {sender} at {msg.get('timestamp')}: {text}", flush=True)
            for st in value.get("statuses", []):
                if not first_time(f"status:{st['id']}:{st['status']}"):
                    continue
                recipient = st.get("recipient_id") or st.get("recipient_user_id")
                print(f"status {st['status']} for {st['id']} to {recipient}", flush=True)
                if st["status"] == "failed":
                    print(json.dumps(st.get("errors", [])), flush=True)
```

Set the callback URL to `https://YOUR_DOMAIN/webhook` in the App Dashboard, enter the same verify token and subscribe to the `messages` field. Reply with [the Python send script](/academy/articles/send-whatsapp-message-python-cloud-api/).

## Read the dotted hub keys with an alias

Meta's verification GET and its rules are covered in [the Express version of this guide](/academy/articles/whatsapp-webhook-nodejs-express-receive-messages/). The FastAPI part is the parameter names. `hub.mode` can't be a Python argument name. In FastAPI you "can declare an `alias`, and that alias is what will be used to find the parameter value" ([FastAPI query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/)).

Each parameter defaults to `None`. A request missing one of the keys then reaches your own 403 instead of FastAPI's validation error response. Reading `request.query_params["hub.mode"]` works too, if you prefer no aliases.

The challenge goes back through `PlainTextResponse`, which "Takes some text or bytes and returns a plain text response" ([FastAPI custom response](https://fastapi.tiangolo.com/advanced/custom-response/)). Return the bare string from the function and FastAPI serializes it as JSON, quotes included, and Meta's check fails.

## Hash the raw body, not a model

The POST takes a `Request` instead of a Pydantic model. FastAPI's docs say that if you read the body from the `Request` directly, "it won't be validated, converted or documented" by FastAPI ([FastAPI using the Request directly](https://fastapi.tiangolo.com/advanced/using-request-directly/)). A model parses the JSON before your code runs, and a hash of the re-serialized object can differ from what Meta signed. [The signature verification guide](/academy/articles/whatsapp-webhook-signature-verification-x-hub-signature-256/) shows how accents and emoji break it.

`await request.body()` returns "The request body as bytes" ([Starlette requests](https://starlette.dev/requests/)). If you switch to `request.stream()` instead, "Any subsequent calls to `.body()`, `.form()`, or `.json()` will raise an error." Don't mix the two in one handler.

The signature header comes in through `Header()`, which converts "underscore (`_`) to hyphen (`-`)" in the parameter name ([FastAPI header parameters](https://fastapi.tiangolo.com/tutorial/header-params/)). So `x_hub_signature_256` reads `X-Hub-Signature-256`, in any letter case.

`hmac.compare_digest` requires both arguments to be the same type, and a `str` argument must be ASCII only ([Python hmac](https://docs.python.org/3/library/hmac.html)). A forged header can carry non-ASCII text, so `valid_signature` encodes both sides to bytes first. A bad header then returns 401 instead of raising a `TypeError` and a 500. Different lengths are fine and need no guard.

## Return 200 first with BackgroundTasks

FastAPI lets you "define background tasks to be run _after_ returning a response" ([FastAPI background tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/)). The task "can be an `async def` or normal `def` function". The 200 to Meta goes out before `process()` touches your database or AI step. A slow or failing step can't turn into a non-200 and a retry.

The route returns a `Response` object, and the tasks still run. The docs page doesn't say so, but `get_request_handler` in [fastapi/routing.py](https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py) checks `isinstance(raw_response, Response)`. When `raw_response.background is None`, it sets it to the route's background tasks. The background tasks page doesn't say what happens to an exception raised inside a task, so `handle()` wraps `process()` and prints the traceback.

BackgroundTasks run in the same process. If it dies after the 200, the payload is gone. Meta retries only non-200 deliveries. Its endpoint guide says there is no API to fetch past webhook data, so store payloads as they arrive ([Meta create a webhook endpoint, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint)). FastAPI's own docs point to "bigger tools like Celery" with "a message/job queue manager" for work across processes and servers. [Webhook queue architecture](/academy/articles/whatsapp-webhook-queue-architecture-workers/) covers writing the raw bytes to a queue before the 200.

## Parse senders with the BSUID fallback

The envelope, the status values and the 1,000-update batches are the same as in [the Express guide](/academy/articles/whatsapp-webhook-nodejs-express-receive-messages/). One field changed. Meta's business-scoped user ID page says `messages[].from` "Will be omitted if the phone number cannot be included" ([Meta business-scoped user IDs, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids)). The new `from_user_id` field is "set to the user's BSUID". The server reads `msg.get("from") or msg.get("from_user_id")`, so a message without a phone number still gets a sender.

Statuses follow the same rule. `recipient_id` is set to the phone number "if you sent the message to the user's phone number", while `recipient_user_id` "Will always be set to the user's BSUID". Meta's text webhook sample still shows only `from` and `wa_id`. If your contact table is keyed on phone numbers, read [business-scoped user IDs](/academy/articles/whatsapp-usernames-business-scoped-user-ids/) before you rely on `from`.

Dedupe keys are `msg:<id>` for messages and `status:<id>:<status>` for statuses. The in-memory set is lost on restart, and each Uvicorn worker process keeps its own copy. In production, let a unique index in your database decide what's new. Arrival order isn't guaranteed either; [out-of-order webhooks](/academy/articles/whatsapp-webhooks-out-of-order-message-sequencing/) covers sequencing.

## Test it locally

Check the GET first. It should print `123`:

```bash
curl "http://localhost:8000/webhook?hub.mode=subscribe&hub.verify_token=$VERIFY_TOKEN&hub.challenge=123"
```

Then send Meta's text webhook sample, compacted to one line and signed with your app secret. This is the same test as in the Express guide, pointed at port 8000:

```bash
cat > sample.json <<'EOF'
{"object":"whatsapp_business_account","entry":[{"id":"102290129340398","changes":[{"value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"15550783881","phone_number_id":"106540352242922"},"contacts":[{"profile":{"name":"Sheena Nelson"},"wa_id":"16505551234"}],"messages":[{"from":"16505551234","id":"wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQTRBNjU5OUFFRTAzODEwMTQ0RgA=","timestamp":"1749416383","type":"text","text":{"body":"Does it come in another color?"}}]},"field":"messages"}]}]}
EOF
SIG=$(openssl dgst -sha256 -hmac "$APP_SECRET" sample.json | awk '{print $NF}')
curl -i -X POST http://localhost:8000/webhook \
  -H "Content-Type: application/json" \
  -H "X-Hub-Signature-256: sha256=$SIG" \
  --data-binary @sample.json
```

The first run returns 200 and Uvicorn's console shows the message line. A second run returns 200 and prints nothing, because the ID is already in the set. Edit one character of `sample.json` without re-signing, then rerun only the `curl` command. The server returns 401. To exercise the fallback, rename `"from"` to `"from_user_id"` in the file and change the message ID. Then rerun the `SIG=` line and the `curl` command.

*Z-API Omni team*
