fastapi-utils icon indicating copy to clipboard operation
fastapi-utils copied to clipboard

CBV Router fails when path is empty

Open vinvinod opened this issue 5 years ago • 4 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:

  1. 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)
  1. 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.

vinvinod avatar Jul 24 '20 11:07 vinvinod

Closing this in favour of https://github.com/dmontagu/fastapi-utils/issues/154

vinvinod avatar May 14 '21 06:05 vinvinod

For the record, I don't think this was resolved as I still get this error when trying to @router.get("") on a CBV's view (in my case, the router does have a prefix)

martinlatrille avatar Aug 08 '24 16:08 martinlatrille

same here...

nnmer avatar Dec 08 '24 05:12 nnmer

Same here. Doesn't work for me. In my case, the router has a prefix. Here is the minimal code to reproduce:


from fastapi import APIRouter 
from fastapi_utils.cbv import cbv

router = APIRouter(prefix="/users")

@cbv(router)
class UserApi:

    @router.get(path="")
    def find() -> List[User]:
       return None

Thanks.

viklele avatar Feb 13 '25 13:02 viklele