Skip to content

FastAPI

  • Start here: Request handlers and the ambient scope
  • Common recipes: app.add_middleware(GrelmicroMiddleware, micro=micro) binds the active app inside request handlers, so patterns resolve their backends ambiently without explicit backend= wiring. health_router() adds the /livez, /readyz, and /healthz endpoints.

grelmicro.integrations.fastapi

FastAPI integration: middleware, install helper, and health router.

GrelmicroMiddleware

GrelmicroMiddleware(app: ASGIApp, *, micro: Grelmicro)

Bind the active Grelmicro app for the duration of each request.

A request handler runs in its own task, outside the async with micro: block, so Grelmicro.current() and the ambient backend= resolution it powers do not see the app there. This middleware sets the active app for the request task, so Lock("cart"), RateLimiter.sliding_window(...), and @cached resolve ambiently inside the handler exactly as they do in a task.

from contextlib import asynccontextmanager

from fastapi import FastAPI

from grelmicro import Grelmicro
from grelmicro.integrations.fastapi import GrelmicroMiddleware

micro = Grelmicro(uses=[...])

@asynccontextmanager
async def lifespan(app: FastAPI):
    async with micro:
        yield

app = FastAPI(lifespan=lifespan)
app.add_middleware(GrelmicroMiddleware, micro=micro)

Open the app in the framework lifespan so its components are registered before any request arrives. The middleware is pure ASGI and works with any ASGI framework (Starlette, Litestar, ...). It binds on http and websocket scopes and passes the lifespan scope through untouched.

Initialize the middleware with the app to bind.

PARAMETER DESCRIPTION
app

The next ASGI application in the middleware chain.

TYPE: ASGIApp

micro

The Grelmicro app to bind for each request. Open it in the framework lifespan so its components are ready.

TYPE: Grelmicro

app instance-attribute

app = app

micro instance-attribute

micro = micro

CheckResultResponse

Bases: BaseModel

Health status of a single check.

status instance-attribute

status: HealthStatus

critical class-attribute instance-attribute

critical: bool = True

error class-attribute instance-attribute

error: str | None = None

details class-attribute instance-attribute

details: dict[str, Any] | None = None

HealthzResponse

Bases: BaseModel

Aggregate health report.

status instance-attribute

status: HealthStatus

checks instance-attribute

checks: dict[str, CheckResultResponse]

health_router

health_router(
    registry: HealthChecks | None = None,
    *,
    prefix: str = "",
    show_details: bool | Depends = False,
    healthz_dependencies: list[Depends] | None = None,
) -> APIRouter

Create a FastAPI router with health check endpoints.

Provides three endpoints:

  • GET/HEAD {prefix}/livez: Liveness probe. Never runs checkers. Always returns 200 with an empty body.
  • GET/HEAD {prefix}/readyz: Readiness probe. Runs critical checkers only. Returns 200 or 503 with an empty body.
  • GET/HEAD {prefix}/healthz: Aggregate JSON report.

All responses set Cache-Control: no-store.

PARAMETER DESCRIPTION
registry

Health checks instance whose checks the router runs. When omitted, the router resolves the default instance from the active Grelmicro app (Grelmicro(uses=[HealthChecks(...)])).

TYPE: HealthChecks | None DEFAULT: None

prefix

URL prefix for health endpoints (e.g. '/api/v1').

TYPE: str DEFAULT: ''

show_details

Whether /healthz includes each check's verbose details field (versions, hostnames, pool stats, ...):

  • False (default): details are stripped. Safe for public endpoints.
  • True: details are always included. Use only if /healthz is private.
  • Depends(fn) where fn returns bool: wires fn into FastAPI's DI graph, so Depends chains, yield cleanup, Security, Request injection, and async all work naturally. Return True to show details, False to strip them. Raising HTTPException blocks the endpoint, so return False instead when you want a soft strip.

TYPE: bool | Depends DEFAULT: False

healthz_dependencies

FastAPI dependencies applied to /healthz. A failing dependency blocks the entire endpoint (401/403). Use to hide /healthz from the public while leaving /livez and /readyz open to orchestrators and load balancers. Independent of show_details.

TYPE: list[Depends] | None DEFAULT: None

RAISES DESCRIPTION
DependencyNotFoundError

If fastapi is not installed.

TypeError

If show_details is neither a bool nor a Depends(...) value.