Full answer
HTTP is request then response. A WebSocket upgrades one HTTP connection into a long-lived, two-way channel, so the server can push messages (live quiz scores, chat, attendance updates) without the client polling.
Basic endpoint:
@app.websocket("/ws/quiz/{room}")
async def quiz(websocket: WebSocket, room: str):
await websocket.accept()
try:
while True:
answer = await websocket.receive_json()
await websocket.send_json({"room": room, "correct": check(answer)})
except WebSocketDisconnect:
cleanup(room)Key points:
accept()completes the handshake. Until then, you can reject withawait websocket.close(code=1008)(policy violation) or raiseWebSocketException.- Receive methods:
receive_text(),receive_bytes(),receive_json(). Send methods mirror them. - When the client leaves,
receive_*()raisesWebSocketDisconnectwith acode(1000 normal, 1001 going away). Theiter_text()/iter_json()async iterators instead end the loop quietly, so put cleanup infinallyto cover both styles. - Path and query parameters,
Header,CookieandDependswork as in HTTP endpoints. HTTPException does not apply; useWebSocketException. - Authentication: browsers cannot set custom headers on WebSocket connections, so tokens usually come through a cookie, a query parameter (beware of logs), or a first "auth" message. Validate before doing anything else.
- Endpoints should be
async def; the connection lives on the event loop. Blocking code there stalls every socket on that worker.
Testing: TestClient(app).websocket_connect("/ws/...") returns a session with send_json / receive_json.
Operations: WebSockets are long-lived, so plan for proxies (enable upgrade headers, raise idle timeouts), heartbeats (ping/pong) to detect dead connections, reconnect logic on the client, and connection limits per worker. Broadcasting across several workers needs a shared channel such as Redis pub/sub.
from typing import Annotated
from fastapi import FastAPI, Query, WebSocket, WebSocketDisconnect, status
from fastapi.testclient import TestClient
app = FastAPI()
ANSWERS = {"q1": "B", "q2": "D"}
events = []
@app.websocket("/ws/quiz/{room}")
async def quiz(websocket: WebSocket, room: str, token: Annotated[str | None, Query()] = None):
if token != "student-token":
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
return
await websocket.accept()
score = 0
try:
while True:
msg = await websocket.receive_json()
correct = ANSWERS.get(msg["question"]) == msg["answer"]
score += correct
await websocket.send_json({"room": room, "question": msg["question"],
"correct": correct, "score": score})
except WebSocketDisconnect as exc:
events.append(f"left room {room} with code {exc.code}")
finally:
events.append(f"final score {score}")
c = TestClient(app)
with c.websocket_connect("/ws/quiz/10A?token=student-token") as ws:
ws.send_json({"question": "q1", "answer": "B"})
print(ws.receive_json())
ws.send_json({"question": "q2", "answer": "A"})
print(ws.receive_json())
try:
with c.websocket_connect("/ws/quiz/10A") as ws:
ws.receive_json()
except WebSocketDisconnect as exc:
print("rejected with code", exc.code)
print(events)
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'room': '10A', 'question': 'q1', 'correct': True, 'score': 1} {'room': '10A', 'question': 'q2', 'correct': False, 'score': 1} rejected with code 1008 ['left room 10A with code 1000', 'final score 1']
Key points
- @app.websocket endpoint with accept, receive, send loop
- WebSocketDisconnect signals the client left
- Reject before accept with close code 1008 or WebSocketException
- Browsers cannot set headers; plan token delivery
- Use async def; test with websocket_connect
Common mistakes
- Not catching WebSocketDisconnect, so cleanup never runs
- Doing work before checking authentication
- Calling blocking code inside the WebSocket loop
- Keeping connection lists in process memory and expecting broadcasts to reach clients on other workers
- Forgetting proxy upgrade headers and idle timeouts
Follow-ups
- How would you broadcast a message to everyone in a room across four workers?
- How do you authenticate a browser WebSocket connection?
- When would Server-Sent Events be a better choice?
Tips
- Show the accept, loop, disconnect structure
- Address authentication explicitly
- Mention scaling with Redis pub/sub and proxy settings