Ir para o conteúdo

tempest_fastapi_sdk.integrations.messaging.zap

zap-api, o gateway de WhatsApp da casa: cliente, schemas e receiver de webhook.

« Integrações e pagamentos


O cliente e os schemas são gerados de vendor/zap-openapi.yaml por scripts/regen_zap.py. A fábrica de HTTPClient (http_client.py) e o receiver de webhook (webhooks.py) são escritos à mão. As duas metades resolvem de forma lazy, então importar o namespace não constrói nenhum modelo.

ZAP_API_KEY_HEADER module-attribute

ZAP_API_KEY_HEADER: str = 'x-api-key'

Authentication header expected by every protected zap-api route.

zap_http_client

zap_http_client(
    base_url: str,
    api_key: str,
    *,
    timeout: float = 10.0,
    retry_policy: RetryPolicy | None = None,
    extra_headers: Mapping[str, str] | None = None,
    transport: AsyncBaseTransport | None = None,
) -> HTTPClient

Build an :class:HTTPClient configured for the zap-api gateway.

Parameters:

Name Type Description Default
base_url str

Gateway root URL (for example "http://127.0.0.1:3000"). Leading and trailing whitespace is stripped; empty or blank values are rejected.

required
api_key str

Consumer API key issued by the gateway, attached as the x-api-key default header. Empty or blank values are rejected.

required
timeout float

Per-request timeout in seconds. Must be a positive finite number. Default: 10.0.

10.0
retry_policy RetryPolicy | None

Retry configuration. None keeps the :class:HTTPClient default.

None
extra_headers Mapping[str, str] | None

Additional default headers merged on top of the authentication header.

None
transport AsyncBaseTransport | None

Transport override — pass an httpx.MockTransport in tests to exercise the client without network calls.

None

Returns:

Name Type Description
HTTPClient HTTPClient

A client pointed at base_url with x-api-key set in

HTTPClient

its default headers.

Raises:

Type Description
ValueError

If base_url or api_key is empty/whitespace, or if timeout is not a positive finite number.

ZapClient

ZapClient(client: HTTPClient)

Client for zap-api (version 1.0.0).

Initialize the client.

Parameters:

Name Type Description Default
client HTTPClient

The transport to issue requests through. Build it with HTTPClient(base_url=DEFAULT_BASE_URL) to target the server the specification declares, and attach credentials via its default_headers.

required

health async

health() -> None

Liveness probe — always 200 while the process is up.

Answers 200 even while WhatsApp is disconnected: the gateway still accepts sends into the outbox. Use /ready to gate traffic.

Returns:

Name Type Description
None None

Nothing — the operation answers 200 with no body.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents no error status.

check_number async

check_number(number: str) -> CheckNumberResponse

Check whether a number is registered on WhatsApp.

Parameters:

Name Type Description Default
number str

The number value.

required

Returns:

Name Type Description
CheckNumberResponse CheckNumberResponse

The 200 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 500.

get_history async

get_history(chat: str, *, limit: int | None = None) -> HistoryResponse

Stored conversation with a number, newest first.

Lets a bot rebuild context without keeping its own copy of the history. Accepts either the digits or the full JID the inbound webhook delivers. The raw Baileys envelope is never exposed.

Parameters:

Name Type Description Default
chat str

Phone digits, or the JID from the inbound webhook

required
limit int | None

The limit value. Omitted from the query when None.

None

Returns:

Name Type Description
HistoryResponse HistoryResponse

The 200 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 500, 503.

react async

react(
    *, body: ReactionRequest | None = None, idempotency_key: str | None = None
) -> AcceptedResponse

Enqueue an emoji reaction to a message.

Goes through the outbox like any other send. An empty emoji removes a reaction previously sent.

Parameters:

Name Type Description Default
body ReactionRequest

The request body. Optional.

None
idempotency_key str | None

Optional. Guards against a retry becoming a duplicate message. Because the send is asynchronous, a lost 202 leaves you unable to tell whether the message was enqueued. Send a fresh key (a UUID) with each new message, and reuse that same key when retrying it: the second call returns the original row with deduped: true instead of enqueueing a second message. The key is scoped to your consumer, and stays claimed for as long as the row exists — so reusing an old key for a new message answers deduped: true and sends nothing. This header does not authenticate. Auth is x-api-key (Authorize, top right). Omitted from the request headers when None.

None

Returns:

Name Type Description
AcceptedResponse AcceptedResponse

The 202 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 429, 500.

mark_read async

mark_read(*, body: ReadRequest | None = None) -> None

Mark inbound messages as read (blue ticks).

Visible to the other side, so it is an explicit call rather than something the gateway does on delivery. Bypasses the outbox for the same reason as presence.

Parameters:

Name Type Description Default
body ReadRequest

The request body. Optional.

None

Returns:

Name Type Description
None None

Nothing — the operation answers 204 with no body.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 429, 503.

send_audio async

send_audio(
    *, body: SendAudioRequest | None = None, idempotency_key: str | None = None
) -> AcceptedResponse

Enqueue an audio message.

Parameters:

Name Type Description Default
body SendAudioRequest

The request body. Optional.

None
idempotency_key str | None

