Ir para o conteúdo

tempest_fastapi_sdk.integrations.messaging.zap.router

O router opcional do FastAPI que recebe o webhook do zap-api.

« Integrações e pagamentos


ZapClientDependency module-attribute

ZapClientDependency = Callable[..., ZapClient | Awaitable[ZapClient]]

A FastAPI dependency returning the :class:ZapClient (sync or async).

ZapInboundHandler module-attribute

ZapInboundHandler = Callable[[ZapInboundMessage], Awaitable[None]]

An async callable receiving one verified message.received body.

Receives the :class:ZapInboundMessage the dependency already validated, and nothing else — close over the service, queue or session factory it needs. Raise to have the gateway re-deliver; return to accept.

ZapInboxReplyHandler module-attribute

ZapInboxReplyHandler = Callable[
    [ZapInboundMessage, ZapInbox[InboundT, DeliveryT]], Awaitable[None]
]

An async callback executed in BackgroundTasks with an independent inbox.

Receives the claimed :class:ZapInboundMessage and a fresh :class:ZapInbox bound to its own database session opened after the HTTP request finishes.

ZapShouldReplyPredicate module-attribute

ZapShouldReplyPredicate = Callable[[ZapInboundOutcomeEnum, ZapInboundMessage], bool]

A predicate deciding whether a claimed inbound message triggers on_reply.

ZapStatusHandler module-attribute

ZapStatusHandler = Callable[[ZapStatusCallback], Awaitable[None]]

An async callable receiving one verified message.${status} body.

Receives the :class:ZapStatusCallback the dependency already validated, which covers message.sent, message.delivered, message.read and message.failed — check :attr:ZapStatusCallback.status to tell them apart, and :func:~tempest_fastapi_sdk.integrations.messaging.zap.is_forward_transition before storing one, since notifications arrive out of order.

ZapWebhookAckSchema

Bases: BaseSchema

The acknowledgement the webhook route answers with.

The gateway only reads the status code, so the body exists for the consumer reading a log or a TestClient transcript: event is the event field exactly as delivered, kept even when this SDK does not model it.

Attributes:

Name Type Description
ok bool

Always True — anything else arrives as an error status, never as a body.

event str

The event name of the delivery, or "" for a body that was not JSON.

make_zap_inbox_router

make_zap_inbox_router(
    *,
    session_factory: Callable[..., AsyncIterator[AsyncSession]],
    message_model: type[InboundT],
    delivery_model: type[DeliveryT],
    client_dependency: ZapClientDependency,
    secret: str | bytes | None = None,
    verify: Callable[..., Coroutine[Any, Any, ZapWebhookDelivery]] | None = None,
    on_reply: ZapInboxReplyHandler[InboundT, DeliveryT] | None = None,
    should_reply: ZapShouldReplyPredicate = is_replyable,
    accepted_servers: frozenset[ZapJidServerEnum] = DEFAULT_ACCEPTED_SERVERS,
    path: str = "/webhooks/zap",
    tags: list[str] | None = None,
    include_in_schema: bool = False,
    docs_locale: str | None = None,
) -> APIRouter

Build a zap-api webhook router wired directly to :class:ZapInbox.

Mounts POST {path}, verifies the HMAC signature, and handles every delivery through :class:ZapInbox:

  • message.received runs :meth:ZapInbox.claim on the request's database session (declared with scope="function" so the session closes as soon as the endpoint returns, releasing its pool connection before the response is sent and before background work starts). When on_reply is provided and should_reply(outcome, message) returns True, schedules on_reply(message, bg_inbox) on FastAPI's :class:~fastapi.BackgroundTasks with a fresh, independent database session and :class:ZapInbox.
  • message.{sent,delivered,read,failed} runs :meth:ZapInbox.track on the request's session, advancing delivery state monotonically.
  • Unmodeled or unrecognized events answer 200 with status="ignored" and log the payload keys at debug level.

Every verified delivery answers 200 with :class:ZapWebhookResponseSchema carrying status and event; exceptions raised inside on_reply are logged with message_id and never bubble out of the background task.

Parameters:

Name Type Description Default
session_factory Callable[..., AsyncIterator[AsyncSession]]

Yields a database session per invocation (for example db.session_dependency or session_dependency_for(get_db)). Registered with FastAPI through :func:session_provider_for for the request and invoked again to open an independent session for each background on_reply task. That second call happens outside FastAPI's resolver, with no arguments, so the factory must take no required parameter: one that needs a dependency (Request, Depends(get_database)) is refused at construction with :class:ValueError.

required
message_model type[InboundT]

Consumer ORM model mixing in :class:ZapInboundMessageMixin.

