8000 ✨ Add ignore trailing slashes option to `FastAPI` class by Synrom · Pull Request #12145 · fastapi/fastapi · GitHub
[go: up one dir, main page]

Skip to content

✨ Add ignore trailing slashes option to FastAPI class #12145

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add ignore_trailing_slashes flag to applications
  • Loading branch information
Synrom committed Sep 4, 2024
commit d4eaafb8043a988701ff965c1c061c586b27f9ff
14 changes: 14 additions & 0 deletions fastapi/applications.py
Original file line number Diff line number Diff line change
Expand Up @@ -810,6 +810,13 @@ class Item(BaseModel):
"""
),
] = True,
ignore_trailing_whitespaces: Annotated[
bool,
Doc(
"""
"""
),
] = False,
**extra: Annotated[
Any,
Doc(
Expand Down Expand Up @@ -943,6 +950,7 @@ class Item(BaseModel):
include_in_schema=include_in_schema,
responses=responses,
generate_unique_id_function=generate_unique_id_function,
ignore_trailing_whitespaces=ignore_trailing_whitespaces,
)
self.exception_handlers: Dict[
Any, Callable[[Request, Any], Union[Response, Awaitable[Response]]]
Expand All @@ -961,6 +969,12 @@ class Item(BaseModel):
[] if middleware is None else list(middleware)
)
self.middleware_stack: Union[ASGIApp, None] = None

if ignore_trailing_whitespaces:
async def middleware_ignore_tailing_whitespace(request: Request, call_next):
request.scope["path"] = request.scope["path"].rstrip("/")
return await call_next(request)
self.add_middleware(BaseHTTPMiddleware, dispatch=middleware_ignore_tailing_whitespace)
self.setup()

def openapi(self) -> Dict[str, Any]:
Expand Down
27 changes: 23 additions & 4 deletions fastapi/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -811,6 +811,13 @@ def __init__(
"""
),
] = Default(generate_unique_id),
ignore_trailing_whitespaces: Annotated[
bool,
Doc(
"""
"""
),
] = False,
) -> None:
super().__init__(
routes=routes,
Expand All @@ -836,6 +843,7 @@ def __init__(
self.route_class = route_class
self.default_response_ 10000 class = default_response_class
self.generate_unique_id_function = generate_unique_id_function
self.ignore_trailing_whitespaces = ignore_trailing_whitespaces

def route(
self,
Expand All @@ -844,6 +852,8 @@ def route(
name: Optional[str] = None,
include_in_schema: bool = True,
) -> Callable[[DecoratedCallable], DecoratedCallable]:
if self.ignore_trailing_whitespaces:
path = path.rstrip("/")
def decorator(func: DecoratedCallable) -> DecoratedCallable:
self.add_route(
path,
Expand Down Expand Up @@ -890,6 +900,8 @@ def add_api_route(
Callable[[APIRoute], str], DefaultPlaceholder
] = Default(generate_unique_id),
) -> None:
if self.ignore_trailing_whitespaces:
path = path.rstrip("/")
route_class = route_class_override or self.route_class
responses = responses or {}
combined_responses = {**self.responses, **responses}
Expand Down Expand Up @@ -1008,6 +1020,8 @@ def add_api_websocket_route(
*,
dependencies: Optional[Sequence[params.Depends]] = None,
) -> None:
if self.ignore_trailing_whitespaces:
path = path.rstrip("/")
current_dependencies = self.dependencies.copy()
if dependencies:
current_dependencies.extend(dependencies)
Expand Down Expand Up @@ -1091,6 +1105,8 @@ def decorator(func: DecoratedCallable) -> DecoratedCallable:
def websocket_route(
self, path: str, name: Union[str, None] = None
) -> Callable[[DecoratedCallable], DecoratedCallable]:
if self.ignore_trailing_whitespaces:
path = path.rstrip("/")
def decorator(func: DecoratedCallable) -> DecoratedCallable:
self.add_websocket_route(path, func, name=name)
return func
Expand Down Expand Up @@ -1248,6 +1264,9 @@ def read_users():
if responses is None:
responses = {}
for route in router.routes:
path = route.path
if self.ignore_trailing_whitespaces:
path = path.rstrip("/")
if isinstance(route, APIRoute):
combined_responses = {**responses, **route.responses}
use_response_class = get_value_or_default(
Expand Down Expand Up @@ -1278,7 +1297,7 @@ def read_users():
self.generate_unique_id_function,
)
self.add_api_route(
prefix + route.path,
prefix + path,
route.endpoint,
response_model=route.response_model,
status_code=route.status_code,
Expand Down Expand Up @@ -1310,7 +1329,7 @@ def read_users():
elif isinstance(route, routing.Route):
methods = list(route.methods or [])
self.add_route(
prefix + route.path,
prefix + path,
route.endpoint,
methods=methods,
include_in_schema=route.include_in_schema,
Expand All @@ -1323,14 +1342,14 @@ def read_users():
if route.dependencies:
current_dependencies.extend(route.dependencies)
self.add_api_websocket_route(
prefix + route.path,
prefix + path,
route.endpoint,
dependencies=current_dependencies,
name=route.name,
)
elif isinstance(route, routing.WebSocketRoute):
self.add_websocket_route(
prefix + route.path, route.endpoint, name=route.name
prefix + path, route.endpoint, name=route.name
)
for handler in router.on_startup:
self.add_event_handler("startup", handler)
Expand Down
29 changes: 29 additions & 0 deletions tests/test_ignore_trailing_slash.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from fastapi import FastAPI
from fastapi.testclient import TestClient

recognizing_app = FastAPI()
ignoring_app = FastAPI(ignore_trailing_whitespaces=True)

@recognizing_app.get("/example")
@ignoring_app.get("/example")
async def return_data():
return {"msg": "Reached the route!"}

recognizing_client = TestClient(recognizing_app)
ignoring_client = TestClient(ignoring_app)

def test_recognizing_trailing_slash():
response = recognizing_client.get("/example", follow_redirects=False)
assert response.status_code == 200
assert response.json()["msg"] == "Reached the route!"
response = recognizing_client.get("/example/", follow_redirects=False)
assert response.status_code == 307
assert response.headers["location"].endswith("/example")

def test_ignoring_trailing_slash():
response = ignoring_client.get("/example", follow_redirects=False)
assert response.status_code == 200
assert response.json()["msg"] == "Reached the route!"
response = ignoring_client.get("/example/", follow_redirects=False)
assert response.status_code == 200
assert response.json()["msg"] == "Reached the route!"
0