Skip to content

Commit b965e33

Browse files
committed
Add ability to override default root APIRouter class
1 parent ea839df commit b965e33

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

fastapi/applications.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -810,6 +810,14 @@ class Item(BaseModel):
810810
"""
811811
),
812812
] = True,
813+
router_class: Annotated[
814+
Type[routing.APIRouter],
815+
Doc(
816+
"""
817+
Custom router class to be used by this application.
818+
""",
819+
),
820+
] = routing.APIRouter,
813821
**extra: Annotated[
814822
Any,
815823
Doc(
@@ -929,7 +937,7 @@ class Item(BaseModel):
929937
"""
930938
),
931939
] = {}
932-
self.router: routing.APIRouter = routing.APIRouter(
940+
self.router: routing.APIRouter = router_class(
933941
routes=routes,
934942
redirect_slashes=redirect_slashes,
935943
dependency_overrides_provider=self,

tests/test_custom_router_class.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
from fastapi import APIRouter, FastAPI, status
2+
from fastapi.testclient import TestClient
3+
from starlette.datastructures import MutableHeaders
4+
5+
6+
class CustomAPIRouter(APIRouter):
7+
async def __call__(self, scope, receive, send):
8+
async def send_wrapper(message):
9+
if message["type"] == "http.response.start":
10+
headers = MutableHeaders(scope=message)
11+
headers["x-custom-header"] = "custom-value"
12+
13+
await send(message)
14+
15+
await super().__call__(scope, receive, send_wrapper)
16+
17+
18+
app = FastAPI(
19+
router_class=CustomAPIRouter,
20+
)
21+
22+
23+
@app.get("/")
24+
def get_root():
25+
return {"message": "root"}
26+
27+
28+
client = TestClient(app)
29+
30+
31+
def test_get():
32+
response = client.get("/")
33+
34+
assert response.status_code == status.HTTP_200_OK
35+
assert response.json() == {"message": "root"}
36+
assert response.headers["x-custom-header"] == "custom-value"
37+
38+
39+
def test_route_classes():
40+
assert isinstance(app.router, CustomAPIRouter)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy