alexschimpf / fastapi-versionizer

FastAPI Versionizer
MIT License
79 stars 13 forks source link

Route class from APIRouter is not getting forward on versionizer #52

Open yuripiratello opened 6 months ago

yuripiratello commented 6 months ago

Subject of the issue

If you set a router class on the Router, the versioned class doesn't receive the same router class.

Your environment

Python 3.11.7 Ubuntu 20 fastapi-versionizer 3.0.4

Steps to reproduce


class CustomRoute(APIRoute):
    def get_route_handler(self) -> Callable:
        original_route_handler = super().get_route_handler()

        async def custom_route_handler(request: Request) -> Response:
            print("debug")
            return await original_route_handler(request)

        return custom_route_handler

users_router = APIRouter(
    prefix='/users',
    tags=['Users'],
    route_class=CustomRoute,
)

@api_version(1)
@users_router.get('')
def get_users() -> List[User]:
    return list(db.users.values())

Expected behaviour

It should identify the route class isn't the default APIRoute and pass it as a parameter to router.add_api_route(**kwargs).

Actual behaviour

The custom_route_handler is never called because the Route class is always APIRoute.

I changed these lines on versionizer, and it worked. Is there any other way to resolve this?


    @staticmethod
    def _add_route_to_router(
        route: Union[APIRoute, APIWebSocketRoute],
        router: APIRouter,
        version: Tuple[int, int]
    ) -> None:
        kwargs = dict(route.__dict__)
        if route.__class__ != APIRoute: # <---
            kwargs['route_class_override'] = route.__class__ # <---