Skip to content

[BUG] Error When Register Endpoint for Router of Instance of APIWebSocketRoute #359

@HideyoshiNakazone

Description

@HideyoshiNakazone

Describe the bug
When trying to add a @router.websocket endpoint to a CBV Router the following exception is throw:

Traceback (most recent call last):
  File "/home/user/Downloads/teste/main.py", line 7, in <module>
    @cbv(router)
     ^^^^^^^^^^^
  File "/home/user/.cache/pypoetry/virtualenvs/teste-4HLGbWUH-py3.12/lib/python3.12/site-packages/fastapi_utils/cbv.py", line 46, in decorator
    return _cbv(router, cls, *urls)
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/.cache/pypoetry/virtualenvs/teste-4HLGbWUH-py3.12/lib/python3.12/site-packages/fastapi_utils/cbv.py", line 57, in _cbv
    _register_endpoints(router, cls, *urls)
  File "/home/user/.cache/pypoetry/virtualenvs/teste-4HLGbWUH-py3.12/lib/python3.12/site-packages/fastapi_utils/cbv.py", line 112, in _register_endpoints
    raise ValueError("The provided routes should be of type APIRoute")
ValueError: The provided routes should be of type APIRoute

To Reproduce

from fastapi import FastAPI, WebSocket, WebSocketDisconnect, APIRouter
from fastapi_utils.cbv import cbv

app = FastAPI()
router = APIRouter()

@cbv(router)
class WebSocketCBV:
    @router.websocket("/ws")
    async def websocket_endpoint(self, websocket: WebSocket):
        await websocket.accept()
        try:
            while True:
                data = await websocket.receive_text()
                await websocket.send_text(f"Message text was: {data}")
        except WebSocketDisconnect:
            print("Client disconnected")

app.include_router(router)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

Expected behavior
It to work since in your code the class WebSocketRoute is supported

Environment:
Python Version: 3.12

Package Versions:

  • fastapi: 0.115.8
  • fastapi-utils: 0.8.0

Additional context
Suggested solution in PR #358

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions