# Z-API Omni quickstart in Python: send and receive with FastAPI

> Send a WhatsApp text through the Z-API Omni API with urllib and verify signed webhooks in FastAPI: five-field HMAC, gzip, 300 s window and dedupe.

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

To send and receive messages with Z-API Omni in Python, you need one file and three values: a Secret Key, a channel ID and a webhook secret. The FastAPI file sends a TEXT message with `POST /v1/channels/{channelId}/messages` through `urllib.request`. It receives webhooks with `await request.body()` and decompresses gzip itself, because FastAPI doesn't. It needs Python 3.10 or later and FastAPI.

## Set up the workspace

FastAPI's tutorial installs with `pip install "fastapi[standard]"` inside a virtual environment and runs the app with `fastapi dev` ([FastAPI tutorial](https://fastapi.tiangolo.com/tutorial/), accessed 2026-11-05). The file uses `str | None` hints, as Omni's own Python sample does, so it needs Python 3.10 or later.

```bash
python3 -m venv .venv
source .venv/bin/activate
pip install "fastapi[standard]"
```

### Generate the Secret Key

In the dashboard at app.omni.z-api.io, open the Security menu and generate a Secret Key. It authenticates every API call as a Bearer token and must stay on your backend ([Omni authentication](https://developer.omni.z-api.io/en/authentication), accessed 2026-11-05). Don't confuse it with the Public Key, which is for the channel-connection SDK.

### Create and connect a channel

Create the channel by API so you get its ID back. The body uses the example values from the create-channel page.

```bash
export OMNI_SECRET_KEY="YOUR_SECRET_KEY"
curl -s -X POST https://api.omni.z-api.io/v1/channels \
  -H "Authorization: Bearer $OMNI_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "My WhatsApp channel", "type": "META_WHATSAPP"}'
```
<!-- TODO:test Omni: POST /v1/channels returns 201 with id and token; a repeated name returns 409 channel_name_in_use -->

A 201 returns `id`, the channelId every later call uses, and a `token` ([Omni create channel](https://developer.omni.z-api.io/en/channels/create-channel), accessed 2026-11-05). A 409 with `"error": "channel_name_in_use"` means the name is taken. Keep the `id`, because listing or reading channels requires the ENTERPRISE role. Then connect it to your number in the dashboard ("via dashboard or SDK", per the page).

### Register a signed webhook

This is the "With HMAC signature" example from the create-webhook page, with the URL replaced by a placeholder.

```bash
export OMNI_CHANNEL_ID="YOUR_CHANNEL_ID"
curl -s -X POST "https://api.omni.z-api.io/v1/channels/$OMNI_CHANNEL_ID/webhooks" \
  -H "Authorization: Bearer $OMNI_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://YOUR_DOMAIN/webhooks/omni", "events": ["MESSAGE_RECEIVED", "MESSAGE_STATUS"], "signing": true}'
```
<!-- TODO:test Omni: POST /v1/channels/{channelId}/webhooks with signing true returns 201 with a 64-character hex secret -->

Save the 64-hex `secret` from the 201 as `OMNI_WEBHOOK_SECRET` now, since "it will not be shown again in any other call" ([Omni create webhook](https://developer.omni.z-api.io/en/webhooks/create-webhook), accessed 2026-11-05). Each `PATCH` with `signing: true` issues a new secret and invalidates the old one ([Omni HMAC signing](https://developer.omni.z-api.io/en/webhooks/signature)). Leave `signing` out of a PATCH unless you mean to rotate.

### Give the webhook a public URL

Omni answers 400 to `localhost`, `.localhost`, `.internal`, dotless names, non-public IPs and hosts missing from DNS ([Omni webhooks introduction](https://developer.omni.z-api.io/en/webhooks/introduction), accessed 2026-11-05). Run the app on a public host, or put a tunnel in front of port 8000 as in [the local webhook testing guide](/academy/articles/whatsapp-webhook-local-testing-ngrok/).

## The full file

```python
# omni_quickstart.py
#   python omni_quickstart.py selftest
#   python omni_quickstart.py send 5511999999999 "Hello!"
#   fastapi dev omni_quickstart.py
import gzip
import hashlib
import hmac
import json
import os
import re
import sys
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request
import zlib

from fastapi import BackgroundTasks, FastAPI, Request, Response

API_BASE = os.environ.get("OMNI_API_BASE", "https://api.omni.z-api.io")
TOLERANCE_SECONDS = 300
KEEP_SECONDS = 24 * 60 * 60

def send_text(phone: str, text: str) -> str:
    secret_key = os.environ.get("OMNI_SECRET_KEY")
    channel_id = os.environ.get("OMNI_CHANNEL_ID")
    if not secret_key or not channel_id:
        raise RuntimeError("Set OMNI_SECRET_KEY and OMNI_CHANNEL_ID")
    body = {"recipient": {"identifier": phone}, "content": {"type": "TEXT", "body": {"message": text}}}
    req = urllib.request.Request(
        f"{API_BASE}/v1/channels/{urllib.parse.quote(channel_id, safe='')}/messages",
        data=json.dumps(body).encode(),
        method="POST",
        headers={"Authorization": f"Bearer {secret_key}", "Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            return json.loads(resp.read())["messageId"]
    except urllib.error.HTTPError as err:
        raw = err.read().decode("utf-8", "replace")
        try:
            data = json.loads(raw)
        except ValueError:
            data = None
        if err.code == 422 and isinstance(data, dict) and data.get("subCode") == "CHANNEL_DISCONNECTED":
            raise RuntimeError("Channel disconnected: reconnect it in the dashboard, then send again") from None
        raise RuntimeError(f"Send refused: HTTP {err.code} {raw}") from None

def verify_signature(
    secret: str,
    body: bytes,
    signature_header: str | None,
    idempotency_key: str | None,
    now: int | None = None,
) -> str | None:
    """Return None when the request is valid, or the reason it is not."""
    if not signature_header or not idempotency_key:
        return "missing headers"
    parts = {}
    for pair in signature_header.split(","):
        key, sep, value = pair.partition("=")
        if sep:
            parts[key.strip()] = value.strip()
    t, v1 = parts.get("t", ""), parts.get("v1", "")
    if not re.fullmatch(r"[0-9]{1,12}", t) or not re.fullmatch(r"[0-9a-f]{64}", v1):
        return "malformed signature header"
    pieces = idempotency_key.rsplit(":", 2)
    if len(pieces) != 3:
        return "malformed idempotency key"
    topic, partition, offset = pieces

    canonical = b"\n".join([t.encode(), topic.encode(), partition.encode(), offset.encode(), body])
    expected = hmac.new(secret.encode(), canonical, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, v1):
        return "bad signature"
    if abs((int(time.time()) if now is None else now) - int(t)) > TOLERANCE_SECONDS:
        return "stale timestamp"
    return None

seen: dict[str, float] = {}  # delivery id -> first seen. Demo only: use a unique key in a database.

def first_delivery(delivery_id: str) -> bool:
    now = time.time()
    for old in [k for k, at in seen.items() if now - at > KEEP_SECONDS]:
        del seen[old]
    if delivery_id in seen:
        return False
    seen[delivery_id] = now
    return True

def handle_event(payload) -> None:
    try:
        msg = payload.get("message") if isinstance(payload, dict) else None
        if not isinstance(msg, dict):
            print("event without a message object", flush=True)
            return
        from_me = (msg.get("metadata") or {}).get("from_me")
        if from_me is not False:
            print(f"skip {msg.get('_id')}: from_me is {from_me}", flush=True)
            return
        contents = msg.get("contents") or [{}]
        first = contents[0] if isinstance(contents[0], dict) else {}
        if first.get("type") == "TEXT":
            sender = (msg.get("sender") or {}).get("identifier")
            print(f"text from {sender} on channel {msg.get('channel_id')}: {first.get('message')}", flush=True)
        else:
            print(f"non-text message {msg.get('_id')}", flush=True)
    except Exception:
        traceback.print_exc()

app = FastAPI()

@app.post("/webhooks/omni")
async def omni_webhook(request: Request, background_tasks: BackgroundTasks):
    secret = os.environ.get("OMNI_WEBHOOK_SECRET")
    if not secret:
        print("Set OMNI_WEBHOOK_SECRET", flush=True)
        return Response(status_code=500)  # 5xx is retried: Omni keeps retrying for up to 23 hours while you fix it
    raw = await request.body()
    body = raw
    if request.headers.get("content-encoding") == "gzip":
        try:
            body = gzip.decompress(raw)
        except (OSError, EOFError, zlib.error):
            return Response(status_code=400)
    delivery_id = request.headers.get("x-webhook-delivery-id")
    problem = verify_signature(
        secret, body, request.headers.get("x-webhook-signature"), request.headers.get("x-idempotency-key")
    )
    if problem:
        print(f"rejected delivery {delivery_id or '-'}: {problem}", flush=True)
        return Response(status_code=401)
    try:
        payload = json.loads(body)
    except ValueError:
        return Response(status_code=400)
    if delivery_id and not first_delivery(delivery_id):
        return Response(status_code=200)
    background_tasks.add_task(handle_event, payload)
    return Response(status_code=200)

def self_test() -> bool:
    # Test vector from the HMAC signing page of the Omni docs.
    secret = "a7f3c81e9d2b4605f1a8c3e7b9d40f6218273645a8b9c0d1e2f3041526374859"
    body = b'[{"field":"message_template_status_update","identifier":"01A0A4FBC8CD7DCBBBFAA8382F5514A5","type":"TEMPLATE_STATUS","value":{"event":"APPROVED","message_template_category":"UTILITY","message_template_id":"1587155656151346","message_template_language":"pt_BR","message_template_name":"exemplo_teste_assinatura_webhook","reason":"NONE"},"waba_id":"845974408299669"}]'
    signature = "t=1789474359,v1=c9a6812419c87dc26841fd802f1b4704f7dfe868b178ba55f9c432642be67230"
    key = "webhook.delivery.event:0:539402"
    t = 1789474359
    checks = [
        ("doc vector", verify_signature(secret, body, signature, key, t), None),
        ("tampered body", verify_signature(secret, body + b" ", signature, key, t), "bad signature"),
        ("stale t", verify_signature(secret, body, signature, key, t + TOLERANCE_SECONDS + 1), "stale timestamp"),
    ]
    ok = len(body) == 364
    print(f"body length {len(body)} bytes (content-length in the doc: 364)")
    for name, got, want in checks:
        ok = ok and got == want
        print(f"{'PASS' if got == want else 'FAIL'} {name}: {got or 'valid'}")
    return ok

if __name__ == "__main__":
    command = sys.argv[1] if len(sys.argv) > 1 else ""
    if command == "selftest":
        sys.exit(0 if self_test() else 1)
    if command == "send" and len(sys.argv) >= 3:
        try:
            print("accepted, messageId", send_text(sys.argv[2], " ".join(sys.argv[3:]) or "Hello!"))
        except RuntimeError as err:
            sys.exit(str(err))
        sys.exit(0)
    sys.exit("usage: python omni_quickstart.py selftest | send PHONE [TEXT]   (serve: fastapi dev omni_quickstart.py)")
```
<!-- TODO:test Omni: send_text against a live channel, and a real signed delivery (plain and gzip) accepted by /webhooks/omni -->

Set `OMNI_API_BASE` only to point the send at a mock. Run `python omni_quickstart.py selftest` first. It checks the verifier against Omni's signing-page example and prints three PASS lines.

## Verify the signature over five fields

Omni's HMAC covers five fields joined by a bare `\n`: `t`, `topic`, `partition`, `offset` and the raw body ([Omni HMAC signing](https://developer.omni.z-api.io/en/webhooks/signature), accessed 2026-11-05). There is no `\r` and no trailing newline. `t` and `v1` come from `x-webhook-signature: t=...,v1=...`. The other three come from `x-idempotency-key`, formatted `{topic}:{partition}:{offset}`. `rsplit(":", 2)` splits that header on its last two colons only, as Omni's sample does.

`verify_signature` follows Omni's Python sample, with a `now` argument for testing and a reason string for your log. It also rejects a `v1` that isn't 64 lowercase hex characters, so a garbage header gets 401 before `compare_digest` can raise.

### Read the raw body and decompress it yourself

The route takes a `Request`, not a Pydantic model. When 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 would re-serialize the bytes, which Omni's signing page warns breaks the match.

"Requests of 1024 bytes or more are sent with `content-encoding: gzip`", and the HMAC covers the uncompressed bytes. FastAPI's own docs build a `GzipRequest` subclass to decompress request bodies ([FastAPI custom request and route](https://fastapi.tiangolo.com/how-to/custom-request-and-route/)). So the default `Request` hands you compressed bytes. The route calls `gzip.decompress` when the header says `gzip`. Skip that step and small events verify while large ones fail. If a proxy decompresses first and drops the header, the code verifies what it receives, as Omni's page advises.

### Reject stale timestamps

The signing page calls 5 minutes "a reasonable value", and its samples use 300 seconds. The docs don't say whether a retry hours later carries a new `t`. If retries show up in your log as stale, check this first.
<!-- TODO:test Omni: confirm a retried delivery (x-webhook-attempt > 1) carries a fresh t in x-webhook-signature -->

## Return 200 within 5 seconds, then deduplicate

A delivery succeeds only on a 2xx "within 5 seconds" ([Omni delivery and retries](https://developer.omni.z-api.io/en/webhooks/delivery), accessed 2026-11-05). The route queues `handle_event` with `BackgroundTasks`, which runs after the response goes out. See [the FastAPI Cloud API webhook guide](/academy/articles/whatsapp-webhook-python-fastapi-receive-messages/) for how that works with a returned `Response`.

| Your response | What Omni does |
|---|---|
| 2xx within 5 s | Delivered, no retry |
| No response in 5 s, connection error, 408, 429 or 5xx | Sends again after 1 min, 5 min, 30 min, 2 h, 6 h and 12 h |
| Any other 4xx, or 3xx | No retry |

That is up to 7 attempts within 23 hours. Meta's equivalent is in [webhook retries when the endpoint is down](/academy/articles/whatsapp-webhook-retries-endpoint-down/). A failed signature returns 401, which is never retried. A bug in your verifier drops real events for good, so watch the `rejected delivery` lines.

Keep processed `x-webhook-delivery-id` values "for at least 24 hours", as the delivery page says. The `seen` dict is lost on restart, and each worker process keeps its own copy. In production, a unique key in your database decides what's new ([duplicate webhooks and idempotency](/academy/articles/n8n-duplicate-webhooks-idempotency/)).

`BackgroundTasks` run in the same process, so an event is gone if it dies after the 200. Write the body to a queue or table first if you can't lose it ([webhook queue architecture](/academy/articles/whatsapp-webhook-queue-architecture-workers/)). Order isn't guaranteed either: sort by `moment` and never move a status backward.

## Read the message text

The default format wraps every event in a `message` object plus `messageEventType`. That field is "currently `NEW_MESSAGE` for all message events" ([Omni payload structure](https://developer.omni.z-api.io/en/webhooks/payloads), accessed 2026-11-05). Text sits in `message.contents[0].message` when `contents[0].type` is `TEXT`. `metadata.from_me` is "`true` when sent by the business; `false` when received from the contact".

The page's only TEXT sample is an API send with `from_me: true`, and the payloads page shows no inbound or status sample. So `handle_event` prints text only when `from_me` is `False` and logs the rest without guessing at fields.

## Send a message and read the errors

This is the request body from Omni's send-text page, with the message string changed to `Hello!`.

```json
{
  "recipient": { "identifier": "5511999999999" },
  "content": {
    "type": "TEXT",
    "body": { "message": "Hello!" }
  }
}
```

```bash
export OMNI_SECRET_KEY="YOUR_SECRET_KEY"
export OMNI_CHANNEL_ID="YOUR_CHANNEL_ID"
python omni_quickstart.py send 5511999999999 "Hello!"
```
<!-- TODO:test Omni: send TEXT returns 200 with messageId; a disconnected channel returns 422 BUSINESS_RULE_VIOLATION / CHANNEL_DISCONNECTED -->

A 200 returns `messageId`, a 32-character uppercase hex string ([Omni send text](https://developer.omni.z-api.io/en/messages/send-text), accessed 2026-11-05). That means the API accepted the message. Status updates arrive later as `MESSAGE_STATUS` events; add `MESSAGE_DELIVERY` to `events` for delivery confirmations. `urllib` raises `HTTPError` on a 4xx or 5xx, and `send_text` branches on its `code` and `subCode`, because the `message` text "may change".

| Status | `code` / `subCode` | Meaning |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The body does not fit the content type |
| 401 | `"error": 401` | Invalid or missing Secret Key |
| 422 | `BUSINESS_RULE_VIOLATION` / `CHANNEL_DISCONNECTED` | Not sent and not kept: reconnect, then send again |
| 422 | `BUSINESS_RULE_VIOLATION`, no `subCode` | Another send rule refused it; the reason is in `message` |
| 502 | varies | A failure on Omni's side |

The rows come from Omni's [send errors table](https://developer.omni.z-api.io/en/messages/introduction) (accessed 2026-11-05). On WhatsApp, free-form text needs an open 24-hour window; outside it you send a `TEMPLATE`. With IP restriction on, a call from an unlisted IP gets a 400 ([Omni IP restriction](https://developer.omni.z-api.io/en/security/ip-restriction), accessed 2026-11-05).

## Test the receiver locally

Sign a request yourself and post it to `localhost`. Start the app with the webhook secret, and export the same value in the terminal you test from.

```bash
export OMNI_WEBHOOK_SECRET="YOUR_WEBHOOK_SECRET"
fastapi dev omni_quickstart.py
```

The sample is the TEXT payload from Omni's payloads page, compacted to one line. The `sed` copy flips `from_me` to `false` so the inbound branch runs. Every request is gzipped, so the decompress path runs too.

```bash
cat > sample.json <<'EOF'
{"message":{"_id":"019E6F1A93FE78DCB54332F9FF0CCAE7","tenant":"019DCEB3E93B7077B2447616B6DC8B91","tenant_owner":"email@z-api.io","channel_id":"019E4C54B1B375A28970B605CA9B03C3","created_by":"BARLING","created":1779980473342,"metadata":{"@class":".Metadata","forwarded":false,"from_api":true,"from_me":true,"middleware":"META_WHATSAPP","moment":1779980473342},"sender":{"@class":".Sender","identifier":"BARLING_SYSTEM","name":"Barling System"},"recipient":{"@class":".Recipient","identifier":"5544936181064","name":"5544936181064"},"contents":[{"@class":".TextContent","identifier":"019E6F1A93FE78DCB542303FF18D389A","internal_information":{},"message":"Hello! We have incredible news waiting for you.","state_items":[{"@class":".StateItem","identifier":"019E6F1A93FE78DCB5418E8D9D007FFB","integration_message_ids":[],"moment":1779980473342,"state":{"@class":".Pending","name":"PENDING"}}],"type":"TEXT"}],"attachments":[],"actions":[],"webhook_processed":false},"messageEventType":"NEW_MESSAGE"}
EOF
sed 's/"from_me":true/"from_me":false/' sample.json > inbound.json

post_signed() { # FILE OFFSET URL
  T=$(date +%s)
  SIG=$( { printf '%s\nwebhook.delivery.event\n0\n%s\n' "$T" "$2"; cat "$1"; } \
    | openssl dgst -sha256 -hmac "$OMNI_WEBHOOK_SECRET" | awk '{print $NF}')
  gzip -c "$1" | curl -s -o /dev/null -w '%{http_code}\n' -X POST "$3" \
    -H 'content-type: application/json' -H 'content-encoding: gzip' \
    -H "x-idempotency-key: webhook.delivery.event:0:$2" \
    -H "x-webhook-signature: t=$T,v1=$SIG" \
    -H "x-webhook-delivery-id: test-$2" -H 'x-webhook-attempt: 1' \
    --data-binary @-
}

post_signed sample.json 1 http://localhost:8000/webhooks/omni
post_signed inbound.json 2 http://localhost:8000/webhooks/omni
post_signed inbound.json 2 http://localhost:8000/webhooks/omni
```

All three requests print `200`. The console shows `skip ... from_me is True` for the first and the text line for the second. The third reuses delivery ID `test-2` and prints nothing. Export a different secret in the test terminal only and the app answers 401 with `bad signature`.

## How this differs from Meta's raw webhook

Meta signs the body alone with your app secret in `X-Hub-Signature-256`. Its envelope is `entry[].changes[].value`, as [the FastAPI Cloud API webhook guide](/academy/articles/whatsapp-webhook-python-fastapi-receive-messages/) shows. Omni signs five fields with a secret per webhook, adds a timestamp and sends a delivery ID for dedupe. Its body is Omni's own `message` envelope, or the `Z_API` or `CHATWOOT` format if you set `payloadFormat`. The webhook pages describe no GET challenge step; you register the URL with an API call.

The same receiver is in [the Express quickstart](/academy/articles/z-api-omni-quickstart-nodejs-express/) and [the PHP quickstart](/academy/articles/z-api-omni-quickstart-php/). One Omni subscription covers WhatsApp, Messenger, Instagram and Telegram, with webhooks included without limit. [View documentation](https://developer.omni.z-api.io/en)

*Z-API Omni team*
