CBV Router fails when path is empty
vinvinod opened this issue · comments
Describe the bug
When the router path is empty string, cbv router fails.
File "./test.py", line 11, in <module>
@cbv(router)
File "/Users/vinod/.pyenv/versions/3.6.10/envs/test/lib/python3.6/site-packages/fastapi_utils/cbv.py", line 26, in decorator
return _cbv(router, cls)
File "/Users/vinod/.pyenv/versions/3.6.10/envs/test/lib/python3.6/site-packages/fastapi_utils/cbv.py", line 49, in _cbv
router.include_router(cbv_router)
File "/Users/vinod/.pyenv/versions/3.6.10/envs/test/lib/python3.6/site-packages/fastapi/routing.py", line 584, in include_router
f"Prefix and path cannot be both empty (path operation: {name})"
Exception: Prefix and path cannot be both empty (path operation: get_items)
To Reproduce
Steps to reproduce the behavior:
- Create a file
test.py
:
from fastapi import APIRouter
from fastapi import FastAPI
from fastapi_utils.cbv import cbv
main_router = APIRouter()
child_router = APIRouter()
@cbv(child_router)
class MyClass:
@child_router.get("")
def get_items(self):
return {"hello": "world"}
main_router.include_router(child_router, prefix="/items")
app = FastAPI()
app.include_router(main_router)
- Start the server with
uvicorn --reload test:app
Expected behavior
The uvicorn server to start normally. The end point http://localhost:8000/items
should return {"hello": "world"}
Environment:
-
OS: [e.g. macOS]
-
FastAPI Utils, FastAPI, and Pydantic versions
- fastapi==0.55.1
- fastapi-utils==0.2.1
- pydantic==1.4
-
Python version: 3.6.10
Additional context
This is because because the cbv helper is including a third router under child router. FastAPI throws an error when both path and prefix are empty.
If I use @child_router.get("/")
instead of @child_router.get("")
and it is working. FastAPI responds with 307 to redirect the user to right endpoint. Since some http clients are not handling 307 correctly, is there a way to support empty path strings with cbv.