WebSockets are a communication protocol that provides a persistent connection between a client and a server. Unlike HTTP, which is a request - response protocol, WebSockets allow for continuous data transfer in both directions. Once a WebSocket connection is established, the client and server can send messages to each other without the need to establish a new connection for each message.
FastAPI is built on top of Starlette, which has native support for WebSockets. FastAPI offers several advantages for working with WebSockets:
First, make sure you have Python installed on your system. Then, you can install FastAPI and Uvicorn (a server for running FastAPI applications) using pip:
pip install fastapi uvicorn
Here is a simple example of using WebSockets 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 received: {data}")
To run this application, save the code in a file named main.py
and run the following command:
uvicorn main:app --reload
In this example, we define a WebSocket endpoint at /ws
. When a client connects to this endpoint, the server accepts the connection. Then, it enters an infinite loop, waiting for messages from the client. When a message is received, it sends a response back to the client.
Broadcasting messages means sending a message to all connected clients. Here is an example of how to broadcast messages in FastAPI:
from fastapi import FastAPI, WebSocket
from typing import List
app = FastAPI()
active_connections: List[WebSocket] = []
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
active_connections.append(websocket)
try:
while True:
data = await websocket.receive_text()
for connection in active_connections:
await connection.send_text(f"Broadcast: {data}")
except Exception as e:
pass
finally:
active_connections.remove(websocket)
In this example, we maintain a list of active WebSocket connections. When a client sends a message, the server broadcasts the message to all connected clients.
FastAPI can handle multiple clients simultaneously because it uses asynchronous programming. Each WebSocket connection runs in an asynchronous task, allowing the server to handle multiple connections without blocking.
When working with WebSockets, it’s important to handle errors properly. For example, if a client disconnects unexpectedly, the server should handle the disconnection gracefully. In the previous examples, we used a try - except - finally
block to handle potential errors and ensure that the client is removed from the list of active connections when the connection is closed.
Using WebSockets with FastAPI is a powerful way to implement real - time communication in your applications. FastAPI’s simplicity, performance, and support for WebSockets make it an excellent choice for building real - time web applications. By following the common and best practices outlined in this blog post, you can ensure that your WebSocket - based applications are robust and secure.