
FastAPI
Learn essential concepts of websockets in FastAPI.
This section covers WebSocket fundamentals, including:
WebSockets enable persistent, bidirectional communication between client and server. Unlike HTTP's request-response model, WebSockets maintain open connections for real-time data exchange.
Understanding WebSockets helps you:
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
try:
while True:
# Receive message from client
data = await websocket.receive_text()
# Send response back
await websocket.send_text(f"Echo: {data}")
except Exception:
await websocket.close()from fastapi import WebSocket
# Store active connections
active_connections = []
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):
# Send message to all connected clients
for connection in self.active_connections:
await connection.send_text(message)
manager = ConnectionManager()
@app.websocket("/ws/chat/{user_id}")
async def websocket_chat(websocket: WebSocket, user_id: int):
await manager.connect(websocket)
try:
while True:
data = await websocket.receive_text()
await manager.broadcast(f"User {user_id}: {data}")
except Exception:
manager.disconnect(websocket)@app.websocket("/ws/notifications/{client_id}")
async def websocket_notifications(websocket: WebSocket, client_id: str):
await websocket.accept()
try:
while True:
# Receive acknowledgment or keep connection alive
await websocket.receive_text()
except Exception:
await websocket.close()
@app.post("/notify/{client_id}")
async def send_notification(client_id: str, message: str):
# Send notification to specific client
# (requires connection tracking in production)
return {"status": "notification_sent", "client": client_id}WebSockets enable:
Next step: Explore the advanced section for production patterns and optimization techniques.
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward