Adding WebSockets to Your FastAPI App (With a Real-Time Chat Example)
This step-by-step guide shows you how to add WebSocket support to your FastAPI app by building a real-time chat system from scratch —…

FastAPI is already fast — but pair it with WebSockets, and you unlock real-time magic.
Adding WebSockets to Your FastAPI App (With a Real-Time Chat Example)
This step-by-step guide shows you how to add WebSocket support to your FastAPI app by building a real-time chat system from scratch — perfect for modern, interactive applications.
Imagine building a chat app where users see new messages instantly — without refreshing the page or constantly polling the server. That’s the magic of WebSockets.
FastAPI, the modern and lightning-fast web framework for Python, has native support for WebSockets, making it incredibly easy to build real-time features like chat, notifications, dashboards, and collaborative tools.
In this article, we’ll walk through how to add WebSocket support to your FastAPI app, step-by-step. And yes, we’ll build a simple real-time chat app that just works.
What Are WebSockets (And Why Should You Care)?
WebSockets provide a persistent, bi-directional communication channel between the client and the server. Unlike HTTP, which follows a request-response pattern, WebSockets allow the server to push data to the client at any time.
This makes WebSockets ideal for:
Real-time chat apps
Live sports scores and stock tickers
Multiplayer games
Live notifications
Collaborative editing tools (think Google Docs)
Setting Up Your FastAPI App
Let’s get our project up and running.
Install Required Packages
pip install fastapi uvicorn
We’ll use uvicorn
as the ASGI server to run our FastAPI app.
Step 1: Basic FastAPI App With WebSocket Support
Let’s start with the essentials — creating a simple WebSocket endpoint.
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from typing import List
app = FastAPI()
class ConnectionManager:
def __init__(self):
self.active_connections: List[WebSocket] = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
def disconnect(self, websocket: WebSocket):
self.active_connections.remove(websocket)
async def broadcast(self, message: str):
for connection in self.active_connections:
await connection.send_text(message)
manager = ConnectionManager()
@app.websocket("/ws/chat")
async def websocket_endpoint(websocket: WebSocket):
await manager.connect(websocket)
try:
while True:
data = await websocket.receive_text()
await manager.broadcast(f"Message: {data}")
except WebSocketDisconnect:
manager.disconnect(websocket)
Step 2: Create the Chat Frontend (HTML + JS)
Now, let’s build a very simple frontend to test our chat app.
Create a file named chat.html
:
<!DOCTYPE html>
<html>
<head>
<title>FastAPI Chat</title>
</head>
<body>
<h2>FastAPI Real-Time Chat</h2>
<ul id="messages"></ul>
<input type="text" id="messageInput" autocomplete="off"/>
<button onclick="sendMessage()">Send</button>
<script>
const ws = new WebSocket("ws://localhost:8000/ws/chat");
ws.onmessage = function(event) {
const messages = document.getElementById('messages');
const message = document.createElement('li');
message.innerText = event.data;
messages.appendChild(message);
};
function sendMessage() {
const input = document.getElementById("messageInput");
ws.send(input.value);
input.value = '';
}
</script>
</body>
</html>
Just open this HTML file in your browser after running the FastAPI server.
Step 3: Run Your App
uvicorn main:app --reload
Now, open multiple tabs of chat.html
and start chatting. Messages will appear in real-time across all connected clients.
Bonus: Handling Usernames and More
Want to personalize messages? Add a username
parameter in the URL and modify the websocket_endpoint
to extract and use it.
@app.websocket("/ws/chat/{username}")
async def websocket_endpoint(websocket: WebSocket, username: str):
await manager.connect(websocket)
try:
while True:
data = await websocket.receive_text()
await manager.broadcast(f"{username}: {data}")
except WebSocketDisconnect:
manager.disconnect(websocket)
await manager.broadcast(f"{username} left the chat")
Then update your frontend’s WebSocket URL like:
const username = prompt("Enter your username:");
const ws = new WebSocket(`ws://localhost:8000/ws/chat/${username}`);
Gotchas to Watch Out For
WebSocket is not HTTP: You can’t use regular HTTP tools (e.g.,requests
,postman
) to test WebSockets.
Connection Limits: Your server needs to manage many simultaneous connections efficiently. Consider async workers or cloud services.
Security: Use authentication and HTTPS in production. FastAPI supports authentication with WebSockets using query params or headers.
Final Thoughts
Adding WebSockets to a FastAPI app is surprisingly easy — and powerful. Whether you’re building a chat app, a collaborative editor, or real-time dashboards, FastAPI’s native support makes it smooth and scalable.
Your turn: Try extending this example to support private messaging, message history, or even emojis. Real-time apps are the future — don’t get left behind.
