FastAPI websocket can not connect

Question:

I am trying to let my Vue.js app communicate with my FastAPI(based on starlette) local server using websockets. I tried using the exact same code as in their example: https://fastapi.tiangolo.com/tutorial/websockets/. However something weird happens, because my server can not start with the reason: AttributeError: 'FastAPI' object has no attribute 'websocket'. That is strange because this exact code is the official docs of FastAPI.
After that I used the Starlette example code: https://www.starlette.io/websockets/. However when I try to connect to it, the FastApi prints to the terminal: WARNING: Invalid HTTP request received.
I tried using another client, the Simple WebSocket Client: https://chrome.google.com/webstore/detail/simple-websocket-client/pfdhoblngboilpfeibdedpjgfnlcodoo, but the same error appears on the terminal.
What am I doing wrong here? In the first place I find it weird that the FastAPI code does not seem to work on my computer, does anyone know why?

Thanks in advance!

Asked By: Simon

||

Answers:

Apparently the WebSocket functionality was added in FastAPI 0.24, which was just released. I was using an older version.

Answered By: Simon

run pip install websockets and configure it as following:

from fastapi import FastAPI, WebSocket

@app.websocket("/ws")
async def send_data(websocket:WebSocket):
    print('CONNECTING...')
    await websocket.accept()
    while True:
        try:
            await websocket.receive_text()
            resp = {
            "message":"message from websocket"
            }
            await websocket.send_json(resp)
        except Exception as e:
            print(e)
            break
    print("CONNECTION DEAD...")
Answered By: Shubham Waje