Basic WebSocket Endpoint
Create a WebSocket endpoint using the@app.websocket() decorator:
You must call
await websocket.accept() before you can send or receive messages.WebSocket Methods
Accepting Connections
Receiving Data
FastAPI provides several methods to receive data:Sending Data
Send data to the connected client:Path Parameters and Query Parameters
WebSocket endpoints support path and query parameters just like regular HTTP endpoints:Dependencies
Use FastAPI’s dependency injection system with WebSocket endpoints:Handling Disconnections
Handle client disconnections gracefully usingWebSocketDisconnect:
Connection Manager Pattern
Manage multiple WebSocket connections with a connection manager class:WebSocket States
Check the connection state usingwebsocket.client_state or websocket.application_state:
WebSocketState.CONNECTINGWebSocketState.CONNECTEDWebSocketState.DISCONNECTED
Client-Side JavaScript
Connect to your WebSocket endpoint from the browser:Testing WebSockets
Test WebSocket endpoints using FastAPI’s test client:FastAPI’s WebSocket support is built on top of Starlette’s WebSocket implementation, providing a robust and well-tested foundation.
WebSocket Close Codes
Use standard WebSocket close codes when raising exceptions:WS_1000_NORMAL_CLOSURE- Normal closureWS_1001_GOING_AWAY- Server going awayWS_1002_PROTOCOL_ERROR- Protocol errorWS_1003_UNSUPPORTED_DATA- Unsupported dataWS_1008_POLICY_VIOLATION- Policy violationWS_1011_INTERNAL_ERROR- Internal server error