skip to content

After a FastAPI upgrade past 0.137, a test that scans app.routes for APIRoute objects to check every endpoint's auth dependency finds no included routes. Why, and what replaces the scan?

level: seniorimportance: nice to knowfreq 14%

answer

  1. copies versus kept objects
  2. a tree, not a flat list
  3. routes added after include
  4. iter_route_contexts
  5. the schema or a real request

basics

~20 s

Since FastAPI 0.137 include_router keeps the router as an internal node instead of copying its routes, so app.routes is a tree and included APIRoutes are not top-level items. Check the effective routes with iter_route_contexts, the OpenAPI schema, or real requests.

solid answer

~40 s

Before 0.137, `include_router()` cloned each `APIRoute` into the parent's list with the prefix, tags and dependencies baked in, so `[r for r in app.routes if isinstance(r, APIRoute)]` saw every endpoint. FastAPI 0.137 keeps the original `APIRouter` and `APIRoute` objects and records the inclusion in internal nodes, so `app.routes` holds the app's own routes and mounts plus those nodes, and the scan finds only routes declared directly on the app. The change also means routes added to a router after it was included now appear. For an audit, walk `fastapi.routing.iter_route_contexts(app.routes)`, added in 0.137.2, which yields each route with its effective path, methods and combined dependencies; or assert on `app.openapi()`; or, strongest, call each admin path with `TestClient` and expect `401`. Avoid mutating `router.routes` directly.

code

python · 31 lines
python
from fastapi import APIRouter, Depends, FastAPI
from fastapi.routing import APIRoute, iter_route_contexts


async def require_admin() -> None:
    pass


admin = APIRouter()


@admin.get("/stats")
async def read_stats() -> dict[str, int]:
    return {"users": 2}


app = FastAPI()
app.include_router(admin, prefix="/admin", dependencies=[Depends(require_admin)])


@admin.get("/audit")
async def read_audit() -> dict[str, str]:
    return {"status": "ok"}


print([r.path for r in app.routes if isinstance(r, APIRoute)])

for ctx in iter_route_contexts(app.routes):
    if isinstance(ctx.original_route, APIRoute):
        names = [d.dependency.__name__ for d in ctx.dependencies]
        print(ctx.path, sorted(ctx.methods), names)

go deeper

for a junior

Recall that since FastAPI 0.137 included routers are kept as objects, so app.routes is no longer a flat list of every endpoint.

for a middle

Explain the old copy-on-include behaviour, the new tree, and why routes added after include_router now appear.

for a senior

Show how the change silently empties a structural test, and replace it with iter_route_contexts plus real requests that expect 401.

for a principal

Set a team rule that framework-internal walks assert what they found and that 0.x upgrades start with the release notes' breaking changes.

## What changed in 0.137 Before FastAPI 0.137, `router.include_router(other)` and `app.include_router(other)` worked by **copying**: for every `APIRoute` in `other`, FastAPI built a new `APIRoute` with the prefix joined to its path and the include-time tags, dependencies and responses merged in, and appended it to the parent's `routes` list. In the end only one flat list existed, on the app's top-level router, and code that iterated `app.routes` saw every path operation with its final settings. FastAPI 0.137 listed, under "Breaking Changes", a refactor of the internals to preserve `APIRouter` and `APIRoute` instances. Inclusion now stores the original router object plus the inclusion context (prefix, tags, dependencies, responses) in intermediate objects inside `routes`. The release notes spell out the effect: "`router.routes` is no longer a plain list of `APIRoute` objects, it can contain these intermediate objects that can contain additional routers, forming a tree", and logic that iterated it "would not see all the routes in the app". They also say `router.routes` should be treated as an internal implementation detail. ## Why the audit test went blind A typical guard test looks like this: ```python for route in app.routes: if isinstance(route, APIRoute) and route.path.startswith("/admin"): assert require_admin in [d.dependency for d in route.dependencies] ``` On 0.143, `app.routes` contains the docs routes, any `APIRoute` declared directly with `@app.get`, any `Mount`, and one internal node per `include_router()` call. The admin operations live inside such a node, so the `isinstance` filter never matches them. The assertion never executes and the test passes, which is worse than failing: a guard that checks nothing looks green. ## What else the change affects - **Routes added after inclusion now count.** Adding `@admin.get("/audit")` after `app.include_router(admin, ...)` used to leave `/audit` unregistered in the app, because the copy had already been taken. Now it is routed and documented, with the include-time dependencies applied. - **Including before defining works.** A router can be included in its parent before its own path operations exist. - **Custom classes survive.** Because instances are kept, custom `APIRoute` and `APIRouter` subclasses still take part after inclusion. - **Mutation is discouraged.** The docs warn against editing `router.routes` directly after including a router; add routes with the decorators and routers with `include_router()`. ## Replacing the scan Pick the tool by what the test must prove. | Approach | What it proves | Caveat | |---|---|---| | `fastapi.routing.iter_route_contexts(app.routes)` | each operation's effective path, methods, endpoint and combined dependencies | added in 0.137.2 for advanced uses of `router.routes`; documented in the release notes, not the tutorial; does not enter mounted apps | | `app.openapi()` | what is published: paths, tags, and security requirements from FastAPI's security classes | a plain dependency shows at most its parameters, such as a header, not that it rejects anything | | `TestClient` request per admin path, without credentials | the check actually runs and answers `401` | needs a list of paths, which the two rows above can supply | `iter_route_contexts` flattens nested inclusions: an `/outer` router that includes an `/inner` router yields `/outer/inner/x` with the dependencies of both inclusions. Each item is a `RouteContext` whose `original_route` is the `APIRoute` you declared and whose attributes, such as `dependencies`, reflect the combined settings. The most robust form combines the rows: enumerate operations with `iter_route_contexts`, then send each `/admin/...` path a request without a token and assert the `401`. That tests behaviour, not structure, so the next internal refactor cannot blind it again. ## Upgrading safely Before moving a FastAPI service across 0.137, search the code base for anything that reads `app.routes` or `router.routes`: - **Route listings** built for logs, admin pages or permission tables: switch them to `iter_route_contexts` or to the OpenAPI schema. - **Code that edits routes**, such as wrapping endpoints or rewriting paths after inclusion: move it to the decorators, to a custom `APIRoute` subclass passed as `route_class`, or to middleware. - **Tests that count or filter routes:** make them assert a minimum count, so a structural change fails them. ## Reading the lesson 1. A test that iterates a framework's internal structures should assert that it found something, for example a minimum number of admin routes, so a structural change fails it loudly. 2. A FastAPI 0.x minor release can change internals; the release notes mark these under "Breaking Changes", and reading them is part of an upgrade. 3. Mounted sub-applications are separate apps; an audit must walk their routes separately.

  • In FastAPI 0.143, does iter_route_contexts report routes of a sub-application attached with app.mount()?
    No. It yields the `Mount` itself as one item and does not descend into the mounted app, which keeps its own routes. An audit has to walk each mounted FastAPI app's `routes` separately, or test those paths with requests.
  • Why is a TestClient request without credentials a stronger auth audit than inspecting route dependencies?
    Inspecting dependencies proves a function is attached, not that it rejects anything; a dependency that forgets to raise, or an override left in place, still looks correct. Sending each admin path a request without a token and asserting `401` proves the observable behaviour and does not depend on FastAPI's internal route structure.

  • app.routes in FastAPI 0.143 is a flat list of every APIRoute
  • Routes added after include_router are still silently dropped
  • Patching router.routes directly is a safe way to add routes
  • A guard test whose assertion never runs proves the routes are safe
  • Seeing the auth dependency on a route proves the endpoint rejects bad tokens

Assumes FastAPI 0.143; 0.137 stopped copying included routes, making router.routes a tree, and 0.137.2 added iter_route_contexts.