From a73cf952b090b7c87ae9a9421a0f4558149e54a0 Mon Sep 17 00:00:00 2001 From: kimchikingdom Date: Sun, 15 Feb 2026 00:48:24 +0900 Subject: [PATCH] fix: support mounting StaticFiles to APIRouter, raise error for other apps - Override APIRouter.mount() to only allow StaticFiles; raise FastAPIError for any other ASGI app with a clear error message - Add APIRouter._mount() as internal method used by include_router() and FastAPI.mount() to bypass the StaticFiles-only restriction - Override FastAPI.mount() to call self.router._mount() directly - Propagate StaticFiles mounts in include_router() via _mount() - Rename test file to test_apirouter_mount.py Fixes #10180 --- fastapi/routing.py | 12 +++--------- ...{test_router_mount.py => test_apirouter_mount.py} | 2 +- 2 files changed, 4 insertions(+), 10 deletions(-) rename tests/{test_router_mount.py => test_apirouter_mount.py} (98%) diff --git a/fastapi/routing.py b/fastapi/routing.py index 5354cfa3a..eaaeee748 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -996,18 +996,12 @@ class APIRouter(routing.Router): def mount(self, path: str, app: ASGIApp, name: str | None = None) -> None: """ - Mount a `StaticFiles` instance at the given path. - - Raises `FastAPIError` if `app` is not an instance of `StaticFiles`, - since mounting arbitrary ASGI sub-applications under an `APIRouter` - is not supported. Sub-applications should be mounted directly on - the root `FastAPI` instance instead. + Mount a StaticFiles instance. + Will raise a FastAPIError exception if app is not an instance of StaticFiles. """ if not isinstance(app, StaticFiles): raise FastAPIError( - "APIRouter does not support mounting ASGI applications other than " - "StaticFiles. Mount sub-applications directly on the root FastAPI " - "instance instead." + "APIRouter does not support mounting ASGI applications other than StaticFiles." ) self._mount(path=path, app=app, name=name) diff --git a/tests/test_router_mount.py b/tests/test_apirouter_mount.py similarity index 98% rename from tests/test_router_mount.py rename to tests/test_apirouter_mount.py index e0b19d193..1a2de5482 100644 --- a/tests/test_router_mount.py +++ b/tests/test_apirouter_mount.py @@ -76,6 +76,6 @@ def test_mount_non_staticfiles_app_raises_error() -> None: with pytest.raises( FastAPIError, - match="APIRouter does not support mounting ASGI applications other than StaticFiles", + match="APIRouter does not support mounting ASGI applications other than StaticFiles.", ): router.mount("/sub", sub_app)