Skip to content

FastAPI Integration

rabbitkit_lifespan(app: Any = None, *, broker: Any | None = None, rabbit_app: Any | None = None) -> AsyncIterator[None] async

Async context manager that starts/stops rabbitkit components.

Suitable for use as FastAPI's lifespan parameter or standalone.

Start order: rabbit_app.start_async() → broker.start() / broker.start_async() Stop order (in finally): broker.stop() / broker.stop_async() → rabbit_app.stop_async()

Duck-types sync vs async: if the method is a coroutine, it is awaited.

Parameters:

Name Type Description Default
app Any

FastAPI app instance (passed by FastAPI lifespan protocol, may be None).

None
broker Any | None

Optional rabbitkit broker (SyncBroker or AsyncBroker).

None
rabbit_app Any | None

Optional RabbitApp for lifecycle hooks.

None
Source code in src/rabbitkit/fastapi.py
@asynccontextmanager
async def rabbitkit_lifespan(
    app: Any = None,
    *,
    broker: Any | None = None,
    rabbit_app: Any | None = None,
) -> AsyncIterator[None]:
    """Async context manager that starts/stops rabbitkit components.

    Suitable for use as FastAPI's ``lifespan`` parameter or standalone.

    Start order: rabbit_app.start_async() → broker.start() / broker.start_async()
    Stop order (in finally): broker.stop() / broker.stop_async() → rabbit_app.stop_async()

    Duck-types sync vs async: if the method is a coroutine, it is awaited.

    Args:
        app: FastAPI app instance (passed by FastAPI lifespan protocol, may be None).
        broker: Optional rabbitkit broker (SyncBroker or AsyncBroker).
        rabbit_app: Optional RabbitApp for lifecycle hooks.
    """
    try:
        # Start rabbit_app first (startup hooks)
        if rabbit_app is not None:
            if hasattr(rabbit_app, "start_async"):
                await rabbit_app.start_async()
            elif hasattr(rabbit_app, "start"):
                result = rabbit_app.start()
                if asyncio.iscoroutine(result):
                    await result

        # Start broker
        if broker is not None:
            if inspect.iscoroutinefunction(getattr(broker, "start", None)):
                await broker.start()
            elif hasattr(broker, "start"):
                broker.start()

        logger.info("rabbitkit lifespan started")
        yield

    finally:
        # Stop broker first
        if broker is not None:
            if inspect.iscoroutinefunction(getattr(broker, "stop", None)):
                await broker.stop()
            elif hasattr(broker, "stop"):
                broker.stop()

        # Stop rabbit_app (shutdown hooks)
        if rabbit_app is not None:
            if hasattr(rabbit_app, "stop_async"):
                await rabbit_app.stop_async()
            elif hasattr(rabbit_app, "stop"):
                result = rabbit_app.stop()
                if asyncio.iscoroutine(result):
                    await result

        logger.info("rabbitkit lifespan stopped")