Broadcasting lets a server send the same message to many clients at once. This helps keep everyone updated together.
Broadcasting to multiple clients in FastAPI
from fastapi import FastAPI, WebSocket from fastapi.websockets import 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)
The ConnectionManager class keeps track of all connected clients.
The broadcast method sends a message to every connected client.
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'Message: {data}') except WebSocketDisconnect: manager.disconnect(websocket)
await manager.broadcast('Hello everyone!')
This FastAPI app creates a WebSocket endpoint at '/ws'. When clients connect, they are added to the manager. When a client sends a message, it is broadcast to all connected clients. If a client disconnects, it is removed.
from fastapi import FastAPI, WebSocket from fastapi.websockets import 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'Message: {data}') except WebSocketDisconnect: manager.disconnect(websocket)
Make sure to handle client disconnects to avoid errors.
Broadcasting works well for chat apps, live updates, and notifications.
Test with multiple clients connected to see messages sent to all.
Broadcasting sends the same message to many clients at once.
Use a connection manager to track and send messages to all clients.
FastAPI WebSockets make it easy to build real-time broadcast features.
Practice
Solution
Step 1: Understand broadcasting concept
Broadcasting means sending one message to many clients simultaneously.Step 2: Compare options with broadcasting definition
Only 'To send the same message to multiple connected clients at once' accurately describes broadcasting.Final Answer:
To send the same message to multiple connected clients at once -> Option AQuick Check:
Broadcasting = send to many clients [OK]
- Confusing broadcasting with single client messaging
- Thinking broadcasting closes connections
- Mixing broadcasting with authentication
Solution
Step 1: Identify correct syntax for sending messages
In FastAPI WebSocket, sending text requires await and send_text method on each client.Step 2: Check each option for correct usage
for client in self.connections: await client.send_text(message) loops through connections and awaits send_text, which is correct. Others miss await or use wrong methods.Final Answer:
for client in self.connections: await client.send_text(message) -> Option DQuick Check:
Use await and send_text per client [OK]
- Forgetting to await send_text
- Trying to send to all clients at once without loop
- Using send instead of send_text
async def broadcast(self, message: str):
for connection in self.active_connections:
await connection.send_text(message)
What happens if self.active_connections is empty when broadcast is called?Solution
Step 1: Understand for-loop behavior on empty list
A for-loop over an empty list runs zero times and does nothing without error.Step 2: Apply to broadcast method
If active_connections is empty, the loop sends no messages but does not raise errors.Final Answer:
No messages are sent and no error occurs -> Option CQuick Check:
Empty list loop = no action, no error [OK]
- Assuming empty list causes errors
- Thinking a default client receives message
- Confusing IndexError with empty iteration
async def broadcast(self, message: str):
for connection in self.active_connections:
connection.send_text(message)
Why does this code cause an error when broadcasting?Solution
Step 1: Identify async method usage
send_text is an async method and must be awaited to run properly.Step 2: Check code for await keyword
The code calls send_text without await, causing coroutine not awaited error.Final Answer:
Missing await before connection.send_text causes coroutine not awaited error -> Option AQuick Check:
Async calls need await [OK]
- Forgetting await on async methods
- Thinking send_text is synchronous
- Misunderstanding active_connections type
Solution
Step 1: Understand client disconnection handling
Disconnected clients cause send_text to raise exceptions when sending messages.Step 2: Use try-except to catch exceptions and remove clients
Wrapping send_text in try-except allows removing disconnected clients from active_connections.Step 3: Evaluate other options
Other approaches are inadequate: tracking client count with a global variable doesn't manage connections, sending without error handling lets exceptions propagate without cleanup, clearing the list discards active connections too.Final Answer:
Wrap send_text in try-except; on exception remove client from active_connections -> Option BQuick Check:
Handle errors to remove disconnected clients [OK]
- Ignoring exceptions during send
- Clearing all clients mistakenly
- Tracking count instead of connections
Ready to prove it?
Pass the test and this pattern moves unknown
