0
0
FastAPIframework~5 mins

Why WebSockets enable real-time communication in FastAPI

Choose your learning style9 modes available
Introduction

WebSockets let your app talk back and forth instantly without waiting. This makes real-time updates possible, like chat or live scores.

Building a chat app where messages appear instantly
Showing live sports scores or stock prices that update continuously
Creating multiplayer games where players see each other's moves right away
Implementing notifications that pop up immediately when something happens
Streaming live data like GPS locations or sensor readings
Syntax
FastAPI
from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Message text was: {data}")

Use @app.websocket to create a WebSocket route.

Call await websocket.accept() to start the connection.

Examples
Accepts the WebSocket connection from the client.
FastAPI
await websocket.accept()
Waits to receive a text message from the client.
FastAPI
data = await websocket.receive_text()
Sends a text message back to the client.
FastAPI
await websocket.send_text(f"Echo: {data}")
Sample Program

This FastAPI app opens a WebSocket at /ws. When a client connects and sends a message, the server replies immediately with the same message prefixed by 'You said:'. This shows real-time two-way communication.

FastAPI
from fastapi import FastAPI, WebSocket
import uvicorn

app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"You said: {data}")

if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000)
OutputSuccess
Important Notes

WebSockets keep the connection open, unlike normal HTTP requests that close after response.

This makes WebSockets perfect for live updates without repeated requests.

Remember to handle connection closing and errors in real apps.

Summary

WebSockets allow instant two-way communication between client and server.

FastAPI supports WebSockets with simple async functions and decorators.

This enables real-time features like chat, live data, and notifications.