Receiving WhatsApp messages (zap-api)¶
The WhatsApp (zap-api) recipe covers the outbound side:
sending and getting a 202 back. This one covers the other side — the
gateway POSTing to your service when a message arrives and when one you
sent changes status.
You will build the receiver in four steps, each one a complete program that runs:
- The ready route — a route that receives the message and answers
401to whatever did not come from the gateway, built by one line. - The enums — dispatching on event, media and address type without comparing against a loose string.
- The router with
ZapInbox—make_zap_inbox_routerwires the two tables (ZapInboundMessageMixin/ZapDeliveryMixin) toZapInbox, stores each message once, never regresses a status and runson_replyinBackgroundTaskson an independent session of its own. - The test — deliveries signed the way the gateway signs, with no gateway running.
Register the webhook on the gateway¶
Registration is a gateway admin operation, not something your service does. One URL receives both kinds of event:
npm run webhook:set -- my-bot https://my-bot.test/webhooks/zap \
--secret my-secret --events status,inbound
--events takes status (the delivery lifecycle of what this consumer
sent), inbound (every message that arrives) or both. Without the flag the
default is status only.
Without --secret, the gateway delivers unsigned
The gateway signs only when the webhook has a secret — without one it
POSTs with no x-zap-signature header. That is why
make_zap_webhook_dependency refuses to be built without a
non-empty secret: with it, an unsigned delivery is always 401.
Step 1 — The ready-made route¶
The ready route: one POST, the signature checked, the body validated into the
right model, dispatch by event, and a 200 answer.
from fastapi import FastAPI
from tempest_fastapi_sdk.integrations.messaging.zap import (
ZapInboundMessage,
make_zap_webhook_router,
)
app: FastAPI = FastAPI()
async def on_message(message: ZapInboundMessage) -> None:
"""Print the messages that arrive.
Args:
message (ZapInboundMessage): The delivery, signature already checked
and body already validated.
"""
print(f"{message.push_name}: {message.text}")
app.include_router(
make_zap_webhook_router(secret="my-secret", on_inbound=on_message)
)
Three pieces:
make_zap_webhook_router(secret=..., on_inbound=...)builds the whole route and returns anAPIRouterlike any other.on_messagereceives the delivery already validated: aZapInboundMessageformessage.received, aZapStatusCallbackfor the four status events. The latter goes inon_status.- The answer is
200once the handler returns, with the event name echoed back —{"ok": true, "event": "message.received"}, aZapWebhookAckSchema.
The parameters the route takes:
| Parameter | Default | What it does |
|---|---|---|
secret |
— | The secret registered on the gateway. Required without verify, and never empty. |
verify |
— | A dependency of your own, for when the secret is not enough: rotation, two secrets, a secret coming from your settings. |
on_inbound |
None |
Called with the ZapInboundMessage of message.received. |
on_status |
None |
Called with the ZapStatusCallback of message.sent, .delivered, .read and .failed. |
path |
"/webhooks/zap" |
Where the route lands. |
tags |
["zap"] |
The tags in the OpenAPI document. |
include_in_schema |
True |
False hides the route from OpenAPI without unmounting it. |
Without secret and without verify, the route is not built
The gateway signs only when the webhook was registered with --secret —
without one it POSTs with no x-zap-signature header. The factory
raises ValueError in that case, instead of building a route that
would accept any POST. And an unsigned delivery is 401, always.
A handler that raises becomes a 500, and the gateway redelivers
The ready route does not swallow your handler's exception: it
propagates, the answer becomes 500, and the gateway re-POSTs the same
bytes with backoff (3 attempts by default). That is what you want for a
transient failure — database down, lock held — and what you do not want
for a body that will never get through: handle that inside the handler and
answer 200. An event with no handler, or an event the gateway invents
later, is already a 200 with a debug log.
Under the hood: the route the factory builds¶
The same route, written by hand
When you need the envelope — or when the route lives inside your service, with its own controller and dependencies — the manual route is exactly this:
from fastapi import Depends, FastAPI
from tempest_fastapi_sdk.integrations.messaging.zap import (
ZapWebhookDelivery,
make_zap_webhook_dependency,
)
app: FastAPI = FastAPI()
verify_zap = make_zap_webhook_dependency(secret="my-secret")
@app.post("/webhooks/zap", include_in_schema=False)
async def receive_zap(
delivery: ZapWebhookDelivery = Depends(verify_zap),
) -> dict[str, str]:
"""Receive every gateway delivery and print the incoming messages.
Args:
delivery (ZapWebhookDelivery): The delivery, signature already
checked and body already validated.
Returns:
dict[str, str]: Always ``200``, so the gateway does not redeliver.
"""
if delivery.inbound is not None:
print(f"{delivery.inbound.push_name}: {delivery.inbound.text}")
return {"status": "ok"}
The difference is in the body: the factory dispatches on event and
answers on its own, with the event name echoed. Yours does whatever you
want after receiving the ZapWebhookDelivery — and it can still use
Depends(verify_zap), which is the same dependency the factory builds for
you.
What the dependency handles for you¶
The signature travels in the x-zap-signature header, HMAC-SHA256 in hex
with a sha256= prefix, computed over the raw body before any parsing
and compared with hmac.compare_digest. The two classic mistakes become
impossible: verifying over re-serialized JSON (which changes whitespace and
key order) and comparing with ==. A header without the sha256= prefix is
also 401, even with the right hex.
Answer 2xx to everything that passed the signature
The gateway treats any non-2xx answer as a failure and redelivers with
backoff, up to CALLBACK_MAX_ATTEMPTS attempts (3 by default). A 422
for a new event protects nothing: it only produces attempts, and the
gateway gives up on the delivery in the end. That is why the route does
not fail on a body it does not recognize — it answers 200 with the
event name and logs at debug (see step 2).
To see it work without the gateway, sign the body with sign_zap_webhook
(HMAC-SHA256 of the raw body, hex, sha256= prefix) and send it through the
TestClient. The body is the inbound example from the gateway's README:
from fastapi.testclient import TestClient
from tempest_fastapi_sdk.integrations.messaging.zap import (
ZAP_WEBHOOK_SIGNATURE_HEADER,
)
from tempest_fastapi_sdk.testing.fakes import sign_zap_webhook
from zap_minimal import app
SECRET: str = "my-secret"
BODY: bytes = (
'{"event":"message.received","messageId":"ABCD1234",'
'"from":"5511999999999@s.whatsapp.net","chatKey":"5511999999999",'
'"pushName":"Fulano","text":"Hello!","mediaType":null,"mediaUrl":null,'
'"timestamp":"2026-04-21T18:30:00.000Z"}'
).encode()
client: TestClient = TestClient(app)
signed = client.post(
"/webhooks/zap",
content=BODY,
headers={ZAP_WEBHOOK_SIGNATURE_HEADER: sign_zap_webhook(BODY, SECRET)},
)
print(signed.status_code, signed.json())
unsigned = client.post("/webhooks/zap", content=BODY)
print(unsigned.status_code, unsigned.json())
$ python simulate.py
Fulano: Hello!
200 {'ok': True, 'event': 'message.received'}
401 {'detail': 'Invalid zap-api webhook signature'}
Step 2 — Dispatch by type with the enums¶
Every value the gateway sends as a string has an enum in the SDK. They are
all StrEnum: a member equals its wire string, so code that already
compares against "audio" keeps working — the enum adds autocompletion, type
checking and one place to read what exists.
| Enum | Where it shows up | Values |
|---|---|---|
ZapWebhookEventEnum |
delivery.event |
MESSAGE_RECEIVED, MESSAGE_SENT, MESSAGE_DELIVERED, MESSAGE_READ, MESSAGE_FAILED |
ZapInboundMediaTypeEnum |
message.media_type |
IMAGE, VIDEO, AUDIO, DOCUMENT, STICKER (None is plain text) |
ZapJidServerEnum |
message.from_server |
USER, LID, GROUP, BROADCAST, NEWSLETTER and five more from Baileys |
ZapOutboundKindEnum |
callback.kind |
TEXT, IMAGE, VIDEO, AUDIO, DOCUMENT, REACTION |
AcceptedResponseStatus |
callback.status |
SENT, DELIVERED, READ, FAILED (plus QUEUED and SENDING, which never reach the webhook) |
Step 1 dispatched for you; here the route is yours again, because event is
what picks the path and it lives on ZapWebhookDelivery — the factory hands
the handler only the body (ZapInboundMessage or ZapStatusCallback), already
opened on the right model. To use the factory with these functions, wrap each
in an async def ... -> None handler and pass it as on_inbound /
on_status: they are synchronous and return str, and the factory awaits the
handler.
from fastapi import Depends, FastAPI
from tempest_fastapi_sdk.integrations.messaging.zap import (
AcceptedResponseStatus,
ZapInboundMediaTypeEnum,
ZapInboundMessage,
ZapJidServerEnum,
ZapOutboundKindEnum,
ZapStatusCallback,
ZapWebhookDelivery,
make_zap_webhook_dependency,
)
app: FastAPI = FastAPI()
verify_zap = make_zap_webhook_dependency(secret="my-secret")
def describe_inbound(message: ZapInboundMessage) -> str:
"""Decide what to do with an incoming message, looking only at enums.
Args:
message (ZapInboundMessage): The validated message.
Returns:
str: A label for the chosen path.
"""
if message.from_server is ZapJidServerEnum.BROADCAST:
return "ignore: status story"
if message.from_server is ZapJidServerEnum.GROUP:
return f"group: {message.text}"
match message.media_type:
case None:
return f"text: {message.text}"
case ZapInboundMediaTypeEnum.AUDIO:
return "audio: transcribe"
case ZapInboundMediaTypeEnum.IMAGE | ZapInboundMediaTypeEnum.VIDEO:
return f"visual, caption: {message.text}"
case _:
return f"file: {message.media_type}"
def describe_status(callback: ZapStatusCallback) -> str:
"""Decide what to do with a send status, looking only at enums.
Args:
callback (ZapStatusCallback): The validated status.
Returns:
str: A label for the chosen path.
"""
if callback.status == AcceptedResponseStatus.FAILED:
return f"failed: {callback.error}"
if callback.kind == ZapOutboundKindEnum.REACTION:
return "reaction delivered: nothing to show"
return f"{callback.kind} is now {callback.status}"
@app.post("/webhooks/zap", include_in_schema=False)
async def receive_zap(
delivery: ZapWebhookDelivery = Depends(verify_zap),
) -> dict[str, str]:
"""Dispatch each delivery to the handler for its kind.
Args:
delivery (ZapWebhookDelivery): The verified delivery.
Returns:
dict[str, str]: The chosen path, or ``ignored`` for an event the
SDK does not model.
"""
if delivery.inbound is not None:
return {"handled": describe_inbound(delivery.inbound)}
if delivery.status is not None:
return {"handled": describe_status(delivery.status)}
return {"handled": "ignored", "event": delivery.event_name}
Sending one delivery of each kind, signed as in step 1:
import json
from typing import Any
from fastapi.testclient import TestClient
from tempest_fastapi_sdk.integrations.messaging.zap import (
ZAP_WEBHOOK_SIGNATURE_HEADER,
)
from tempest_fastapi_sdk.testing.fakes import sign_zap_webhook
from zap_dispatch import app
SECRET: str = "my-secret"
WHEN: str = "2026-04-21T18:30:00.000Z"
DELIVERIES: list[dict[str, Any]] = [
{
"event": "message.received",
"messageId": "M1",
"text": "Hello!",
"from": "5511999999999@s.whatsapp.net",
"timestamp": WHEN,
},
{
"event": "message.received",
"messageId": "M2",
"mediaType": "audio",
"from": "123456789012345@lid",
"timestamp": WHEN,
},
{
"event": "message.received",
"messageId": "M3",
"text": "good morning",
"from": "120363000000000000@g.us",
"timestamp": WHEN,
},
{
"event": "message.received",
"messageId": "M4",
"mediaType": "image",
"from": "status@broadcast",
"timestamp": WHEN,
},
{
"event": "message.read",
"id": "out-1",
"consumer": "bot",
"kind": "text",
"to": "5511999999999",
"status": "read",
"timestamp": WHEN,
},
{
"event": "message.failed",
"id": "out-2",
"consumer": "bot",
"kind": "image",
"to": "5511999999999",
"status": "failed",
"error": "number not on WhatsApp",
"timestamp": WHEN,
},
{"event": "message.edited", "messageId": "M1", "timestamp": WHEN},
]
client: TestClient = TestClient(app)
for delivery in DELIVERIES:
body: bytes = json.dumps(delivery).encode()
response = client.post(
"/webhooks/zap",
content=body,
headers={ZAP_WEBHOOK_SIGNATURE_HEADER: sign_zap_webhook(body, SECRET)},
)
print(f"{delivery['event']:<17} {response.status_code} {response.json()}")
$ python simulate_dispatch.py
message.received 200 {'handled': 'text: Hello!'}
message.received 200 {'handled': 'audio: transcribe'}
message.received 200 {'handled': 'group: good morning'}
message.received 200 {'handled': 'ignore: status story'}
message.read 200 {'handled': 'text is now read'}
message.failed 200 {'handled': 'failed: number not on WhatsApp'}
message.edited 200 {'handled': 'ignored', 'event': 'message.edited'}
Let's go piece by piece.
Which body arrived: inbound, status or neither¶
The same URL receives message.received and
message.{sent,delivered,read,failed}, with different shapes. The dependency
already returns the validated body in the right field:
delivery.event |
Body in |
|---|---|
ZapWebhookEventEnum.MESSAGE_RECEIVED |
delivery.inbound (ZapInboundMessage) |
MESSAGE_SENT, MESSAGE_DELIVERED, MESSAGE_READ, MESSAGE_FAILED |
delivery.status (ZapStatusCallback) |
None |
neither — log event_name and payload and answer 200 |
event is set only when the matching body validated, so asking
delivery.inbound is not None and delivery.status is not None is the
complete dispatch — and it is the form the type checker understands, because
it narrows the Optional for you. None covers an event this SDK version
does not know (the message.edited above) and a known event whose body does
not match the model.
from_server: what kind of address wrote¶
from_ is the raw JID, <user>@<server>, and the server says whether it is
a person (s.whatsapp.net or lid), a group (g.us), a status story
(status@broadcast) or a channel (newsletter). message.from_server reads
that part and returns the ZapJidServerEnum member — None when there is no
@ or the server is unknown.
The gateway does not filter on the JID's server
The gateway's publishMessage (src/services/whatsapp.service.ts,
commit d0477d8) forwards every notify message with content, without
looking at the remoteJid's server — read in the code, not measured on a
live session. So a status story (status@broadcast) or a channel post
can arrive as message.received, and replying to it, or storing it as a
conversation, is almost never what you want. Filter on from_server.
is for the envelope, == for the body¶
ZapWebhookDelivery is a dataclass, so delivery.event holds the member
itself and delivery.event is ZapWebhookEventEnum.MESSAGE_RECEIVED works.
from_server returns the member too. Inside ZapInboundMessage and
ZapStatusCallback, as in every BaseSchema, enum fields hold the
value — compare with == (or use match, which compares with ==).
callback.kind is str on purpose, not ZapOutboundKindEnum: the gateway
declares it as string, and a send kind it gains later must not turn a
message's status into an event=None delivery. Compare it with the enum
anyway — callback.kind == ZapOutboundKindEnum.REACTION.
Step 3 — ZapInbox ready-made with make_zap_inbox_router¶
So far the rules live in the route. In a real service, storing each message
once, never regressing a status and recording each send once per key are the
same rules for every consumer of the gateway — the SDK ships them as
ZapInbox and wires the whole flow in a single factory:
make_zap_inbox_router.
| Piece | Job here |
|---|---|
| models | two tables, each with a mixin: ZapInboundMessageMixin (UNIQUE on message_id) and ZapDeliveryMixin (UNIQUE on outbound_id) |
make_zap_inbox_router |
verifies the HMAC, calls inbox.claim on message.received and inbox.track on message.{sent,delivered,read,failed}, answers 200 with ZapWebhookResponseSchema and schedules on_reply in BackgroundTasks with a fresh, independent session |
on_reply / should_reply |
the rule that is yours alone — when to answer (default is_replyable) and which message to send through inbox.send_reply |
The file below is complete and typed. The route answers 200 once the
claim commits on the request's session (which closes with
scope="function" before the response goes out), and on_reply then runs
over a ZapInbox bound to a freshly opened session that closes when the task
ends:
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from tempest_fastapi_sdk import AsyncDatabaseManager, BaseModel
from tempest_fastapi_sdk.integrations.messaging.zap import (
ZapClient,
ZapDeliveryMixin,
ZapInboundMessage,
ZapInboundMessageMixin,
ZapInboundOutcomeEnum,
ZapInbox,
is_replyable,
make_zap_inbox_router,
zap_http_client,
)
db: AsyncDatabaseManager = AsyncDatabaseManager("sqlite+aiosqlite:///:memory:")
class ZapMessageModel(ZapInboundMessageMixin, BaseModel):
"""An incoming message, stored only once."""
__tablename__ = "zap_messages"
class ZapDeliveryModel(ZapDeliveryMixin, BaseModel):
"""The last known status of a sent message."""
__tablename__ = "zap_deliveries"
def get_zap_client(request: Request) -> ZapClient:
"""Return the gateway client the lifespan opened.
Args:
request (Request): The current request.
Returns:
ZapClient: The client shared by the application.
"""
client: ZapClient = request.app.state.zap
return client
def allow_captionless(
outcome: ZapInboundOutcomeEnum, message: ZapInboundMessage
) -> bool:
"""Accept freshly stored messages, captionless media included.
Args:
outcome (ZapInboundOutcomeEnum): Outcome of the ``claim``.
message (ZapInboundMessage): The already validated message.
Returns:
bool: ``True`` when ``on_reply`` may be scheduled.
"""
return is_replyable(outcome, message, require_text=False)
async def on_reply(
message: ZapInboundMessage,
inbox: ZapInbox[ZapMessageModel, ZapDeliveryModel],
) -> None:
"""Reply in the background over the independent session the router opened.
Args:
message (ZapInboundMessage): The freshly stored message.
inbox (ZapInbox[ZapMessageModel, ZapDeliveryModel]): Inbox bound to
the background session.
"""
if message.chat_key is not None:
await inbox.send_reply(
message.chat_key,
message.message_id,
"Got it, thanks!",
)
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
"""Create the tables and open the gateway client with the service.
Args:
app (FastAPI): The application.
Yields:
None: While the service is up.
"""
await db.create_tables()
async with zap_http_client(
"http://127.0.0.1:3000",
"<your key>",
) as http:
app.state.zap = ZapClient(http)
yield
await db.disconnect()
app: FastAPI = FastAPI(lifespan=lifespan)
app.include_router(
make_zap_inbox_router(
session_factory=db.session_dependency,
message_model=ZapMessageModel,
delivery_model=ZapDeliveryModel,
client_dependency=get_zap_client,
secret="my-secret",
on_reply=on_reply,
should_reply=allow_captionless,
)
)
create_tables() here is a demo shortcut
The example fits in a single file, so it creates the tables straight
in the lifespan. In a service, the lifespan calls sync_schema_async()
over the Alembic migrations: create_tables() adds no column to a
table that already exists. See
Migrations ».
Running a sequence of deliveries against it with FakeZapClient:
from fastapi.testclient import TestClient
from tempest_fastapi_sdk.integrations.messaging.zap import (
AcceptedResponseStatus,
ZapInboundMediaTypeEnum,
)
from tempest_fastapi_sdk.testing.fakes import (
FakeZapClient,
make_zap_inbound,
make_zap_status,
)
from test_zap_service import post
from zap_service import app, get_zap_client
fake_zap: FakeZapClient = FakeZapClient()
app.dependency_overrides[get_zap_client] = lambda: fake_zap
with TestClient(app) as client:
for label, payload in [
("text", make_zap_inbound(message_id="A1", text="Hi")),
("same delivery", make_zap_inbound(message_id="A1", text="Hi")),
(
"audio",
make_zap_inbound(
message_id="A2",
text=None,
media_type=ZapInboundMediaTypeEnum.AUDIO,
media_url="/message/A2/media",
),
),
(
"lost audio",
make_zap_inbound(
message_id="A3",
chat_key=None,
text=None,
media_type=ZapInboundMediaTypeEnum.AUDIO,
),
),
(
"group",
make_zap_inbound(
message_id="A4",
from_="120363000000000000@g.us",
chat_key=None,
text="good morning",
),
),
("delivered", make_zap_status(id="out-1", status=AcceptedResponseStatus.DELIVERED)),
("late sent", make_zap_status(id="out-1", status=AcceptedResponseStatus.SENT)),
("read", make_zap_status(id="out-1", status=AcceptedResponseStatus.READ)),
("new event", {"event": "message.edited", "messageId": "A1"}),
]:
response = post(client, payload)
print(f"{label:<14} {response.status_code} {response.json()}")
print("sent:", [item.idempotency_key for item in fake_zap.sent])
$ python run_service.py
text 200 {'status': 'stored', 'event': 'message.received'}
same delivery 200 {'status': 'duplicate', 'event': 'message.received'}
audio 200 {'status': 'stored', 'event': 'message.received'}
lost audio 200 {'status': 'media-lost', 'event': 'message.received'}
group 200 {'status': 'skipped', 'event': 'message.received'}
delivered 200 {'status': 'applied', 'event': 'message.delivered'}
late sent 200 {'status': 'stale', 'event': 'message.sent'}
read 200 {'status': 'applied', 'event': 'message.read'}
new event 200 {'status': 'ignored', 'event': 'message.edited'}
sent: ['reply_A1', 'reply_A2']
run_service.py uses the SDK's FakeZapClient, make_zap_inbound and
make_zap_status together with post from step 4. The second delivery also
shows up in the log, as a WARNING from BaseRepository (IntegrityError on
ZapMessageModel.add: unique violation; table=zap_messages;
columns=message_id; ...) — that is the claim working, not an error.
Now each piece.
What make_zap_inbox_router guarantees in the background¶
- An independent session for
on_reply. The request's session dependency is registered throughsession_provider_for(session_factory)withscope="function", so it closes as soon asreceive_zap_inboxreturns the200. TheBackgroundTaskstask calls the same provider (honoringdependency_overridesin tests) to open a new session, builds a newZapInboxover it and closes the session in afinally. - An isolated exception with
message_id. The200has already gone to the gateway whenon_replyruns; any exception raised there is caught and logged withlogger.exception(..., extra={"message_id": message.message_id})without bringing the ASGI server down. session_factorywith no required parameter. The background session is opened outside FastAPI's resolver, by callingsession_factory()with no arguments. Somake_zap_inbox_routerrefuses at construction, with aValueErrornaming the parameter, a factory such asget_session(request: Request)(the message saysrequires 'request'and suggestsdb.session_dependency). Parameters with a default and*args/**kwargspass.- Out of OpenAPI by default.
include_in_schemadefaults toFalseto keep the webhook out of the public docs (passinclude_in_schema=Trueanddocs_locale="en-US"to expose it). Usemake_zap_webhook_routerwhen you need neither a database norZapInbox, or write a manual route withDepends(make_zap_webhook_dependency(...))when you want a controller of your own in between.
What ZapInbox does for you¶
claim: idempotency by messageId. Deliveries go through the gateway's
callback_deliveries queue, with retries: the same message arrives more than
once when your answer is lost, or when the gateway restarts mid-POST. The
UNIQUE on message_id is the claim — the insert of whoever arrives second
hits it and claim returns duplicate. There is no exists before the
insert: two replicas checking at the same time would both see "not there"
and both store. A conflict whose message_id is not stored is not a
duplicate (another constraint on your table refused the row) and is raised.
See Idempotency for the same reasoning on your own routes.
claim: only a person's conversation. accepted_servers defaults to
ZapJidServerEnum.USER and ZapJidServerEnum.LID; groups, broadcasts and channels
come back skipped without being stored. Pass another frozenset to accept
more.
claim and get_message_media: media only through the gateway. The
gateway downloads the media when the message arrives, and WhatsApp does not
serve it again afterwards. claim downloads nothing: it stores the
media_type, and whoever needs the bytes calls
inbox.get_message_media(message_id) (a facade over
client.get_message_media(message_id)). When media_type is set and
media_url is None, the download failed or went over MEDIA_MAX_BYTES: the
row is stored and claim returns media-lost.
track: status out of order, and before the send. Each delivery has its
own retry and backoff, so a sent whose first POST failed can land after
the delivered. And the gateway guards its own row against regression,
but sends the callback anyway. track applies the status only when
is_forward_transition(current, new) says it moves forward:
- the ladder is
queued < sending < sent < delivered < read; - repeating the current status, or stepping down the ladder, is not forward;
failedis terminal — nothing overwrites it —, and it only overwritesqueued,sendingandsent, becausedeliveredandreadalready prove the message arrived; the callback'serrorgoes to theerrorcolumn.
The row is keyed by the callback's id — the outbox row the send's 202
returned — and is created when it does not exist: the gateway can call
back before the send was committed, and answering 404 would only spend its
retries.
send_text: one record per key. The send stores the delivery row with
the 202's id and the idempotency_key. On a re-delivery, the same key
makes the gateway answer deduped=True, and send_text finds the row by the
key instead of creating another. If track already created the row from a
callback, send_text only attaches the key — and never steps the status
down. A 202 that is already failed raises ZapSendFailedException
(502, code="ZAP_SEND_FAILED") and records nothing.
The commit belongs to BaseRepository, not to the session
db.session_dependency does not commit at the end of the request.
Every ZapInbox write goes through BaseRepository.add or update,
which commit. Changing a row's attribute without calling update looks
like it works in a test and stores nothing.
Why text is Text and nullable
A media message without a caption arrives without text, and a WhatsApp
message has no 255-character ceiling. ZapInboundMessageMixin declares
text as a nullable Text. A required String(255) column refuses the
captionless media on any database, and the long text on PostgreSQL —
SQLite ignores the declared length and stores it all, so an in-memory
test does not show it.
Your service: the reply and standard schemas¶
is_replyable(outcome, message, *, require_text=True) decides whether a
claimed message can be answered: it requires outcome in REPLYABLE_OUTCOMES
(stored or media-lost), a resolved message.chat_key and, by default,
non-empty message.text. Pass require_text=False to also reply to
captionless media (audio, images). send_reply(chat_key, message_id, text, *,
key_prefix="reply_") quotes reply_to=message_id, computes
idempotency_key=f"{key_prefix}{message_id}" and rejects raw JIDs containing
"@" (@lid, @s.whatsapp.net) with ValueError before touching the
gateway.
chatKey, not from. from_ is the raw address, and the same person
can arrive through a number and later through a LID — grouping by from_
splits one conversation in two. chat_key is the number's digits, already
resolved by the gateway from the LID; it is also the to that send_text and
send_reply accept. It is None for a LID the gateway could not map —
claim stores it and is_replyable returns False.
Standard response schemas. Alongside ZapWebhookResponseSchema (status:
ZapWebhookOutcome, event: str | None = None), the package ships
ZapInboundMessageResponseSchema (mirroring ZapInboundMessageMixin) and
ZapDeliveryResponseSchema (mirroring ZapDeliveryMixin), ready for
model_validate(row) in query or listing routes.
Where each piece lives in your service¶
The single file is there so the example runs. In the Tempest service layout,
the models go to src/db/models/zap.py, get_zap_client to
src/api/dependencies/services.py, the on_reply handler to
src/services/zap_bot.py, and make_zap_inbox_router(...) is mounted
straight in src/server.py (or in src/api/routers/webhooks.py). When the
route needs a controller of its own with more synchronous steps, keep using
Depends(make_zap_webhook_dependency(...)) over the same ZapInbox.
Why the ZapClient is born in the lifespan
A closed HTTPClient does not reopen. Created at module level, it
survives a single lifespan: the suite's second TestClient(app) finds
the client closed and fails with RuntimeError: Cannot send a request, as
the client has been closed. Created inside the lifespan with
zap_http_client(**settings.zap_http_kwargs()) over ZapSettings, every
start-up of the application gets its own.
Step 4 — Testing without the gateway¶
Use FakeZapClient, sign_zap_webhook, make_zap_inbound and
make_zap_status from tempest_fastapi_sdk.testing.fakes (also re-exported
from tempest_fastapi_sdk.testing) instead of hand-writing
httpx.MockTransport, HMAC headers and raw dicts. FakeZapClient subclasses
ZapClient, deduplicates on idempotency_key, records accepted sends in
sent and serves media from media. The fixture opens TestClient as a
context manager so the lifespan runs and overrides get_zap_client per test.
import json
from collections.abc import Iterator
from typing import Any
import httpx
import pytest
from fastapi.testclient import TestClient
from tempest_fastapi_sdk.integrations.messaging.zap import (
ZAP_WEBHOOK_SIGNATURE_HEADER,
AcceptedResponseStatus,
ZapInboundMediaTypeEnum,
ZapInboundMessage,
ZapStatusCallback,
)
from tempest_fastapi_sdk.testing.fakes import (
FakeZapClient,
make_zap_inbound,
make_zap_status,
sign_zap_webhook,
)
from zap_service import app, get_zap_client
SECRET: str = "my-secret"
def post(
client: TestClient,
payload: ZapInboundMessage | ZapStatusCallback | dict[str, Any],
secret: str = SECRET,
) -> httpx.Response:
"""Sign and deliver a body, like the gateway's callback worker.
Args:
client (TestClient): The application's client.
payload (ZapInboundMessage | ZapStatusCallback | dict[str, Any]): The body.
secret (str): The secret to sign with.
Returns:
httpx.Response: The route's response.
"""
body: bytes = (
payload.model_dump_json(by_alias=True).encode()
if isinstance(payload, (ZapInboundMessage, ZapStatusCallback))
else json.dumps(payload).encode()
)
return client.post(
"/webhooks/zap",
content=body,
headers={ZAP_WEBHOOK_SIGNATURE_HEADER: sign_zap_webhook(body, secret)},
)
@pytest.fixture
def fake_zap() -> FakeZapClient:
"""Provide a clean in-memory client per test.
Returns:
FakeZapClient: The fake gateway client.
"""
return FakeZapClient()
@pytest.fixture
def client(fake_zap: FakeZapClient) -> Iterator[TestClient]:
"""Start the application with its lifespan and inject ``FakeZapClient``.
Args:
fake_zap (FakeZapClient): In-memory client for this test.
Yields:
TestClient: The application's client.
"""
app.dependency_overrides[get_zap_client] = lambda: fake_zap
try:
with TestClient(app) as test_client:
yield test_client
finally:
app.dependency_overrides.clear()
def test_wrong_secret_is_401(client: TestClient) -> None:
"""A delivery signed with another secret is refused."""
response = post(client, make_zap_inbound(message_id="A1"), "other")
assert response.status_code == 401
def test_message_is_stored_once(
client: TestClient, fake_zap: FakeZapClient
) -> None:
"""The gateway's redelivery becomes ``duplicate`` and sends only one reply."""
payload = make_zap_inbound(message_id="A2", text="Hi")
assert post(client, payload).json() == {
"status": "stored",
"event": "message.received",
}
assert post(client, payload).json() == {
"status": "duplicate",
"event": "message.received",
}
assert len(fake_zap.sent) == 1
assert fake_zap.sent[0].idempotency_key == "reply_A2"
def test_group_is_skipped(client: TestClient, fake_zap: FakeZapClient) -> None:
"""A group message is neither stored nor answered."""
payload = make_zap_inbound(
message_id="A3",
from_="120363000000000000@g.us",
chat_key=None,
text="good morning",
)
assert post(client, payload).json() == {
"status": "skipped",
"event": "message.received",
}
assert fake_zap.sent == []
def test_lost_media(client: TestClient) -> None:
"""``mediaType`` without ``mediaUrl`` is lost media."""
payload = make_zap_inbound(
message_id="A4",
text=None,
media_type=ZapInboundMediaTypeEnum.AUDIO,
)
assert post(client, payload).json() == {
"status": "media-lost",
"event": "message.received",
}
def test_late_status_is_stale(client: TestClient) -> None:
"""A ``delivered`` after the ``read`` does not move the status back."""
assert post(
client, make_zap_status(id="out-9", status=AcceptedResponseStatus.READ)
).json() == {"status": "applied", "event": "message.read"}
assert post(
client, make_zap_status(id="out-9", status=AcceptedResponseStatus.DELIVERED)
).json() == {"status": "stale", "event": "message.delivered"}
def test_unknown_event_is_200(client: TestClient) -> None:
"""An event the SDK does not model answers ``200``, so it is not retried."""
payload: dict[str, Any] = {"event": "message.edited", "messageId": "A2"}
assert post(client, payload).json() == {
"status": "ignored",
"event": "message.edited",
}
$ pytest test_zap_service.py -v
test_zap_service.py::test_wrong_secret_is_401 PASSED
test_zap_service.py::test_message_is_stored_once PASSED
test_zap_service.py::test_group_is_skipped PASSED
test_zap_service.py::test_lost_media PASSED
test_zap_service.py::test_late_status_is_stale PASSED
test_zap_service.py::test_unknown_event_is_200 PASSED
Signature cross-checked with the gateway
sign_zap_webhook produces the exact same header as the gateway's
signPayload (src/utils/signature.ts): the SDK's suite pins two
signatures produced by the gateway itself and checks that they pass
(tests/testing/test_fake_zap.py and
tests/integrations/messaging/zap/test_webhooks.py).
Recap¶
- Register the webhook with
--secret; without it the gateway does not sign. make_zap_webhook_dependency(secret=...)verifies the HMAC over the raw body and returns aZapWebhookDelivery.- Dispatch on
delivery.inbound/delivery.status; whatever has neither answers200and goes to the log. - Compare against the enums —
ZapWebhookEventEnum,ZapInboundMediaTypeEnum,ZapJidServerEnum,ZapOutboundKindEnum,AcceptedResponseStatus— not loose strings;ison the envelope and onfrom_server,==on body fields. - Filter on
from_server: groups, status stories and channels arrive too. ZapInbox+ZapInboundMessageMixin/ZapDeliveryMixinbring idempotency throughUNIQUEonmessage_id(inbound) andoutbound_id(status and send);is_replyablefilters replyable deliveries (REPLYABLE_OUTCOMES) andsend_replyquotesmessage_idwithidempotency_key=f"{key_prefix}{message_id}", rejecting raw JIDs with@.ZapInboundMessageResponseSchema,ZapDeliveryResponseSchemaandZapWebhookResponseSchema(ZapWebhookOutcome) provide standard schemas for query and webhook routes.- Group and reply by
chat_key;Noneis a group or a LID with no number. - Media only through
inbox.get_message_media, andmedia_url: Nonewithmedia_typemeans lost. ZapInbox.trackappliesis_forward_transitionbefore writing any status, and creates the row of a callback that arrives before the send.make_zap_inbox_routerjoinsmake_zap_webhook_dependency,ZapInbox.claim,ZapInbox.trackandon_replyinBackgroundTasksover a session of its own, independent of the request's session (closed withscope="function"), logging background failures withmessage_idwithout answering500.- In tests, use
FakeZapClient,sign_zap_webhook,make_zap_inboundandmake_zap_statusfromtempest_fastapi_sdk.testing.fakesto exerciseZapInboxand webhook routes without a gateway orhttpx.MockTransport.