Async Streaming & WebSockets
Stream data to clients with FastAPI StreamingResponse, Server-Sent Events, WebSocket connections, and async queue-based broadcasting.
Part 1: What You Will Learn
- Understand the difference between normal HTTP responses and long-lived real-time connections.
- Create a FastAPI WebSocket endpoint.
- Accept messages from one client and broadcast them to all connected clients.
- Handle disconnects without crashing the server.
Part 2: WebSocket Chat Server
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
app = FastAPI()
class ConnectionManager:
def __init__(self) -> None:
self.connections: list[WebSocket] = []
async def connect(self, websocket: WebSocket) -> None:
await websocket.accept()
self.connections.append(websocket)
def disconnect(self, websocket: WebSocket) -> None:
if websocket in self.connections:
self.connections.remove(websocket)
async def broadcast(self, message: str) -> None:
for connection in self.connections.copy():
try:
await connection.send_text(message)
except Exception:
self.disconnect(connection)
manager = ConnectionManager()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket) -> None:
await manager.connect(websocket)
try:
while True:
message = await websocket.receive_text()
await manager.broadcast(f"Client says: {message}")
except WebSocketDisconnect:
manager.disconnect(websocket)pip install fastapi "uvicorn[standard]" uvicorn app:app --reload
Part 3: Simple Browser Client
<!DOCTYPE html>
<html>
<body>
<input id="message" placeholder="Type a message">
<button onclick="sendMessage()">Send</button>
<ul id="messages"></ul>
<script>
const socket = new WebSocket("ws://127.0.0.1:8000/ws");
socket.onmessage = (event) => {
const item = document.createElement("li");
item.textContent = event.data;
document.querySelector("#messages").appendChild(item);
};
function sendMessage() {
const box = document.querySelector("#message");
socket.send(box.value);
box.value = "";
}
</script>
</body>
</html>Part 4: Streaming Choices
Use WebSockets when both client and server need to send messages repeatedly. Server-Sent Events (SSE) are often simpler when only the server must continuously push updates to the browser. StreamingResponse is useful when an HTTP response should be delivered in chunks, such as generated text or a large file.
Part 5: Hands-On Practice
Mini project โ Live Classroom Notice Board. Allow several browser windows to connect to the same FastAPI application. Add a sender name, timestamp each message, and broadcast classroom announcements to every connected client.
Part 6: Next Steps
Test the application with several browser windows, then continue to Lesson 38 to organise larger systems as microservices.