In this tutorial we are going to implement our first WebSocket route. If you have not build a websocket route before, don't worry, It will be as simple as building an API route with FastAPI. Just read the below code and you should understand most pieces already.
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket("/ws")
async def health_check(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_json({"msg":data})
/ws
that opens the gateway to our WebSocket adventure./ws
endpoint. Once the connection is established, the server responds by accepting the connection through await websocket.accept(). With this, our WebSocket is ready to send and receive messages between the client and server.data = await websocket.receive_text()
and prepares the response with an enchanting touch. With this, the WebSocket reveals the server's reply, gracefully weaving it back to the client.This is it, let's see this in action.
Brige the gap between Tutorial hell and Industry. We want to bring in the culture of Clean Code, Test Driven Development.
We know, we might make it hard for you but definitely worth the efforts.
© Copyright 2022-23 Team FastAPITutorial