Optional. Guards against a retry becoming a duplicate message. Because the send is asynchronous, a lost 202 leaves you unable to tell whether the message was enqueued. Send a fresh key (a UUID) with each new message, and reuse that same key when retrying it: the second call returns the original row with deduped: true instead of enqueueing a second message. The key is scoped to your consumer, and stays claimed for as long as the row exists — so reusing an old key for a new message answers deduped: true and sends nothing. This header does not authenticate. Auth is x-api-key (Authorize, top right). Omitted from the request headers when None.

None

Returns:

Name Type Description
AcceptedResponse AcceptedResponse

The 202 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 429, 500.

send_audio_base64 async

send_audio_base64(
    *, body: SendAudioBase64Request | None = None, idempotency_key: str | None = None
) -> AcceptedResponse

Enqueue an audio file sent as base64.

Parameters:

Name Type Description Default
body SendAudioBase64Request

The request body. Optional.

None
idempotency_key str | None

Optional. Guards against a retry becoming a duplicate message. Because the send is asynchronous, a lost 202 leaves you unable to tell whether the message was enqueued. Send a fresh key (a UUID) with each new message, and reuse that same key when retrying it: the second call returns the original row with deduped: true instead of enqueueing a second message. The key is scoped to your consumer, and stays claimed for as long as the row exists — so reusing an old key for a new message answers deduped: true and sends nothing. This header does not authenticate. Auth is x-api-key (Authorize, top right). Omitted from the request headers when None.

None

Returns:

Name Type Description
AcceptedResponse AcceptedResponse

The 202 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 413, 429, 500.

send_document async

send_document(
    *, body: SendDocumentRequest | None = None, idempotency_key: str | None = None
) -> AcceptedResponse

Enqueue a document message.

Parameters:

Name Type Description Default
body SendDocumentRequest

The request body. Optional.

None
idempotency_key str | None

Optional. Guards against a retry becoming a duplicate message. Because the send is asynchronous, a lost 202 leaves you unable to tell whether the message was enqueued. Send a fresh key (a UUID) with each new message, and reuse that same key when retrying it: the second call returns the original row with deduped: true instead of enqueueing a second message. The key is scoped to your consumer, and stays claimed for as long as the row exists — so reusing an old key for a new message answers deduped: true and sends nothing. This header does not authenticate. Auth is x-api-key (Authorize, top right). Omitted from the request headers when None.

None

Returns:

Name Type Description
AcceptedResponse AcceptedResponse

The 202 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 429, 500.

send_document_base64 async

send_document_base64(
    *, body: SendDocumentBase64Request | None = None, idempotency_key: str | None = None
) -> AcceptedResponse

Enqueue a document sent as base64.

Parameters:

Name Type Description Default
body SendDocumentBase64Request

The request body. Optional.

None
idempotency_key str | None

Optional. Guards against a retry becoming a duplicate message. Because the send is asynchronous, a lost 202 leaves you unable to tell whether the message was enqueued. Send a fresh key (a UUID) with each new message, and reuse that same key when retrying it: the second call returns the original row with deduped: true instead of enqueueing a second message. The key is scoped to your consumer, and stays claimed for as long as the row exists — so reusing an old key for a new message answers deduped: true and sends nothing. This header does not authenticate. Auth is x-api-key (Authorize, top right). Omitted from the request headers when None.

None

Returns:

Name Type Description
AcceptedResponse AcceptedResponse

The 202 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 413, 429, 500.

send_image async

send_image(
    *, body: SendImageRequest | None = None, idempotency_key: str | None = None
) -> AcceptedResponse

Enqueue an image message.

Parameters:

Name Type Description Default
body SendImageRequest

The request body. Optional.

None
idempotency_key str | None

Optional. Guards against a retry becoming a duplicate message. Because the send is asynchronous, a lost 202 leaves you unable to tell whether the message was enqueued. Send a fresh key (a UUID) with each new message, and reuse that same key when retrying it: the second call returns the original row with deduped: true instead of enqueueing a second message. The key is scoped to your consumer, and stays claimed for as long as the row exists — so reusing an old key for a new message answers deduped: true and sends nothing. This header does not authenticate. Auth is x-api-key (Authorize, top right). Omitted from the request headers when None.

None

Returns:

Name Type Description
AcceptedResponse AcceptedResponse

The 202 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 429, 500.

send_image_base64 async

send_image_base64(
    *, body: SendImageBase64Request | None = None, idempotency_key: str | None = None
) -> AcceptedResponse

Enqueue an image sent as base64.

Parameters:

Name Type Description Default
body SendImageBase64Request

The request body. Optional.

None
idempotency_key str | None

Optional. Guards against a retry becoming a duplicate message. Because the send is asynchronous, a lost 202 leaves you unable to tell whether the message was enqueued. Send a fresh key (a UUID) with each new message, and reuse that same key when retrying it: the second call returns the original row with deduped: true instead of enqueueing a second message. The key is scoped to your consumer, and stays claimed for as long as the row exists — so reusing an old key for a new message answers deduped: true and sends nothing. This header does not authenticate. Auth is x-api-key (Authorize, top right). Omitted from the request headers when None.

None

Returns:

Name Type Description
AcceptedResponse AcceptedResponse

The 202 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 413, 429, 500.

send_text async

send_text(
    *, body: SendTextRequest | None = None, idempotency_key: str | None = None
) -> AcceptedResponse

Enqueue a text message.

Parameters:

Name Type Description Default
body SendTextRequest

The request body. Optional.

