FastAPI#
PubSubRouter from faststream_gcp_pubsub.fastapi is a FastAPI router that owns a broker. It
takes the options of PubSubBroker and of fastapi.APIRouter.
app.py
from fastapi import FastAPI
from faststream_gcp_pubsub.fastapi import PubSubRouter
router = PubSubRouter(project_id="my-project")
@router.subscriber("orders-billing", topic="orders")
async def bill(order: dict[str, int]) -> None: ...
@router.post("/orders")
async def place_order(order: dict[str, int]) -> str:
return await router.broker.publish(order, "orders")
app = FastAPI()
app.include_router(router)
Subscribers start with the FastAPI application and stop with it. router.broker is the
PubSubBroker, so router.broker.publish(...) publishes from a route.
The broker's dependencies are FastAPI dependencies here, and its tags are
specification_tags.
Testing#
Test the router with the broker it owns:
test_app.py
async with TestPubSubBroker(router.broker) as br:
await br.publish({"id": 1}, "orders")
bill.mock.assert_called_once_with({"id": 1})
The module also exports PubSubMessage, PubSubBroker, Connection, Context, ContextRepo
and Logger as FastAPI-aware annotations for handler arguments.