WebSockets in FastAPI
Key Concepts
WebSockets are a communication protocol that provides full-duplex communication channels over a single TCP connection. In FastAPI, WebSockets allow for real-time, bidirectional communication between the client and server. Here are the key concepts:
- WebSocket Connection: A persistent connection between the client and server that allows for continuous data exchange.
- WebSocket Handshake: The initial process where the client and server agree to upgrade from an HTTP connection to a WebSocket connection.
- WebSocket Messages: Data packets sent and received over a WebSocket connection.
- WebSocket Events: Specific actions or events that occur during the WebSocket connection lifecycle, such as connection open, message received, and connection close.
Explaining Each Concept
1. WebSocket Connection
A WebSocket connection is established once the WebSocket handshake is successfully completed. This connection remains open, allowing both the client and server to send messages to each other at any time. This is in contrast to HTTP, where the connection is closed after each request and response.
2. WebSocket Handshake
The WebSocket handshake is initiated by the client sending an HTTP request with an "Upgrade" header to the server. If the server supports WebSockets, it responds with an HTTP 101 status code, confirming the upgrade to a WebSocket connection. This process is handled automatically by FastAPI.
3. WebSocket Messages
Once a WebSocket connection is established, both the client and server can send messages to each other. These messages can be text, binary, or control frames. In FastAPI, you can handle incoming messages and send responses using WebSocket events.
4. WebSocket Events
WebSocket events are specific actions that occur during the WebSocket connection lifecycle. Common events include:
- on_connect: Triggered when a WebSocket connection is successfully established.
- on_receive: Triggered when a message is received from the client.
- on_disconnect: Triggered when the WebSocket connection is closed.
Examples
Example 1: Basic WebSocket Connection
Here is a simple example of setting up a WebSocket connection in FastAPI:
from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}")
Example 2: Handling WebSocket Events
In this example, we handle the WebSocket connection events:
from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() try: while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") except WebSocketDisconnect: await websocket.close()
Analogies
Think of a WebSocket connection as a telephone call. Once the call is connected (WebSocket handshake), both parties can talk (send messages) and listen (receive messages) at the same time. The call remains open until one party hangs up (connection close).
Another analogy is a chat room. Once you join the chat room (WebSocket connection), you can send messages (WebSocket messages) and receive messages from others in real-time. The chat room remains open until you leave (connection close).