FastAPI supports WebSockets for real-time, bidirectional communication (chat, live updates, notifications) via the @app.websocket decorator. Unlike HTTP's request-response, a WebSocket connection stays open, letting the server and client send messages freely.
A basic WebSocket endpoint
fastapi WebSocket, WebSocketDisconnect
():
websocket.accept()
:
:
data = websocket.receive_text()
websocket.send_text()
WebSocketDisconnect:
()
