Skip to main content
WebSockets provide full-duplex communication channels over a single TCP connection, enabling real-time bidirectional data exchange between clients and servers.

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

Accepts the WebSocket connection. This must be called before any other WebSocket operations.

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:
Use WebSocketException instead of HTTPException to raise errors in WebSocket dependencies. This allows you to specify WebSocket-specific close codes.

Handling Disconnections

Handle client disconnections gracefully using WebSocketDisconnect:

Connection Manager Pattern

Manage multiple WebSocket connections with a connection manager class:
The connection manager pattern is ideal for building chat applications, collaborative tools, or any scenario requiring broadcasting messages to multiple clients.

WebSocket States

Check the connection state using websocket.client_state or websocket.application_state:
Available states:
  • WebSocketState.CONNECTING
  • WebSocketState.CONNECTED
  • WebSocketState.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:
Common close codes:
  • WS_1000_NORMAL_CLOSURE - Normal closure
  • WS_1001_GOING_AWAY - Server going away
  • WS_1002_PROTOCOL_ERROR - Protocol error
  • WS_1003_UNSUPPORTED_DATA - Unsupported data
  • WS_1008_POLICY_VIOLATION - Policy violation
  • WS_1011_INTERNAL_ERROR - Internal server error