fix: enable mounting sub-applications under APIRouter#14793
fix: enable mounting sub-applications under APIRouter#14793jonathan-fulton wants to merge 1 commit intofastapi:masterfrom
Conversation
Added support for mounting sub-applications on APIRouter with proper
prefix handling:
1. Override mount() in APIRouter to automatically apply the router's
prefix to the mount path
2. Handle Mount routes in include_router() to apply the include prefix
This allows patterns like:
router = APIRouter(prefix='/api')
router.mount('/subapp', FastAPI())
app.include_router(router)
Which correctly routes requests to /api/subapp/...
Note: Mounts must be added before include_router() is called, as
include_router copies routes at call time. This is consistent with
how other routes work.
Fixes fastapi#10180
|
I think we should wait for Sebastian to take a decision on whether we want to support this. |
|
@YuriiMotov Thanks for the feedback! That makes sense - I'll wait for Sebastian's decision on whether this should be supported more broadly or limited to StaticFiles. I agree that for full apps, using Happy to adjust the scope based on Sebastian's guidance! |
I implemented that approach in #13944 |
|
One additional regression test that may be worth adding here is mounted sub-app OpenAPI behavior. The original issue also mentioned docs/spec URLs, so it would be useful to assert that a sub-application mounted through APIRouter is reachable at its expected schema URL, for example /api/subapi/openapi.json when the router prefix is /api and the mount path is /subapi. That helps verify not only request routing but also that the mounted app gets the correct composed path/root_path behavior. |
Summary
Fixes #10180
When mounting a sub-application on an
APIRouterwith a prefix, the mount wasn't accessible at the expected path. The router's prefix wasn't being applied to mounts.Changes
mount()inAPIRouterto automatically apply the router's prefixMountroutes ininclude_router()to apply the include prefixUsage
Enables patterns like:
Note: Mounts must be added before
include_router()is called.Testing
Added comprehensive tests in
tests/test_router_mount.py