None
idempotency_key str | None

Optional. Guards against a retry becoming a duplicate message. Because the send is asynchronous, a lost 202 leaves you unable to tell whether the message was enqueued. Send a fresh key (a UUID) with each new message, and reuse that same key when retrying it: the second call returns the original row with deduped: true instead of enqueueing a second message. The key is scoped to your consumer, and stays claimed for as long as the row exists — so reusing an old key for a new message answers deduped: true and sends nothing. This header does not authenticate. Auth is x-api-key (Authorize, top right). Omitted from the request headers when None.

None

Returns:

Name Type Description
AcceptedResponse AcceptedResponse

The 202 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 429, 500.

send_video async

send_video(
    *, body: SendVideoRequest | None = None, idempotency_key: str | None = None
) -> AcceptedResponse

Enqueue a video message.

Parameters:

Name Type Description Default
body SendVideoRequest

The request body. Optional.

None
idempotency_key str | None

Optional. Guards against a retry becoming a duplicate message. Because the send is asynchronous, a lost 202 leaves you unable to tell whether the message was enqueued. Send a fresh key (a UUID) with each new message, and reuse that same key when retrying it: the second call returns the original row with deduped: true instead of enqueueing a second message. The key is scoped to your consumer, and stays claimed for as long as the row exists — so reusing an old key for a new message answers deduped: true and sends nothing. This header does not authenticate. Auth is x-api-key (Authorize, top right). Omitted from the request headers when None.

None

Returns:

Name Type Description
AcceptedResponse AcceptedResponse

The 202 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 429, 500.

send_video_base64 async

send_video_base64(
    *, body: SendVideoBase64Request | None = None, idempotency_key: str | None = None
) -> AcceptedResponse

Enqueue a video sent as base64.

Parameters:

Name Type Description Default
body SendVideoBase64Request

The request body. Optional.

None
idempotency_key str | None

Optional. Guards against a retry becoming a duplicate message. Because the send is asynchronous, a lost 202 leaves you unable to tell whether the message was enqueued. Send a fresh key (a UUID) with each new message, and reuse that same key when retrying it: the second call returns the original row with deduped: true instead of enqueueing a second message. The key is scoped to your consumer, and stays claimed for as long as the row exists — so reusing an old key for a new message answers deduped: true and sends nothing. This header does not authenticate. Auth is x-api-key (Authorize, top right). Omitted from the request headers when None.

None

Returns:

Name Type Description
AcceptedResponse AcceptedResponse

The 202 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 413, 429, 500.

set_typing async

set_typing(*, body: TypingRequest | None = None) -> None

Publish a typing / recording indicator, or clear it.

Sent straight to WhatsApp rather than through the outbox: presence is ephemeral, and an indicator replayed after a restart would misreport what the sender is doing. WhatsApp expires it on its own, so a caller that dies mid-thought stops showing as typing with no cleanup call.

Parameters:

Name Type Description Default
body TypingRequest

The request body. Optional.

None

Returns:

Name Type Description
None None

Nothing — the operation answers 204 with no body.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 429, 503.

upload_audio async

upload_audio(
    *,
    file: bytes,
    to: str,
    reply_to: str | None = None,
    idempotency_key: str | None = None,
) -> AcceptedResponse

Upload an audio file and enqueue it.

The file travels in the request, so nothing has to be publicly reachable first — this is the route to use when the media exists only on the caller's disk.

Capped at MEDIA_MAX_BYTES (16MB by default), enforced while the body streams: an oversized upload is cut off mid-flight rather than buffered in full and refused afterwards.

Parameters:

Name Type Description Default
file bytes

The file itself — the form's only file part

required
to str

Recipient phone number, digits only

required
reply_to str | None

Message id being replied to, quoted above this one. Omitted from the form body when None.

None
idempotency_key str | None

Optional. Guards against a retry becoming a duplicate message. Because the send is asynchronous, a lost 202 leaves you unable to tell whether the message was enqueued. Send a fresh key (a UUID) with each new message, and reuse that same key when retrying it: the second call returns the original row with deduped: true instead of enqueueing a second message. The key is scoped to your consumer, and stays claimed for as long as the row exists — so reusing an old key for a new message answers deduped: true and sends nothing. This header does not authenticate. Auth is x-api-key (Authorize, top right). Omitted from the request headers when None.

None

Returns:

Name Type Description
AcceptedResponse AcceptedResponse

The 202 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 413, 415, 429, 500.

upload_document async

upload_document(
    *,
    file: bytes,
    to: str,
    file_name: str | None = None,
    reply_to: str | None = None,
    idempotency_key: str | None = None,
) -> AcceptedResponse

Upload a document and enqueue it.

The file travels in the request, so nothing has to be publicly reachable first — this is the route to use when the media exists only on the caller's disk.

Capped at MEDIA_MAX_BYTES (16MB by default), enforced while the body streams: an oversized upload is cut off mid-flight rather than buffered in full and refused afterwards.

Parameters:

Name Type Description Default
file bytes

The file itself — the form's only file part

required
to str

Recipient phone number, digits only

required
file_name str | None

Name the recipient sees. Falls back to the uploaded part's own file name. Omitted from the form body when None.

None
reply_to str | None

Message id being replied to, quoted above this one. Omitted from the form body when None.

None
idempotency_key str | None

Optional. Guards against a retry becoming a duplicate message. Because the send is asynchronous, a lost 202 leaves you unable to tell whether the message was enqueued. Send a fresh key (a UUID) with each new message, and reuse that same key when retrying it: the second call returns the original row with deduped: true instead of enqueueing a second message. The key is scoped to your consumer, and stays claimed for as long as the row exists — so reusing an old key for a new message answers deduped: true and sends nothing. This header does not authenticate. Auth is x-api-key (Authorize, top right). Omitted from the request headers when None.

None

Returns:

Name Type Description
AcceptedResponse AcceptedResponse

The 202 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 413, 415, 429, 500.

upload_image async

upload_image(
    *,
    file: bytes,
    to: str,
    caption: str | None = None,
    reply_to: str | None = None,
    idempotency_key: str | None = None,
) -> AcceptedResponse

Upload an image and enqueue it.

The file travels in the request, so nothing has to be publicly reachable first — this is the route to use when the media exists only on the caller's disk.

Capped at MEDIA_MAX_BYTES (16MB by default), enforced while the body streams: an oversized upload is cut off mid-flight rather than buffered in full and refused afterwards.

Parameters:

Name Type Description Default
file bytes

The file itself — the form's only file part

required
to str

Recipient phone number, digits only

required
caption str | None

The caption value. Omitted from the form body when None.

None
reply_to str | None

Message id being replied to, quoted above this one. Omitted from the form body when None.

None
idempotency_key str | None

Optional. Guards against a retry becoming a duplicate message. Because the send is asynchronous, a lost 202 leaves you unable to tell whether the message was enqueued. Send a fresh key (a UUID) with each new message, and reuse that same key when retrying it: the second call returns the original row with deduped: true instead of enqueueing a second message. The key is scoped to your consumer, and stays claimed for as long as the row exists — so reusing an old key for a new message answers deduped: true and sends nothing. This header does not authenticate. Auth is x-api-key (Authorize, top right). Omitted from the request headers when None.

None

Returns:

Name Type Description
AcceptedResponse AcceptedResponse

The 202 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 413, 415, 429, 500.

upload_video async

upload_video(
    *,
    file: bytes,
    to: str,
    caption: str | None = None,
    reply_to: str | None = None,
    idempotency_key: str | None = None,
) -> AcceptedResponse

Upload a video and enqueue it.

The file travels in the request, so nothing has to be publicly reachable first — this is the route to use when the media exists only on the caller's disk.

Capped at MEDIA_MAX_BYTES (16MB by default), enforced while the body streams: an oversized upload is cut off mid-flight rather than buffered in full and refused afterwards.

Parameters:

Name Type Description Default
file bytes

The file itself — the form's only file part

required
to str

Recipient phone number, digits only

required
caption str | None

The caption value. Omitted from the form body when None.

None
reply_to str | None

Message id being replied to, quoted above this one. Omitted from the form body when None.

None
idempotency_key str | None

Optional. Guards against a retry becoming a duplicate message. Because the send is asynchronous, a lost 202 leaves you unable to tell whether the message was enqueued. Send a fresh key (a UUID) with each new message, and reuse that same key when retrying it: the second call returns the original row with deduped: true instead of enqueueing a second message. The key is scoped to your consumer, and stays claimed for as long as the row exists — so reusing an old key for a new message answers deduped: true and sends nothing. This header does not authenticate. Auth is x-api-key (Authorize, top right). Omitted from the request headers when None.

None

Returns:

Name Type Description
AcceptedResponse AcceptedResponse

The 202 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 413, 415, 429, 500.

get_message_media async

get_message_media(message_id: str) -> bytes

Media bytes of a stored message.

Addressed by the WhatsApp message id — the same id the inbound webhook delivers as messageId, and the one its mediaUrl points at.

Media is fetched while the message is still in memory and never re-downloadable from WhatsApp afterwards, so a message whose download failed or exceeded MEDIA_MAX_BYTES is stored with a media type and no file, and answers 404 here.

The response Content-Type is the media's own (image/jpeg, video/mp4, …), not application/octet-stream.

Parameters:

Name Type Description Default
message_id str

The WhatsApp message id (messageId in the webhook)

required

Returns:

Name Type Description
bytes bytes

The 200 response body, undecoded — the operation answers application/octet-stream, which is handed over as bytes rather than parsed.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 400, 401, 404, 503.

metrics async

metrics() -> bytes

Prometheus metrics (text exposition format).

Returns:

Name Type Description
bytes bytes

The 200 response body, undecoded — the operation answers text/plain, which is handed over as bytes rather than parsed.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents no error status.

ready async

ready() -> None

Readiness probe — 503 until the WhatsApp session is connected.

Returns:

Name Type Description
None None

Nothing — the operation answers 200 with no body.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 503.

disconnect_session async

disconnect_session() -> SessionStatusResponse

Log out and invalidate the session.

A deliberate logout: the reconnect loop does not undo it. Pairing again requires a new QR scan.

Returns:

Name Type Description
SessionStatusResponse SessionStatusResponse

The 200 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 401.

get_session_qr async

get_session_qr() -> QrResponse

Authenticated URL of the current pairing QR.

Returns:

Name Type Description
QrResponse QrResponse

The 200 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 401, 404.

get_session_qr_image async

get_session_qr_image() -> bytes

The pairing QR as a PNG.

Served image/png with Cache-Control: no-store. Behind the same API key as everything else — the pairing code is never public.

Returns:

Name Type Description
bytes bytes

The 200 response body, undecoded — the operation answers image/png, which is handed over as bytes rather than parsed.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 401, 404.

start_session async

start_session() -> SessionStartResponse

Start the WhatsApp connection.

Idempotent: calling it while already connected returns the current status. qr is the authenticated URL of the pairing image, not the code itself.

Returns:

Name Type Description
SessionStartResponse SessionStartResponse

The 200 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 401.

get_session_status async

get_session_status() -> SessionStatusResponse

Current WhatsApp session status.

Returns:

Name Type Description
SessionStatusResponse SessionStatusResponse

The 200 response body, validated.

Raises:

Type Description
HTTPStatusError

For any non-2xx response. The specification documents 401.

AcceptedResponse

Bases: BaseSchema

Schema generated for AcceptedResponse.

Attributes:

Name Type Description
id str | None

Undocumented in the spec.

status AcceptedResponseStatus | None

Undocumented in the spec.

deduped bool

Undocumented in the spec.

AcceptedResponseStatus

Bases: BaseStrEnum

Allowed values for AcceptedResponseStatus.

SendTextRequest

Bases: BaseSchema

Schema generated for SendTextRequest.

Attributes:

Name Type Description
to str

Undocumented in the spec.

reply_to str | None

Undocumented in the spec.

text str

Undocumented in the spec.

SendImageRequest

Bases: BaseSchema

Schema generated for SendImageRequest.

Attributes:

Name Type Description
to str

Undocumented in the spec.

reply_to str | None

Undocumented in the spec.

media str

Undocumented in the spec.

caption str | None

Undocumented in the spec.

SendVideoRequest

Bases: BaseSchema

Schema generated for SendVideoRequest.

Attributes:

Name Type Description
to str

Undocumented in the spec.

reply_to str | None

Undocumented in the spec.

media str

Undocumented in the spec.

caption str | None

Undocumented in the spec.

SendAudioRequest

Bases: BaseSchema

Schema generated for SendAudioRequest.

Attributes:

Name Type Description
to str

Undocumented in the spec.

reply_to str | None

Undocumented in the spec.

media str

Undocumented in the spec.

SendDocumentRequest

Bases: BaseSchema

Schema generated for SendDocumentRequest.

Attributes:

Name Type Description
to str

Undocumented in the spec.

reply_to str | None

Undocumented in the spec.

media str

Undocumented in the spec.

file_name str

Undocumented in the spec.

ReactionRequest

Bases: BaseSchema

Schema generated for ReactionRequest.

Attributes:

Name Type Description
to str

Undocumented in the spec.

message_id str

Undocumented in the spec.

emoji str

Undocumented in the spec.

ReadRequest

Bases: BaseSchema

Schema generated for ReadRequest.

Attributes:

Name Type Description
to str

Undocumented in the spec.

message_ids list[str]

Undocumented in the spec.

TypingRequest

Bases: BaseSchema

Schema generated for TypingRequest.

Attributes:

Name Type Description
to str

Undocumented in the spec.

state TypingRequestState

Undocumented in the spec.

TypingRequestState

Bases: BaseStrEnum

Allowed values for TypingRequestState.

CheckNumberResponse

Bases: BaseSchema

Schema generated for CheckNumberResponse.

Attributes:

Name Type Description
number str

Undocumented in the spec.

exists bool

Undocumented in the spec.

jid str | None

Undocumented in the spec.

HistoryResponse

Bases: BaseSchema

Schema generated for HistoryResponse.

Attributes:

Name Type Description
chat str

Undocumented in the spec.

messages list[HistoryMessage]

Undocumented in the spec.

HistoryMessage

Bases: BaseSchema

Schema generated for HistoryMessage.

Attributes:

Name Type Description
message_id str

Undocumented in the spec.

direction HistoryMessageDirection

Undocumented in the spec.

text str | None

Undocumented in the spec.

media_type str | None

Undocumented in the spec.

timestamp datetime

Undocumented in the spec.

HistoryMessageDirection

Bases: BaseStrEnum

Allowed values for HistoryMessageDirection.

QrResponse

Bases: BaseSchema

Schema generated for QrResponse.

Attributes:

Name Type Description
qr str

Undocumented in the spec.

SessionStartResponse

Bases: BaseSchema

Schema generated for SessionStartResponse.

Attributes:

Name Type Description
status SessionStatusResponseStatus

Undocumented in the spec.

qr str | None

Undocumented in the spec.

SessionStatusResponse

Bases: BaseSchema

Schema generated for SessionStatusResponse.

Attributes:

Name Type Description
status SessionStatusResponseStatus

Undocumented in the spec.

SessionStatusResponseStatus

Bases: BaseStrEnum

Allowed values for SessionStatusResponseStatus.

ErrorResponse

Bases: BaseSchema

Schema generated for ErrorResponse.

Attributes:

Name Type Description
error str

Undocumented in the spec.

ZAP_INBOUND_EVENT module-attribute

ZAP_INBOUND_EVENT: str = 'message.received'

event value of an incoming-message notification.

Ported from zap-api's INBOUND_EVENT (src/services/webhook.service.ts).

ZAP_WEBHOOK_SIGNATURE_HEADER module-attribute

ZAP_WEBHOOK_SIGNATURE_HEADER: str = 'x-zap-signature'

Header carrying the HMAC-SHA256 signature of the raw body.

Ported from zap-api's SIGNATURE_HEADER (src/utils/signature.ts). The gateway's README spells it X-Zap-Signature; HTTP header names are case-insensitive, and the constant keeps the code's spelling.

ZAP_WEBHOOK_SIGNATURE_PREFIX module-attribute

ZAP_WEBHOOK_SIGNATURE_PREFIX: str = 'sha256='

Fixed prefix in front of the hex digest in the signature header.

Ported from zap-api's signPayload (src/utils/signature.ts), which returns sha256=<hex>.

ZapWebhookEventEnum

Bases: BaseStrEnum

The event value the gateway POSTs to a consumer's webhook.

One URL receives every event, and this is the field that tells them apart. :func:make_zap_webhook_dependency parses it into :attr:ZapWebhookDelivery.event, so a route dispatches with is instead of comparing against a string literal. message.received carries a :class:ZapInboundMessage; the other four carry a :class:ZapStatusCallback and reach only the consumer that sent the message.

Being a :class:~enum.StrEnum, every member still equals its wire string, so code that compares event_name == "message.read" keeps working.

Ported from zap-api's INBOUND_EVENT and the message.${CallbackStatus} template of CallbackPayload (src/services/callback.service.ts), whose CallbackStatus is "sent" | "delivered" | "read" | "failed".

Attributes:

Name Type Description
MESSAGE_RECEIVED

A message arrived on the WhatsApp session. Sent to every webhook subscribed to inbound.

MESSAGE_SENT

WhatsApp accepted an outbound message.

MESSAGE_DELIVERED

The recipient's device received it.

MESSAGE_READ

The recipient opened it.

MESSAGE_FAILED

The gateway gave up sending it; the reason is in :attr:ZapStatusCallback.error.

Examples:

>>> ZapWebhookEventEnum("message.read") is ZapWebhookEventEnum.MESSAGE_READ
True
>>> ZapWebhookEventEnum.MESSAGE_RECEIVED == "message.received"
True

ZapInboundMediaTypeEnum

Bases: BaseStrEnum

The media category of an incoming message.

The value of :attr:ZapInboundMessage.media_type. None there — not a member here — means a plain text message.

Ported from zap-api's NormalizedMediaType (src/services/message-normalizer.ts).

Attributes:

Name Type Description
IMAGE

A photo; :attr:ZapInboundMessage.text holds the caption.

VIDEO

A video; :attr:ZapInboundMessage.text holds the caption.

AUDIO

A voice note or audio file.

DOCUMENT

Any file sent as a document; the caption, if any, is in :attr:ZapInboundMessage.text.

STICKER

A sticker.

Examples:

>>> ZapInboundMediaTypeEnum.AUDIO == "audio"
True

ZapJidServerEnum

Bases: BaseStrEnum

The server part of a WhatsApp JID — what kind of address it is.

A JID is <user>@<server>, and the server says whether the address is a person's phone number, a privacy-preserving LID, a group or something else. :attr:ZapInboundMessage.from_server reads it off from_, so a route tells a group from a person without endswith("@g.us").

The gateway does not filter on the server: its publishMessage (src/services/whatsapp.service.ts, commit d0477d8) forwards every notify message with content, so a status story (status@broadcast) or a channel post (newsletter) can reach the webhook as well. Read in the gateway's code, not measured on a live session.

Ported from Baileys' JidServer (WABinary/jid-utils), read from @whiskeysockets/baileys 7.0.0-rc14 — the version installed under zap-api's ^7.0.0-rc.9 range at commit d0477d8.

Attributes:

Name Type Description
USER

A phone number (<digits>@s.whatsapp.net) — :attr:ZapInboundMessage.chat_key holds the digits.

LID

A LID (<id>@lid), WhatsApp's number-hiding address. The gateway maps it back to a number when it can.

GROUP

A group (<id>@g.us). chat_key is None.

BROADCAST

A broadcast list or a status story (status@broadcast).

NEWSLETTER

A WhatsApp channel.

LEGACY_USER

The legacy c.us phone address.

CALL

A call address.

BOT

A bot account.

HOSTED

A hosted phone number.

HOSTED_LID

The LID of a hosted phone number.

Examples:

>>> ZapJidServerEnum("g.us") is ZapJidServerEnum.GROUP
True

ZapOutboundKindEnum

Bases: BaseStrEnum

What kind of send a status notification is about.

The value of :attr:ZapStatusCallback.kind, one per /message/send-* route plus reaction, which goes through the gateway's outbox like any other send. Typing presence and read receipts are not here: the gateway does not queue them, so they never produce a status.

Ported from zap-api's OutboundKind (src/db/models/outbound-message.model.ts).

Attributes:

Name Type Description
TEXT

send_text.

IMAGE

send_image and its base64 / upload variants.

VIDEO

send_video and its variants.

AUDIO

send_audio and its variants.

DOCUMENT

send_document and its variants.

REACTION

react.

Examples:

>>> ZapOutboundKindEnum.REACTION == "reaction"
True

ZapInboundMessage

Bases: BaseSchema

The body of a message.received notification — one incoming message.

You do not build this yourself: :func:make_zap_webhook_dependency validates it and hands it over as :attr:ZapWebhookDelivery.inbound. What a route usually does with it, in order: dedupe on :attr:message_id, file it under :attr:chat_key, branch on :attr:media_type, and fetch the bytes with :meth:ZapClient.get_message_media when there are any.

Ported from zap-api's InboundPayload (src/services/webhook.service.ts). Every nullable field defaults to None so a field the gateway stops sending does not reject the delivery, and unknown fields are kept (extra="allow").

Like every :class:BaseSchema, enum fields hold the enum's value: compare message.media_type == ZapInboundMediaTypeEnum.AUDIO, not with is. A :class:~enum.StrEnum member equals its string, so both spellings of the comparison work.

str_strip_whitespace is turned off on purpose: :class:BaseSchema strips every string, which would rewrite what the person typed (leading indentation, a trailing newline) before the service sees it.

Attributes:

Name Type Description
event ZapWebhookEventEnum

Always message.received.

message_id str

The WhatsApp message id. The key to dedupe on — the gateway retries a delivery until it gets a 2xx, so the same message can arrive more than once. It is also the argument :meth:ZapClient.get_message_media takes.

from_ str

The raw remote JID (<digits>@s.whatsapp.net, a @lid, a @g.us group, status@broadcast…). An address, not a conversation key; :attr:from_server says which kind.

chat_key str | None

The phone digits that identify the conversation, resolved from the LID when the message arrived addressed to one. Group by this, never by from_. None for a group, a broadcast, a channel, or a LID the gateway could not map.

push_name str | None

The name the sender set on their own profile. Not a verified identity.

text str | None

The text, or the media caption.

media_type ZapInboundMediaTypeEnum | None

The media category, or None for a plain text message.

media_url str | None

Link to GET /message/{messageId}/media on the gateway — absolute when the gateway has PUBLIC_BASE_URL set, root-relative otherwise. None with media_type set means the download failed or exceeded MEDIA_MAX_BYTES, and the media cannot be fetched again.

timestamp datetime

When the message was sent, per WhatsApp.

Examples:

>>> message = ZapInboundMessage.model_validate(
...     {
...         "event": "message.received",
...         "messageId": "ABCD1234",
...         "from": "5511999999999@s.whatsapp.net",
...         "chatKey": "5511999999999",
...         "text": "Olá!",
...         "timestamp": "2026-04-21T18:30:00.000Z",
...     }
... )
>>> message.from_server is ZapJidServerEnum.USER
True
>>> message.media_type is None
True

from_server property

from_server: ZapJidServerEnum | None

The kind of address :attr:from_ is, read from its server part.

Returns:

Type Description
ZapJidServerEnum | None

ZapJidServerEnum | None: The server after the last @ of

ZapJidServerEnum | None

from_, or None when there is no @ or the server is

ZapJidServerEnum | None

one Baileys does not define.

Examples:

>>> ZapInboundMessage.model_validate(
...     {
...         "event": "message.received",
...         "messageId": "G1",
...         "from": "120363000000000000@g.us",
...         "timestamp": "2026-04-21T18:30:00.000Z",
...     }
... ).from_server is ZapJidServerEnum.GROUP
True

ZapStatusCallback

Bases: BaseSchema

The body of a message.{sent,delivered,read,failed} notification.

One step in the life of a message you sent. The gateway answers a send with 202 and an id; every later status of that message comes here, carrying the same id. Only the consumer that sent the message receives it, and only when its webhook subscribes to status.

Two things a route must assume: the same notification can arrive more than once (retried until a 2xx), and notifications can arrive out of order (each is retried with its own backoff). Store a status only when :func:is_forward_transition says it advances what you have.

Ported from zap-api's CallbackPayload (src/services/callback.service.ts). Enum fields hold the enum's value, as in every :class:BaseSchema — compare with ==.

Attributes:

Name Type Description
event ZapWebhookEventEnum

message.sent, message.delivered, message.read or message.failed.

id str

The outbound row id — the id the 202 of the send answered. The key to correlate and dedupe on.

consumer str

The consumer name the message was sent under.

to str

The recipient as the send stored it.

kind str

Which send produced the message, one of :class:ZapOutboundKindEnum (compare callback.kind == ZapOutboundKindEnum.IMAGE). Typed str, not the enum, on purpose: the gateway types it string on the wire, and a kind it adds later must not turn the status of a message into an event=None delivery.

status AcceptedResponseStatus

The status the event reports. The gateway only ever sends sent, delivered, read or failed here; queued and sending never arrive on the webhook.

wa_message_id str | None

The WhatsApp message id, when known.

error str | None

Why the send failed, on message.failed.

timestamp datetime

When the gateway built the notification — not when WhatsApp reported the receipt.

Examples:

>>> callback = ZapStatusCallback.model_validate(
...     {
...         "event": "message.delivered",
...         "id": "outbound-uuid",
...         "consumer": "billing-api",
...         "to": "5511999999999",
...         "kind": "text",
...         "status": "delivered",
...         "timestamp": "2026-06-27T18:30:00.000Z",
...     }
... )
>>> callback.status == AcceptedResponseStatus.DELIVERED
True
>>> callback.kind == ZapOutboundKindEnum.TEXT
True

ZapWebhookDelivery dataclass

ZapWebhookDelivery(
    event_name: str,
    event: ZapWebhookEventEnum | None = None,
    inbound: ZapInboundMessage | None = None,
    status: ZapStatusCallback | None = None,
    payload: dict[str, Any] = dict(),
    body: bytes = b"",
)