required
delivery_model type[DeliveryT]

Consumer ORM model mixing in :class:ZapDeliveryMixin.

required
client_dependency ZapClientDependency

FastAPI dependency returning the :class:ZapClient (sync or async).

required
secret str | bytes | None

Webhook secret registered on the gateway. Builds the signature dependency with :func:make_zap_webhook_dependency.

None
verify Callable[..., Coroutine[Any, Any, ZapWebhookDelivery]] | None

Custom verification dependency used instead of secret.

None
on_reply ZapInboxReplyHandler[InboundT, DeliveryT] | None

Async callback invoked in BackgroundTasks with (message, inbox) whenever should_reply(outcome, message) is True. The inbox passed to on_reply uses its own fresh database session, separate from the request's session.

None
should_reply ZapShouldReplyPredicate

Predicate receiving (outcome, message) and deciding whether to schedule on_reply. Defaults to :func:is_replyable.

is_replyable
accepted_servers frozenset[ZapJidServerEnum]

JID servers accepted by :meth:ZapInbox.claim. Defaults to :data:DEFAULT_ACCEPTED_SERVERS.

DEFAULT_ACCEPTED_SERVERS
path str

Route path to mount. Defaults to "/webhooks/zap".

'/webhooks/zap'
tags list[str] | None

OpenAPI tags. Defaults to ["zap"].

None
include_in_schema bool

Whether the route appears in OpenAPI. Defaults to False so internal webhooks stay out of public docs.

False
docs_locale str | None

Language of OpenAPI summary and description text — "en-US" or "pt-BR". None reads API_DOCS_LOCALE via :class:~tempest_fastapi_sdk.settings.ServerSettings.

None

Returns:

Name Type Description
APIRouter APIRouter

Ready to mount with app.include_router.

Raises:

Type Description
ValueError

If both secret and verify are given, or neither is, or secret is empty, or session_factory has a required parameter.

TypeError

If session_factory, client_dependency, should_reply or a non-None on_reply is not callable.

make_zap_webhook_router

make_zap_webhook_router(
    *,
    secret: str | bytes | None = None,
    verify: Callable[..., Coroutine[Any, Any, ZapWebhookDelivery]] | None = None,
    on_inbound: ZapInboundHandler | None = None,
    on_status: ZapStatusHandler | None = None,
    path: str = "/webhooks/zap",
    tags: list[str] | None = None,
    include_in_schema: bool = True,
    docs_locale: str | None = None,
) -> APIRouter

Build a router with the one POST the zap-api webhook needs.

One route, POST {path}, dispatching by event: on_inbound for a message.received delivery and on_status for the four status events. It answers 200 with :class:ZapWebhookAckSchema once the handler returns, and 401 when the signature does not verify.

Both events reach the same URL, so pass --events status,inbound when registering the webhook on the gateway, and one or both handlers depending on which half the service subscribes to.

Parameters:

Name Type Description Default
secret str | bytes | None

The webhook secret, as registered on the gateway. Builds the signature dependency with :func:make_zap_webhook_dependency.

None
verify Callable[..., Coroutine[Any, Any, ZapWebhookDelivery]] | None

A dependency verifying the delivery instead of secret — the one :func:make_zap_webhook_dependency returns, for a rotated secret checked by a custom verifier or a test double.

None
on_inbound ZapInboundHandler | None

Called with the validated :class:ZapInboundMessage of a message.received delivery. None (the default) leaves those deliveries to a 200 and a debug log.

None
on_status ZapStatusHandler | None

Called with the validated :class:ZapStatusCallback of a status delivery. None leaves those deliveries to a 200 and a debug log.

None
path str

The path to mount. Register this same path on the gateway (npm run webhook:set).

'/webhooks/zap'
tags list[str] | None

OpenAPI tags. Defaults to ["zap"].

None
include_in_schema bool

Whether the route appears in the OpenAPI document. Turn it off to keep the webhook out of a public schema.

True
docs_locale str | None

Language of the OpenAPI summary and description text — "en-US" or "pt-BR". None (default) reads API_DOCS_LOCALE through :class:~tempest_fastapi_sdk.settings.ServerSettings, whose default is "en-US".

None

Returns:

Name Type Description
APIRouter APIRouter

Ready to mount with app.include_router.

Raises:

Type Description
ValueError

If both secret and verify 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 a route that accepted that would look authenticated while checking nothing.

TypeError

If on_inbound or on_status is neither None nor callable.

A delivery the signature accepted but no handler claimed answers 200; a handler that raises propagates, so the response is 500 and the gateway re-delivers. See the module docstring for the gateway code both come from.