Skip to main content
The WebSocket class provides an interface for handling WebSocket connections in FastAPI. It allows bidirectional, real-time communication between the client and server. FastAPI uses Starlette’s WebSocket class.

Importing

Basic Usage

Class Reference

WebSocket

The WebSocket class provides methods for accepting connections, sending and receiving data, and closing connections.

Methods

async accept(subprotocol=None, headers=None)

Accept the WebSocket connection.
str | None
default:"None"
WebSocket subprotocol to use.
Iterable[tuple[bytes, bytes]] | None
default:"None"
Additional headers to send in the accept response.
Note: You must call accept() before sending or receiving any messages.

async receive_text()

Receive a text message from the client.
Returns: str - The received text messageRaises: WebSocketDisconnect - If the client disconnects

async receive_bytes()

Receive binary data from the client.
Returns: bytes - The received binary dataRaises: WebSocketDisconnect - If the client disconnects

async receive_json(mode='text')

Receive and parse JSON data from the client.
str
default:"'text'"
Either “text” or “binary” to specify how to receive the data.
Returns: Any - The parsed JSON dataRaises: WebSocketDisconnect - If the client disconnects

async send_text(data)

Send a text message to the client.
str
required
The text message to send.

async send_bytes(data)

Send binary data to the client.
bytes
required
The binary data to send.

async send_json(data, mode='text')

Serialize and send JSON data to the client.
Any
required
The data to serialize and send as JSON.
str
default:"'text'"
Either “text” or “binary” to specify how to send the data.

async close(code=1000, reason=None)

Close the WebSocket connection.
int
default:"1000"
WebSocket close code (1000 = normal closure).
str | None
default:"None"
Optional reason for closing the connection.
Common close codes:
  • 1000 - Normal closure
  • 1001 - Going away
  • 1002 - Protocol error
  • 1003 - Unsupported data
  • 1011 - Internal server error

Attributes

Address | None
Client address information (host and port).
URL
The WebSocket URL.
Headers
Request headers from the WebSocket handshake.
QueryParams
Query parameters from the WebSocket URL.
dict[str, Any]
Path parameters from the WebSocket URL.
dict[str, str]
Cookies from the WebSocket handshake request.
State
State object for storing data during the WebSocket connection lifecycle.
WebSocketState
Current state of the WebSocket connection.States:
  • WebSocketState.CONNECTING - Connection is being established
  • WebSocketState.CONNECTED - Connection is established
  • WebSocketState.DISCONNECTED - Connection is closed

WebSocketDisconnect Exception

Raised when the client disconnects or the connection is lost.
Attributes:
int
WebSocket close code.
str | None
Reason for disconnection.

Common Patterns

Echo Server

Broadcasting to Multiple Clients

JSON Message Handling

Authentication

Path and Query Parameters

Dependencies with WebSockets

Client Example (JavaScript)