Fast api, sending json response in web socket

9.8k views Asked by At

I have a small WebSocket built with fast api. I'm trying to receive a message from the client, process it, and return a JSON response.

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        story = await websocket.receive_text()
        data = sentiment_analysis(news=story)
# Exmaple out put of sentiment_analysis function: {'compound_score': 0.5856095238095237, 'correlation_score': 0.8736042200587304}

        await websocket.send_json(json.dumps(data))

the message from the client is received and processed as it should, but I can't seem to be able to load the response dictionary to JSON and send it back.

I'm getting an error:

  ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/uvicorn/protocols/websockets/websockets_impl.py", line 153, in run_asgi
    result = await self.app(self.scope, self.asgi_receive, self.asgi_send)
  File "/usr/lib/python3/dist-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/usr/local/lib/python3.8/dist-packages/fastapi/applications.py", line 179, in __call__
    await super().__call__(scope, receive, send)
  File "/usr/local/lib/python3.8/dist-packages/starlette/applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/usr/local/lib/python3.8/dist-packages/starlette/middleware/errors.py", line 146, in __call__
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.8/dist-packages/starlette/exceptions.py", line 58, in __call__
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.8/dist-packages/starlette/routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "/usr/local/lib/python3.8/dist-packages/starlette/routing.py", line 283, in handle
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.8/dist-packages/starlette/routing.py", line 57, in app
    await func(session)
  File "/usr/local/lib/python3.8/dist-packages/fastapi/routing.py", line 228, in app
    await dependant.call(**values)
  File "./app.py", line 20, in websocket_endpoint
    stock = await websocket.receive_text()
  File "/usr/local/lib/python3.8/dist-packages/starlette/websockets.py", line 85, in receive_text
    self._raise_on_disconnect(message)
  File "/usr/local/lib/python3.8/dist-packages/starlette/websockets.py", line 80, in _raise_on_disconnect
    raise WebSocketDisconnect(message["code"])
starlette.websockets.WebSocketDisconnect: 1011

1

There are 1 answers

0
Joe On

If you're using websocket.send_json() then you don't need to do json.dumps() as that is just parsing it into string text.

Also I found that @app.websocket() doesn't work for me and I needed to use the websocket_route() decorator. FastAPI kept throwing the WebSocketDisconnect until I used the websocket_route() decorator.

NOTE: I was using the decorator with APIRouter() and not FastAPI() so take that with a grain of salt, but I believe the latest version of FastAPI supports websocket_route() for both.

The code below should work with those 2 modifications


@app.websocket_route("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        story = await websocket.receive_text()
        data = sentiment_analysis(news=story)
        await websocket.send_json(data)