]> git.ipfire.org Git - thirdparty/fastapi/fastapi.git/commitdiff
✨ Show a clear error on attempt to include router into itself (#14258)
authorJavier Sánchez Castro <72013291+JavierSanchezCastro@users.noreply.github.com>
Tue, 10 Feb 2026 10:58:40 +0000 (11:58 +0100)
committerGitHub <noreply@github.com>
Tue, 10 Feb 2026 10:58:40 +0000 (11:58 +0100)
Co-authored-by: Javier Sánchez <javier.sanchez.castro@bookline.ai>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Motov Yurii <109919500+YuriiMotov@users.noreply.github.com>
fastapi/routing.py
tests/test_router_circular_import.py [new file with mode: 0644]

index 16a89ef3e33176840c33d2397d8e6bc1b5d4f565..ed873fda8ca6ff8763365a7e94aaf5e7223bf0de 100644 (file)
@@ -1393,6 +1393,10 @@ class APIRouter(routing.Router):
         app.include_router(internal_router)
         ```
         """
+        assert self is not router, (
+            "Cannot include the same APIRouter instance into itself. "
+            "Did you mean to include a different router?"
+        )
         if prefix:
             assert prefix.startswith("/"), "A path prefix must start with '/'"
             assert not prefix.endswith("/"), (
diff --git a/tests/test_router_circular_import.py b/tests/test_router_circular_import.py
new file mode 100644 (file)
index 0000000..492a26d
--- /dev/null
@@ -0,0 +1,12 @@
+import pytest
+from fastapi import APIRouter
+
+
+def test_router_circular_import():
+    router = APIRouter()
+
+    with pytest.raises(
+        AssertionError,
+        match="Cannot include the same APIRouter instance into itself. Did you mean to include a different router?",
+    ):
+        router.include_router(router)