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.
Previous
What is rate limiting and how do you implement it in FastAPI?
Next
What is the difference between Flask-RESTful and Flask-RESTX?
More FastAPI / Flask Questions
View all →- Intermediate How do you implement JWT authentication in FastAPI?
- Intermediate How does SQLAlchemy async work with FastAPI?
- Intermediate What is Flask's application factory pattern?
- Intermediate How do you implement background tasks in FastAPI?
- Intermediate What is Pydantic v2 and what changed from v1?