The WebSocket protocol enables bidirectional communication between a client (usually a web browser) and a server. Unlike the traditional HTTP protocol, which follows a request - response model, WebSocket allows the server to send data to the client without the client explicitly requesting it.
FastAPI provides built - in support for WebSocket. It uses the WebSocket
class from the fastapi
library to handle WebSocket connections. When a WebSocket connection is established, the server and the client can exchange messages at any time.
Here is a simple example of setting up a WebSocket server using 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}")
In this code:
FastAPI
and WebSocket
) from the fastapi
library.FastAPI
application instance.@app.websocket
decorator. The endpoint is accessible at the path /ws
.await websocket.accept()
.await websocket.receive_text()
and send a response back to the client using await websocket.send_text()
.To run the FastAPI application, you can use Uvicorn. Save the above code in a file named main.py
and run the following command in your terminal:
uvicorn main:app --reload
You can use a WebSocket testing tool like wscat
or a browser console to test the WebSocket connection. For example, using wscat
:
wscat -c ws://localhost:8000/ws
Once connected, you can send a message, and you should receive a response from the server.
FastAPI allows you to handle different types of messages such as text, binary, and JSON. Here is an example of handling JSON messages:
from fastapi import FastAPI, WebSocket
import json
app = FastAPI()
@app.websocket("/ws_json")
async def websocket_json_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
try:
data = await websocket.receive_json()
response = {"message": "Received JSON data", "data": data}
await websocket.send_json(response)
except Exception as e:
await websocket.close()
break
In a real - time application, you may want to broadcast messages to multiple clients. Here is an example of how to do it:
from fastapi import FastAPI, WebSocket
from typing import List
app = FastAPI()
connected_clients: List[WebSocket] = []
@app.websocket("/ws_broadcast")
async def websocket_broadcast_endpoint(websocket: WebSocket):
await websocket.accept()
connected_clients.append(websocket)
try:
while True:
data = await websocket.receive_text()
for client in connected_clients:
if client != websocket:
await client.send_text(f"New message: {data}")
except Exception as e:
connected_clients.remove(websocket)
await websocket.close()
In this code, we maintain a list of connected clients. When a new client connects, we add it to the list. When a client sends a message, we broadcast the message to all other connected clients.
It is important to handle errors properly in a WebSocket application. When an error occurs, you should close the connection gracefully and clean up any resources. In the previous examples, we used a try - except
block to catch exceptions and close the WebSocket connection.
Implementing WebSocket in FastAPI is a powerful way to build real - time web applications. By understanding the fundamental concepts, usage methods, common practices, and best practices, you can create robust and efficient WebSocket - based applications. FastAPI’s built - in support for WebSocket simplifies the development process, allowing you to focus on the application logic.