mirror of
https://github.com/rommapp/romm.git
synced 2026-12-03 10:33:22 +01:00
According to multiple FastAPI discussions [1], FastAPI only includes a built-in mechanism to redirect requests including a trailing slash, to its variation without slash, using a `307` status code. This can be an issue when certain clients do not send the same headers on the redirected request. This change adds a custom FastAPI `APIRouter`, that registers both route path variations (with and without trailing slash), while only marking the path without slash for being included in the OpenAPI schema. [1] https://github.com/fastapi/fastapi/discussions/7298
36 lines
1.1 KiB
Python
36 lines
1.1 KiB
Python
from typing import Any, Callable
|
|
|
|
from fastapi import APIRouter as FastAPIRouter
|
|
from fastapi.types import DecoratedCallable
|
|
|
|
|
|
class APIRouter(FastAPIRouter):
|
|
"""FastAPI router that automatically adds an alternate route with a trailing slash.
|
|
|
|
This is needed as FastAPI does not include a built-in way to handle routes with and without
|
|
trailing slashes, without requiring a redirect or duplicating the route definition.
|
|
|
|
Reference: https://github.com/fastapi/fastapi/discussions/7298
|
|
"""
|
|
|
|
def api_route(
|
|
self, path: str, *, include_in_schema: bool = True, **kwargs: Any
|
|
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
|
if path.endswith("/") and len(path) > 1:
|
|
path = path[:-1]
|
|
|
|
add_path = super().api_route(
|
|
path, include_in_schema=include_in_schema, **kwargs
|
|
)
|
|
|
|
alternate_path = path + "/"
|
|
add_alternate_path = super().api_route(
|
|
alternate_path, include_in_schema=False, **kwargs
|
|
)
|
|
|
|
def decorator(func: DecoratedCallable) -> DecoratedCallable:
|
|
add_alternate_path(func)
|
|
return add_path(func)
|
|
|
|
return decorator
|