A verified zap-api webhook delivery — what your route receives.

:func:make_zap_webhook_dependency returns one of these after the signature checked out. It holds the event and, already validated, the body that event carries, so a route dispatches on event and reads the matching field:

  • ZapWebhookEventEnum.MESSAGE_RECEIVED — the message is in inbound;
  • MESSAGE_SENT, MESSAGE_DELIVERED, MESSAGE_READ and MESSAGE_FAILED — the status is in status;
  • None — neither is set; see below.

One invariant makes dispatch total: event is set only when the matching typed body parsed. MESSAGE_RECEIVED always comes with inbound, the four status events always come with status, and event is None covers both an event name this SDK does not know and a known event whose body did not match the model. Either way, answer 2xx and log event_name and payload — a non-2xx makes the gateway retry the same bytes until it gives up.

A dataclass rather than a :class:BaseSchema, for the same reason as :class:OpenPixWebhookEvent: BaseSchema stores enums as their value, and then delivery.event is ZapWebhookEventEnum.MESSAGE_RECEIVED would be false on every delivery. Here event is the member itself.

Attributes:

Name Type Description
event_name str

The event field exactly as delivered, kept even when it is not a known value.

event ZapWebhookEventEnum | None

The parsed event, or None as described above.

inbound ZapInboundMessage | None

The parsed body of a message.received notification.

status ZapStatusCallback | None

The parsed body of a status notification.

payload dict[str, Any]

The whole decoded body.

body bytes

The raw body, byte-for-byte as received.

Examples:

>>> delivery = ZapWebhookDelivery(event_name="message.edited")
>>> delivery.event is None
True

webhook_verifier

webhook_verifier(secret: str | bytes) -> WebhookSignatureVerifier

Build a verifier configured for zap-api.

Parameters:

Name Type Description Default
secret str | bytes

The secret registered with the consumer's webhook (npm run webhook:set -- <consumer> <url> --secret <secret> on the gateway).

required

Returns:

Name Type Description
WebhookSignatureVerifier WebhookSignatureVerifier

An HMAC-SHA256 verifier reading

WebhookSignatureVerifier

data:ZAP_WEBHOOK_SIGNATURE_HEADER, hex-encoded, with the

WebhookSignatureVerifier

sha256= prefix stripped. The comparison is

WebhookSignatureVerifier

func:hmac.compare_digest.

make_zap_webhook_dependency

make_zap_webhook_dependency(
    *,
    secret: str | bytes | None = None,
    verifier: WebhookSignatureVerifier | None = None,
    error_message: str = "Invalid zap-api webhook signature",
) -> Callable[..., Coroutine[Any, Any, ZapWebhookDelivery]]

Build a FastAPI dependency yielding a verified, parsed delivery.

Parameters:

Name Type Description Default
secret str | bytes | None

The webhook secret. Builds the verifier with :func:webhook_verifier.

None
verifier WebhookSignatureVerifier | None

A verifier to use instead of secret — for a rotated secret checked by a custom verifier, or a test double.

None
error_message str

Message on the raised :class:UnauthorizedException.

'Invalid zap-api webhook signature'

Returns:

Type Description
Callable[..., Coroutine[Any, Any, ZapWebhookDelivery]]

Callable[..., Coroutine[Any, Any, ZapWebhookDelivery]]: An async

Callable[..., Coroutine[Any, Any, ZapWebhookDelivery]]

dependency that verifies the signature over the raw body, decodes

Callable[..., Coroutine[Any, Any, ZapWebhookDelivery]]

it, and returns a :class:ZapWebhookDelivery.

Raises:

Type Description
ValueError

If both secret and verifier are given, or neither is, or secret is empty. The gateway signs a delivery only when the webhook was registered with a secret — without one it POSTs unsigned — and this dependency refuses to be built in a shape that would accept that.

UnauthorizedException

Raised by the returned dependency when the signature header is missing or does not verify.

An unrecognized event, a body that does not match its event's model, and a body that is not JSON do not fail the request: the signature verified, so the gateway sent it, and a non-2xx only makes it retry the same bytes. Each comes back with event left None.

is_forward_transition

is_forward_transition(
    current: AcceptedResponseStatus | str | None, new: AcceptedResponseStatus | str
) -> bool

Tell whether moving from current to new advances the state.

Parameters:

Name Type Description Default
current AcceptedResponseStatus | str | None

The status the service has stored, or None when it has none yet. A plain str is accepted because a :class:BaseSchema field stores the enum's value.

required
new AcceptedResponseStatus | str

The status a callback reports.

required

Returns:

Name Type Description
bool bool

True when the service should apply new.

Raises:

Type Description
ValueError

If either value is not a status.

The ladder is queued < sending < sent < delivered < read; repeating the current status, or stepping down it, is not forward. failed is terminal — nothing overwrites it — and it overwrites only queued, sending and sent, because a delivered or read already proves the message arrived.

Ported from zap-api's OUTRANKED_BY (src/db/repositories/outbound-message.repository.ts), the guard the gateway applies to its own row. It sends the callback whether or not that guard moved the row, so a late delivered after a read still reaches the consumer — and each delivery is retried with its own backoff, so a sent whose first POST failed can land after the delivered.