- Spec files
pypi-fastapi
Describes: pkg:pypi/fastapi@0.116.x
- Description
- FastAPI framework, high performance, easy to learn, fast to code, ready for production
- Author
- tessl
- Last updated
websocket-support.md docs/
1# WebSocket Support23FastAPI provides comprehensive WebSocket support for real-time bidirectional communication between clients and servers. This enables applications to push data to clients instantly and receive real-time updates from clients.45## Capabilities67### WebSocket Connection Class89The WebSocket class handles real-time bidirectional communication with clients, providing methods for sending and receiving data in various formats.1011```python { .api }12class WebSocket:13def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:14"""15Initialize WebSocket connection.1617Parameters:18- scope: ASGI scope dictionary19- receive: ASGI receive callable20- send: ASGI send callable21"""2223async def accept(24self,25subprotocol: str = None,26headers: List[Tuple[bytes, bytes]] = None27) -> None:28"""29Accept the WebSocket connection.3031Parameters:32- subprotocol: WebSocket subprotocol to use33- headers: Additional headers to send34"""3536async def receive_text(self) -> str:37"""38Receive text data from the WebSocket.3940Returns:41String containing the received text message42"""4344async def receive_bytes(self) -> bytes:45"""46Receive binary data from the WebSocket.4748Returns:49Bytes containing the received binary message50"""5152async def receive_json(self, mode: str = "text") -> Any:53"""54Receive JSON data from the WebSocket.5556Parameters:57- mode: Receive mode ("text" or "binary")5859Returns:60Parsed JSON data as Python object61"""6263async def send_text(self, data: str) -> None:64"""65Send text data to the WebSocket.6667Parameters:68- data: Text message to send69"""7071async def send_bytes(self, data: bytes) -> None:72"""73Send binary data to the WebSocket.7475Parameters:76- data: Binary message to send77"""7879async def send_json(self, data: Any, mode: str = "text") -> None:80"""81Send JSON data to the WebSocket.8283Parameters:84- data: Python object to serialize and send as JSON85- mode: Send mode ("text" or "binary")86"""8788async def close(self, code: int = 1000, reason: str = None) -> None:89"""90Close the WebSocket connection.9192Parameters:93- code: WebSocket close code94- reason: Close reason string95"""9697@property98def client(self) -> Address:99"""Client address information."""100101@property102def url(self) -> URL:103"""WebSocket URL information."""104105@property106def headers(self) -> Headers:107"""WebSocket headers."""108109@property110def query_params(self) -> QueryParams:111"""WebSocket query parameters."""112113@property114def path_params(self) -> dict:115"""WebSocket path parameters."""116117@property118def cookies(self) -> dict:119"""WebSocket cookies."""120121@property122def state(self) -> State:123"""WebSocket connection state."""124```125126### WebSocket State Enumeration127128Enumeration defining the possible states of a WebSocket connection.129130```python { .api }131class WebSocketState(enum.Enum):132"""WebSocket connection state constants."""133134CONNECTING = 0135CONNECTED = 1136DISCONNECTED = 3137```138139### WebSocket Disconnect Exception140141Exception raised when a WebSocket connection is unexpectedly disconnected.142143```python { .api }144class WebSocketDisconnect(Exception):145def __init__(self, code: int = 1000, reason: str = None) -> None:146"""147WebSocket disconnect exception.148149Parameters:150- code: WebSocket close code151- reason: Disconnect reason152"""153self.code = code154self.reason = reason155```156157### WebSocket Route Decorator158159Decorator method on FastAPI and APIRouter instances for defining WebSocket endpoints.160161```python { .api }162def websocket(163self,164path: str,165*,166name: str = None,167dependencies: List[Depends] = None,168) -> Callable[[DecoratedCallable], DecoratedCallable]:169"""170Decorator for WebSocket endpoints.171172Parameters:173- path: WebSocket URL path174- name: Endpoint name for URL generation175- dependencies: List of dependencies for this WebSocket176"""177```178179### WebSocket Route Class180181Class representing individual WebSocket routes in the application.182183```python { .api }184class APIWebSocketRoute:185def __init__(186self,187path: str,188endpoint: Callable,189*,190name: str = None,191dependencies: List[Depends] = None,192) -> None:193"""194WebSocket route representation.195196Parameters:197- path: WebSocket URL path198- endpoint: WebSocket handler function199- name: Route name for URL generation200- dependencies: List of dependencies for the WebSocket201"""202203def matches(self, scope: Scope) -> Tuple[Match, Scope]:204"""Check if route matches the given scope."""205206def url_path_for(self, name: str, **path_params: Any) -> URLPath:207"""Generate URL path for the named route."""208```209210## Usage Examples211212### Basic WebSocket Endpoint213214```python215from fastapi import FastAPI, WebSocket216217app = FastAPI()218219@app.websocket("/ws")220async def websocket_endpoint(websocket: WebSocket):221await websocket.accept()222try:223while True:224data = await websocket.receive_text()225await websocket.send_text(f"Message text was: {data}")226except WebSocketDisconnect:227print("Client disconnected")228```229230### WebSocket with Path Parameters231232```python233from fastapi import FastAPI, WebSocket234235app = FastAPI()236237@app.websocket("/ws/{client_id}")238async def websocket_endpoint(websocket: WebSocket, client_id: int):239await websocket.accept()240try:241while True:242data = await websocket.receive_text()243await websocket.send_text(f"Client {client_id}: {data}")244except WebSocketDisconnect:245print(f"Client {client_id} disconnected")246```247248### WebSocket with Dependencies249250```python251from fastapi import FastAPI, WebSocket, Depends, HTTPException252from fastapi.security import HTTPBearer253254app = FastAPI()255security = HTTPBearer()256257def verify_websocket_token(token: str = Depends(security)):258if token.credentials != "valid-token":259raise HTTPException(status_code=401, detail="Invalid token")260return token.credentials261262@app.websocket("/ws")263async def websocket_endpoint(264websocket: WebSocket,265token: str = Depends(verify_websocket_token)266):267await websocket.accept()268await websocket.send_text(f"Authenticated with token: {token}")269try:270while True:271data = await websocket.receive_text()272await websocket.send_text(f"Echo: {data}")273except WebSocketDisconnect:274print("Authenticated client disconnected")275```276277### WebSocket JSON Communication278279```python280from fastapi import FastAPI, WebSocket, WebSocketDisconnect281from typing import Dict, Any282283app = FastAPI()284285@app.websocket("/ws/json")286async def websocket_json_endpoint(websocket: WebSocket):287await websocket.accept()288try:289while True:290# Receive JSON data291data: Dict[str, Any] = await websocket.receive_json()292293# Process the data294response = {295"type": "response",296"original_message": data,297"timestamp": "2023-01-01T00:00:00Z"298}299300# Send JSON response301await websocket.send_json(response)302except WebSocketDisconnect:303print("JSON WebSocket client disconnected")304```305306### WebSocket Connection Manager307308```python309from fastapi import FastAPI, WebSocket, WebSocketDisconnect310from typing import List311312class ConnectionManager:313def __init__(self):314self.active_connections: List[WebSocket] = []315316async def connect(self, websocket: WebSocket):317await websocket.accept()318self.active_connections.append(websocket)319320def disconnect(self, websocket: WebSocket):321self.active_connections.remove(websocket)322323async def send_personal_message(self, message: str, websocket: WebSocket):324await websocket.send_text(message)325326async def broadcast(self, message: str):327for connection in self.active_connections:328await connection.send_text(message)329330app = FastAPI()331manager = ConnectionManager()332333@app.websocket("/ws/{client_id}")334async def websocket_endpoint(websocket: WebSocket, client_id: int):335await manager.connect(websocket)336try:337while True:338data = await websocket.receive_text()339await manager.send_personal_message(f"You wrote: {data}", websocket)340await manager.broadcast(f"Client #{client_id} says: {data}")341except WebSocketDisconnect:342manager.disconnect(websocket)343await manager.broadcast(f"Client #{client_id} left the chat")344```345346### WebSocket with Query Parameters347348```python349from fastapi import FastAPI, WebSocket, Query350351app = FastAPI()352353@app.websocket("/ws")354async def websocket_endpoint(355websocket: WebSocket,356room: str = Query(..., description="Chat room name"),357user_id: int = Query(..., description="User ID")358):359await websocket.accept()360await websocket.send_text(f"Welcome to room {room}, user {user_id}!")361362try:363while True:364message = await websocket.receive_text()365await websocket.send_text(f"[{room}] User {user_id}: {message}")366except WebSocketDisconnect:367print(f"User {user_id} left room {room}")368```369370### WebSocket Error Handling371372```python373from fastapi import FastAPI, WebSocket, WebSocketDisconnect374import json375376app = FastAPI()377378@app.websocket("/ws/safe")379async def safe_websocket_endpoint(websocket: WebSocket):380await websocket.accept()381382try:383while True:384try:385# Receive and validate JSON386data = await websocket.receive_text()387parsed_data = json.loads(data)388389if "action" not in parsed_data:390await websocket.send_json({391"error": "Missing 'action' field"392})393continue394395# Process valid messages396response = {397"success": True,398"action": parsed_data["action"],399"data": parsed_data.get("data")400}401await websocket.send_json(response)402403except json.JSONDecodeError:404await websocket.send_json({405"error": "Invalid JSON format"406})407except Exception as e:408await websocket.send_json({409"error": f"Processing error: {str(e)}"410})411412except WebSocketDisconnect:413print("Client disconnected from safe WebSocket")414```415416### WebSocket with Custom Close Handling417418```python419from fastapi import FastAPI, WebSocket, WebSocketDisconnect420421app = FastAPI()422423@app.websocket("/ws/custom-close")424async def websocket_with_custom_close(websocket: WebSocket):425await websocket.accept()426427try:428while True:429data = await websocket.receive_text()430431if data == "close":432await websocket.close(code=1000, reason="Client requested close")433break434elif data == "error":435await websocket.close(code=1011, reason="Server error occurred")436break437else:438await websocket.send_text(f"Received: {data}")439440except WebSocketDisconnect as disconnect:441print(f"WebSocket disconnected with code: {disconnect.code}, reason: {disconnect.reason}")442```