What are FastAPI WebSockets?

Answer

FastAPI supports WebSockets for persistent bidirectional connections. Define a WebSocket endpoint: @app.websocket('/ws') async def websocket_endpoint(websocket: WebSocket): await websocket.accept(); while True: data = await websocket.receive_text(); await websocket.send_text(f'Echo: {data}'). Handle disconnects: catch WebSocketDisconnect. For broadcasting to multiple connected clients, maintain a list of active connections and iterate to send. WebSocket dependencies work the same as HTTP dependencies — inject authentication, database sessions, etc. in the function signature with Depends(). FastAPI's WebSocket support is built on Starlette's, which uses websockets or wsproto under the hood. Use cases: real-time dashboards, collaborative editing, live chat, and streaming ML inference results.