How to Broadcast Messages Using WebSocket in FastAPI
To broadcast messages using
WebSocket in FastAPI, maintain a list of active connections and send the message to each connected client. Use a connection manager class to track and broadcast messages efficiently.Syntax
Broadcasting in FastAPI WebSocket involves managing multiple client connections and sending messages to all of them. The key parts are:
- Connection Manager: A class to store active WebSocket connections.
- connect: Method to accept and add new clients.
- disconnect: Method to remove clients when they leave.
- broadcast: Method to send a message to all connected clients.
python
class ConnectionManager: def __init__(self): self.active_connections: list[WebSocket] = [] async def connect(self, websocket: WebSocket): await websocket.accept() self.active_connections.append(websocket) def disconnect(self, websocket: WebSocket): self.active_connections.remove(websocket) async def broadcast(self, message: str): for connection in self.active_connections: await connection.send_text(message)
Example
This example shows a FastAPI app that accepts WebSocket connections and broadcasts any received message to all connected clients.
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI() class ConnectionManager: def __init__(self): self.active_connections: list[WebSocket] = [] async def connect(self, websocket: WebSocket): await websocket.accept() self.active_connections.append(websocket) def disconnect(self, websocket: WebSocket): self.active_connections.remove(websocket) async def broadcast(self, message: str): for connection in self.active_connections: await connection.send_text(message) manager = ConnectionManager() @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await manager.connect(websocket) try: while True: data = await websocket.receive_text() await manager.broadcast(f"Broadcast: {data}") except WebSocketDisconnect: manager.disconnect(websocket)
Output
When clients connect to ws://<server>/ws and send messages, all connected clients receive the broadcasted messages prefixed with 'Broadcast: '.
Common Pitfalls
Common mistakes when broadcasting with FastAPI WebSocket include:
- Not accepting the WebSocket connection before sending or receiving messages, causing errors.
- Failing to remove disconnected clients, which leads to exceptions when broadcasting.
- Blocking the event loop by using synchronous code inside async functions.
- Not handling
WebSocketDisconnectexceptions properly, causing server crashes.
python
from fastapi import WebSocket # Wrong: Not accepting connection async def wrong_connect(websocket: WebSocket): # Missing await websocket.accept() pass # Right: Accept connection async def right_connect(websocket: WebSocket): await websocket.accept()
Quick Reference
- Use a connection manager to track active WebSocket clients.
- Call
await websocket.accept()before communication. - Handle disconnects to keep the connection list clean.
- Broadcast by looping over all active connections and sending messages.
Key Takeaways
Maintain a list of active WebSocket connections to broadcast messages.
Always accept WebSocket connections before sending or receiving data.
Handle client disconnects to avoid errors during broadcasting.
Use async methods to keep the server responsive during broadcasts.