Skip to content

Routers#

A router groups subscribers and publishers in a module and is included into the broker.

service.py
from faststream import FastStream

from faststream_gcp_pubsub import (
    PubSubBroker,
    PubSubPublisher,
    PubSubRoute,
    PubSubRouter,
)

broker = PubSubBroker(project_id="my-project")
app = FastStream(broker)

router = PubSubRouter(prefix="billing-")


@router.subscriber("orders", topic="orders")
@router.publisher("receipts")
async def bill(order: dict[str, int]) -> dict[str, int]:
    return {"order_id": order["id"]}


async def notify(receipt: dict[str, int]) -> None: ...


# routes declare handlers without a decorator
routes = PubSubRouter(
    prefix="shop-",
    handlers=(
        PubSubRoute(
            notify,
            "receipts",
            topic="receipts",
            publishers=(PubSubPublisher("notifications"),),
        ),
    ),
)

broker.include_router(router)
broker.include_router(routes)

PubSubRouter(prefix="billing-") prepends the prefix to the topic and subscription names it declares: the handler above reads billing-orders and publishes to billing-receipts. A full name that starts with projects/ is used as it is, without the prefix.

PubSubRoute and PubSubPublisher#

PubSubRoute registers a handler without a decorator: it takes the function, the subscription and the same options as @broker.subscriber. PubSubPublisher is a publisher registration that a route passes in publishers=. Routes go to the router's handlers=; routers nest with routers=.

Options of the router#

PubSubRouter also accepts dependencies, middlewares, parser, decoder, ack_policy and include_in_schema. They apply to everything the router declares.