API reference¶
Every symbol below is exported from the top-level fastapi_router_lazy package
(from fastapi_router_lazy import ...), except RecordingRouteInfosExtractor
and VariantsRouterLoader, which live in fastapi_router_lazy.variants and
require the variants extra.
Loader¶
RouterLoader¶
RouterLoader(
extractor: AbstractRouteInfosExtractor,
app: FastAPI | None = None,
deployments: set[str] | None = None,
)
Mounts routers on demand, one module (and router variable) at a time. Works with
plain fastapi.APIRouter objects. To mount fastapi-router-variants
RouterWrapper objects (including their parent chains), use
VariantsRouterLoader (variants extra) instead.
Key methods:
load(lazy_registry=None)— with no argument, scan every router module and mount each router now, returninglist[LoadedRouter]. Passed aLazyRouteRegistry(such as aLazyMiddlewaresubclass), register a stub per declared route instead and returnNone.load_router(module_name, variables=None)— import one module and mount the given router variable(s); withvariables=None, mount every variable the extractor reports for that module. Returnslist[LoadedRouter].load_router_lazily(module_name, router_variable)—load_routerfor one router variable, then move its routes to their canonical position among the routers already mounted. The middleware calls it on the first request matching a stub.load_routers(module_names)—load_routerover an iterable of modules.load_router_decl(router_decl)/load_router_decls(router_decls)— mount from declarations, each either a module name or a(module_name, variables)tuple.filter_with_deployments(route_infos)— keep only the routes whosedeploymentmatches the loader'sdeploymentsset (orTrue).
flatten_routes¶
Replaces the included-router wrappers that FastAPI 0.137+ include_router
appends with the effective routes they serve. Every route reachable through a
wrapper, nested includes included, is rebuilt with what its includes apply —
prefix, dependencies, tags, responses, include_in_schema, response class,
unique id function, content-type strictness — and bound to the dependency
override provider of the router the include was made on, the way FastAPI 0.136
include_router copied routes. The included router's own routes are never
mutated.
Includes whose router tree holds APIRouter.frontend() routes are kept
wrapped, since FastAPI only serves those through the wrapper. Other routes are
returned unchanged, so the call is a no-op on FastAPI versions before 0.137.
RouterLoader and the plain and sandbox extractors apply it automatically.
reparent_route¶
Binds an HTTP or WebSocket route to another application and rebuilds its ASGI
handler with that application's dependency override provider. Routes returned
by flatten_routes are already bound to the router their include was made on.
FastAPI routes are shallow-copied so a source router remains reusable across
applications; other Starlette route types are returned unchanged.
LoadedRouter¶
The result of mounting one router: the router that was included and the concrete routes it added to the application.
RouterLoaderMeta¶
Stamped onto a mounted router (router._loader_meta) to record where it came
from.
LazyRouteRegistry¶
Abstract base for anything that can register lazy stub routes. Implement the
classmethod register_lazy_routes(module_route_infos). LazyMiddleware
implements it.
Middleware¶
lazy_middleware_factory¶
Build a LazyMiddleware subclass bound to router_loader, ready to pass to
app.add_middleware(...). On the first request matching a stub, the middleware
loads the real router, removes the consumed stubs, and lets the request fall
through. Also exported under its internal name factory.
LazyMiddleware¶
Base ASGI middleware / LazyRouteRegistry. Each subclass built by
lazy_middleware_factory holds the stub routes on its own app_stub: FastAPI.
Notable members:
register_lazy_routes(module_route_infos)— add a stub route (HTTP or websocket) perExtractedRouteInfo.get_stub_matching_route(scope, match=Match.FULL)— find the stub matching a request scope.remove_stub_routes(route_name)— drop the stubs for a loaded router; when the last stub is consumed, an optional_on_all_stubs_consumedcallback fires.
LAZY_LOADING_ROUTER_HEADER¶
The header (module:variable) the middleware sets on the response when it
lazily mounts a router, so you can observe which module was loaded. It is set on
the response only, never injected into the request the handlers see.
Route infos¶
RouteType¶
RouteInfo¶
@dataclass(frozen=True, kw_only=True)
class RouteInfo:
path: str
type: RouteType = "http"
methods: tuple[str, ...] | None = None
Base description of a single route.
ExtractedRouteInfo¶
@dataclass(frozen=True, kw_only=True)
class ExtractedRouteInfo(RouteInfo):
router_variable: str
router_module: str
version: Any = None
prefix: Any = None
deployment: str | bool | None = None
hidden: bool = False
A route discovered by an extractor, carrying enough to mount it without importing
the router: its owning module and router variable, optional version/prefix
(kept opaque so the core stays independent of any versioning scheme), a
deployment tag, and a hidden flag (served but not published). build_variant(path)
returns a copy with a different path.
MetaRouteInfo¶
@dataclass(frozen=True, kw_only=True)
class MetaRouteInfo(RouteInfo):
router_variable: str
version: Any = None
prefix: Any = None
deployment: str | bool | None = None
Manually declared route metadata, for routes defined outside a router.
Extractors¶
AbstractRouteInfosExtractor¶
AbstractRouteInfosExtractor(
defaults: ExtractorDefaultsProtocol,
package_name: str,
*,
router_module_pattern: str = "router.py",
)
Base class for all extractors. Provides scan_router_modules() (walk the
package, yield dotted module names matching the pattern); subclasses implement
extract_module_route_infos(module_name, router_variables=None) and
preload_from_cache(cache).
route_infos_extractor¶
route_infos_extractor(
package_name: str,
*,
defaults: ExtractorDefaultsProtocol | None = None,
extractor: AbstractRouteInfosExtractor | None = None,
cache: bool = False,
cache_file: Path | None = None,
router_module_pattern: str = "router.py",
strict: bool = False,
) -> AbstractRouteInfosExtractor
Factory building an extractor for package_name. Defaults to
PlainRouteInfosExtractor; cache=True wraps it in a CachedRouteInfosExtractor
persisted to cache_file (defaults to ./routes.json).
PlainRouteInfosExtractor¶
Default in-process extractor. Imports each module and reads the routes off its
plain FastAPI routers. Implements InitializableExtractor.
extract_routes_from_module¶
Import one module and read the routes of its FastAPI routers, standalone.
SandboxRouteInfosExtractor¶
SandboxRouteInfosExtractor(
defaults: ExtractorDefaultsProtocol,
package_name: str,
*,
router_module_pattern: str = "router.py",
python_executable: str = sys.executable,
)
Extractor isolating module imports in a subprocess. Implements
InitializableExtractor.
extract_routes_sandboxed¶
extract_routes_sandboxed(
modules: list[str], python_executable: str = sys.executable
) -> list[ExtractedRouteInfo]
Extract routes for a list of modules in an isolated child process.
CachedRouteInfosExtractor¶
CachedRouteInfosExtractor(
defaults: ExtractorDefaultsProtocol,
package_name: str,
cache_file: Path,
extractor: AbstractRouteInfosExtractor,
*,
strict: bool = False,
)
Wraps another extractor with a checksum-keyed JSON cache. Re-extracts only the
modules whose source changed; strict=True raises on a missing or stale cache
instead of re-extracting.
module_checksum¶
Hash of a module's source file — the key a cache entry is stored under when
its router declares no __route_sources__.
verify_route_infos_cache¶
verify_route_infos_cache(
extractor: CachedRouteInfosExtractor,
module_names: Iterable[str] | None = None,
) -> list[RouteInfosCacheMismatch]
Extracts module_names again with the wrapped extractor and compares the result
with the cache; an empty list means the cache is up to date for those modules.
module_names defaults to the routers declaring route sources: pass every
router module to also catch a router that should declare some and does not.
RecordingRouteInfosExtractor (variants extra)¶
from fastapi_router_lazy.variants import RecordingRouteInfosExtractor
RecordingRouteInfosExtractor(
router_wrapper_class: type[RouterWrapper],
package_name: str,
*,
router_module_pattern: str = "router.py",
defaults: ExtractorDefaultsProtocol | None = None,
)
Variant/version-aware extractor. Imports modules under
RouterWrapper.recording(...) to enumerate every expanded variant with full
metadata, without importing route handlers or building the routes. Requires the
variants extra.
VariantsRouterLoader (variants extra)¶
from fastapi_router_lazy.variants import VariantsRouterLoader
VariantsRouterLoader(
extractor: AbstractRouteInfosExtractor,
app: FastAPI | None = None,
deployments: set[str] | None = None,
)
A RouterLoader subclass that also mounts fastapi-router-variants
RouterWrapper objects: it unwraps the wrapper to its underlying APIRouter
(.base) and includes it through every parent wrapper before reaching the
application. Use it in place of RouterLoader when your routers are
RouterWrapper instances. Requires the variants extra.
Supporting types¶
ExtractorDefaultsProtocol¶
Structural protocol for the defaults an extractor relies on — currently a single
deployment: str | None attribute. fastapi_router_variants.RouterDefaults
satisfies it structurally.
ExtractorDefaults¶
Concrete default ExtractorDefaultsProtocol implementation.
InitializableExtractor¶
Mixin for extractors that keep invalidatable in-memory state: init() extracts
every scanned module up front, reset(module_names=None) drops cached state.
CachedExtractedRouteInfos¶
@dataclass
class CachedExtractedRouteInfos:
router_checksums: dict[str, str]
routes: dict[str, list[ExtractedRouteInfo]]
route_sources: dict[str, RouteSources] = field(default_factory=dict)
route_sources_read: bool = False
router_priorities: dict[str, RouterPriority] = field(default_factory=dict)
router_priorities_read: bool = False
The on-disk cache payload: per-module source checksums, the extracted routes,
the route sources of the routers declaring some, and the priorities of the
routers declaring one. route_sources_read and router_priorities_read are
false for a cache written before route sources or router priorities existed.
RouteSources¶
The modules a router declares in __route_sources__. error says why the
declaration is invalid: such a router is re-extracted on every start outside
strict mode.
RouterPriority¶
The ROUTER_LAZY_PRIORITY a router module declares, used in the
route order. error says why the declaration is
invalid: value is then 0 and the router is re-extracted on every start
outside strict mode.
RouteInfosCacheMismatch¶
@dataclass(frozen=True)
class RouteInfosCacheMismatch:
module: str
missing: tuple[ExtractedRouteInfo, ...]
unexpected: tuple[ExtractedRouteInfo, ...]
Returned by verify_route_infos_cache: the route infos a fresh extraction of
module finds and the cache lacks (missing), and those the cache holds and a
fresh extraction does not (unexpected).
__version__¶
The installed package version string.