FastAPI 0.137.0 refactors internals to preserve router instances
No more route cloning – routers are now stored as trees, unlocking custom subclasses and per-router middleware.
FastAPI 0.137.0, released by creator @tiangolo, introduces a fundamental internal refactor that changes how routers and routes are stored. Previously, using router.include_router(other_router) would clone each path operation from the included router, effectively flattening everything into a single top-level router. Now, the framework preserves the original APIRouter and APIRoute instances, maintaining a tree structure that tracks the inclusion hierarchy. This means routes are no longer copied but referenced directly, which saves memory and allows changes to propagate automatically – for example, adding a path operation to a subrouter after it has been included in the main router will now work immediately.
This change comes with a breaking modification: router.routes is no longer a simple list of APIRoute objects. It can now contain intermediate objects that form a tree, so any code that iterated over router.routes expecting a flat list will need to be updated. The real win is what this unlocks. The release introduces two new alpha methods on APIRouter – .matches() and .handle() – which let developers customize how a router matches and handles incoming requests (e.g., routing based on custom headers). More importantly, this architecture sets the stage for future per-router features such as dependencies, exception handlers, and middleware, which have been long-requested. While still experimental, FastAPI 0.137.0 is a major step toward more flexible, hierarchical API design.
- Router inclusions now preserve APIRouter/APIRoute instances instead of cloning, creating a tree structure.
- Breaking change: router.routes is no longer a plain list but a tree of intermediate objects; custom iteration code may break.
- Alpha features include custom .matches() and .handle() methods on routers, enabling per-router request handling, with future support for per-router dependencies, exception handlers, and middleware.
Why It Matters
Preserving router instances enables per-router customisation, unlocking advanced request handling patterns for large-scale FastAPI applications.