Overview
FastrAPI provides built-in support for WebSocket connections, allowing real-time bidirectional communication between clients and servers. The WebSocket API is designed to be simple and intuitive, with support for text, binary, and JSON messages.Decorator
@app.websocket()
Defines a WebSocket endpoint at the specified path.The URL path for the WebSocket endpoint (e.g., “/ws”)
WebSocket class
The WebSocket object is passed to your handler function and provides methods for managing the connection.accept()
Accepts the WebSocket connection. Must be called before sending or receiving messages.Returns nothing. The connection is established.
send_text()
Sends a text message to the client.The text message to send
Returns an awaitable that completes when the message is sent
send_bytes()
Sends binary data to the client.The binary data to send
Returns an awaitable that completes when the data is sent
send_json()
Serializes a Python object to JSON and sends it as a text message.Any JSON-serializable Python object (dict, list, etc.)
Returns an awaitable that completes when the message is sent
receive_text()
Receives a text message from the client.The text message received from the client
ConnectionError: If the WebSocket is closedTypeError: If the received message is binary instead of text
receive_bytes()
Receives binary data from the client.The binary data received from the client
ConnectionError: If the WebSocket is closedTypeError: If the received message is text instead of binary
receive_json()
Receives a text message and parses it as JSON.The parsed JSON object (dict, list, etc.)
ConnectionError: If the WebSocket is closedTypeError: If the received message is binary instead of textValueError: If the message is not valid JSON
close()
Closes the WebSocket connection.WebSocket close code (optional)
Returns an awaitable that completes when the connection is closed
Properties
client_state
Returns the current state of the WebSocket connection.Connection state: 1 (connected) or 3 (disconnected)