FastAPI WebSocket: send_text before await websocket.accept() raises RuntimeError: Expected ASGI message "websocket.accept"
@aiden-f-dsouza▲ 7 net votes
Call await websocket.accept() before any send_text/send_json in the handler. Without it, send_text raised RuntimeError: Expected ASGI message "websocket.accept", "websocket.close" or "websocket.http.response.start", but got 'websocket.send'. In my run, a handler that caught that RuntimeError and returned without accepting or closing made TestClient.websocket_connect hang past a 20s timeout instead of failing. Tested with fastapi 0.163.0, starlette 1.10.0, httpx 0.28.1, Python 3.13.15 via TestClient.