Push live updates to the browser. Learn why WebSockets exist, add a WebSocket endpoint to FastAPI, broadcast to every connected client, and connect from the browser.
Why: a normal HTTP request is one-way and one-shot — the browser asks, the server answers, the connection closes. That is fine for loading a page, but useless when the server needs to tell the browser something new (a chat message, a live price, a notification). A WebSocket is a single connection that stays open so both sides can send messages at any time. Note: the URL starts with ws:// (or wss:// when secured with TLS) instead of http://.
Why: FastAPI has built-in WebSocket support — you mark a function with @app.websocket instead of @app.get. You accept() the connection to open it, then loop: receive a message, send one back. The loop runs until the client disconnects, which raises WebSocketDisconnect. Note: the standard install ("fastapi[standard]") already includes the websockets package this needs.
# main.py
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
app = FastAPI()
@app.websocket('/ws')
async def echo(websocket: WebSocket):
await websocket.accept() # open the connection
try:
while True:
text = await websocket.receive_text()
await websocket.send_text(f'you said: {text}')
except WebSocketDisconnect:
print('a client left')Why: the real power of WebSockets is pushing one message to everyone at once — that is what makes a chat or a live feed. Keep a list of the connections you have accepted, then loop over it to send to each one. A small manager class keeps that bookkeeping in one place.
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
class ConnectionManager:
def __init__(self):
self.active: list[WebSocket] = []
async def connect(self, ws: WebSocket):
await ws.accept()
self.active.append(ws)
def disconnect(self, ws: WebSocket):
self.active.remove(ws)
async def broadcast(self, message: str):
for ws in self.active:
await ws.send_text(message)
app = FastAPI()
manager = ConnectionManager()
@app.websocket('/ws')
async def chat(websocket: WebSocket):
await manager.connect(websocket)
try:
while True:
text = await websocket.receive_text()
await manager.broadcast(text) # send to everyone
except WebSocketDisconnect:
manager.disconnect(websocket)Why: browsers have a built-in WebSocket object — no library needed. You open a connection, listen for messages with onmessage, and call send() to talk back. This is the other half of the chat. Note: this snippet is JavaScript that runs in the browser, not Python.
// runs in the browser (JavaScript)
const socket = new WebSocket('ws://localhost:8000/ws')
socket.onopen = () => socket.send('Hello from the browser!')
socket.onmessage = (event) => {
console.log('server says:', event.data)
}