Hello WebSocket

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})
  • We've created a new endpoint /ws that opens the gateway to our WebSocket adventure.
  • The WebSocket adventure starts with the client attempting to establish a connection by requesting the /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.
  • The true essence of WebSockets lies in their persistent connection, enabling a continuous flow of data. As the adventurous "while True" loop commences, our WebSocket waits patiently for incoming messages from the client using await websocket.receive_text(). It's a captivating moment as the server listens to the client's every word, eager to respond with real-time updates.
  • As the client sends a message, the server swiftly catches it with 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.

FastAPITutorial

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.

Contacts

Refunds:

Refund Policy
Social

Follow us on our social media channels to stay updated.

© Copyright 2022-23 Team FastAPITutorial