WebSockets let your app talk back and forth instantly without waiting. This makes real-time updates possible, like chat or live scores.
Why WebSockets enable real-time communication in 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.
await websocket.accept()data = await websocket.receive_text()await websocket.send_text(f"Echo: {data}")
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.
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)
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.
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.