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
TheWebSocket class provides methods for accepting connections, sending and receiving data, and closing connections.
Methods
accept()
accept()
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.
accept() before sending or receiving any messages.receive_text()
receive_text()
async receive_text()
Receive a text message from the client.str - The received text messageRaises: WebSocketDisconnect - If the client disconnectsreceive_bytes()
receive_bytes()
async receive_bytes()
Receive binary data from the client.bytes - The received binary dataRaises: WebSocketDisconnect - If the client disconnectsreceive_json()
receive_json()
send_text()
send_text()
send_bytes()
send_bytes()
send_json()
send_json()
close()
close()
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.
1000- Normal closure1001- Going away1002- Protocol error1003- Unsupported data1011- 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 establishedWebSocketState.CONNECTED- Connection is establishedWebSocketState.DISCONNECTED- Connection is closed
WebSocketDisconnect Exception
Raised when the client disconnects or the connection is lost.int
WebSocket close code.
str | None
Reason for disconnection.