18 Websocket Fastapi
DodaTech
1 min read
title: WebSocket Support in FastAPI REST APIs weight: 28 date: 2026-06-28 lastmod: 2026-06-28 description: Implement WebSocket connections in FastAPI for real-time bidirectional communication including chat, notifications, and live data streaming with connection management. tags: [api-development, fastapi]
FastAPI WebSocket support enables real-time bidirectional communication using the WebSocket protocol, with automatic upgrade handling, message broadcasting, connection lifecycle management, and integration with existing authentication.
```python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from typing import Set
app = FastAPI()
class ConnectionManager:
def __init__(self):
self.active_connections: Set[WebSocket] = set()
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.add(websocket)
def disconnect(self, websocket: WebSocket):
self.active_connections.discard(websocket)
async def broadcast(self, message: str):
for connection in self.active_connections:
try:
await connection.send_text(message)
except WebSocketDisconnect:
self.disconnect(connection)
manager = ConnectionManager()
@app.websocket("/ws/chat")
async def websocket_endpoint(websocket: WebSocket):
await manager.connect(websocket)
try:
while True:
data = await websocket.receive_text()
await manager.broadcast(f"User: {data}")
except WebSocketDisconnect:
manager.disconnect(websocket)
await manager.broadcast("A user disconnected")
What's Next
Now learn about background tasks in Building REST APIs with FastAPI.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro