websocket_route does not work like I expect it should #8979
-
First check
ExampleHere's a self-contained minimal, reproducible, example with my use case: from fastapi import FastAPI
from fastapi.testclient import TestClient
from fastapi.websockets import WebSocket
app = FastAPI()
@app.websocket_route("/ws/{arg}/something")
async def websocket(arg, websocket: WebSocket):
await websocket.accept()
await websocket.send_json({"msg": "Hello WebSocket"})
await websocket.close()
def test_websocket():
client = TestClient(app)
with client.websocket_connect("/ws/this/something") as websocket:
data = websocket.receive_json()
assert data == {"msg": "Hello WebSocket"}
test_websocket()DescriptionI copied and slightly modfied the example from https://fastapi.tiangolo.com/advanced/testing-websockets/ . The issue is that fastapi.routing.APIRouter inherits from starlette.routing.Router, and so websocket_route is inherited from there, and it does not do dependency injection which is quite confusing. The APIRouter should either remove that method, clearly document it or override it so that a consistent interface is provided.
The solution you would likeFix up the example to use websocket instead of websocket_route (for people using a version of FastAPI that does not yet have the fix). Add websocket_route as an alias for websocket so that starlette's version does not get used. Describe alternatives you've consideredAs documented, I am now using websocket instead of websocket_route, but the project could be improved by making the changes above. Environment
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
websocket_route doesn't take any body parameters. Websockets does. |
Beta Was this translation helpful? Give feedback.
-
|
The query parameters are passed through and accessible if you use the (lower level) Starlette You just don't get them as function/method arguments like FastAPI abstracts for you. |
Beta Was this translation helpful? Give feedback.
websocket_route doesn't take any body parameters. Websockets does.
This will resolve the issue: