Real-time apps are everywhere — from chat systems and live dashboards to multiplayer games and stock tickers. If you’re building something that needs instant updates, HTTP just won’t cut it. You need a two-way communication protocol. That’s where WebSockets come in.
Pair WebSockets with FastAPI, and you get a blazing-fast, modern Python framework that’s built to handle asynchronous operations with ease. In this guide, you’ll learn how to build real-time functionality into your FastAPI app using WebSockets — with clear examples and practical code you can reus
What Are WebSockets and Why Use Them?
Traditional HTTP is request-response. The client makes a request, the server sends back a response, and the connection closes. It works great for most web interactions, but it falls short when your app needs to push updates to the client as things happen.
WebSockets solve this by keeping the connection open. Once established, a WebSocket allows two-way communication: the server can send data to the client anytime, and vice versa — no need to keep polling the server for updates.
When Should You Use WebSockets?
Here are a few common real-world use cases:
- Chat applications: Send and receive messages instantly.
- Live notifications: Show real-time alerts, like new emails or system updates.
- Collaborative tools: Think Google Docs or Figma-style editing.
- Multiplayer games: Sync player actions and game state live.
- Real-time dashboards: Push analytics updates without refreshing the page.
In short, if your app needs to react to events in real time, WebSockets are the way to go.
Why WebSockets with FastAPI?
FastAPI is built on ASGI, which supports asynchronous protocols like WebSockets with FastAPI out of the box. Unlike Flask (which requires extra tools like Flask-SocketIO) or Django (which needs Django Channels), FastAPI handles WebSocket routes natively and cleanly.
You don’t need third-party libraries or convoluted setup. Just define a @app.websocket() route and you’re good to go. Plus, FastAPI gives you:
- Type hints and auto-completion for WebSocket parameters.
- Full async/await support.
- Performance close to Node.js and Go.
If you want a modern, minimalist stack that’s production-ready and developer-friendly, FastAPI is a solid choice.
Setting Up Your FastAPI Project
Let’s get started with the basics. First, create a new project folder and set up a virtual environment:
python -m venv venv
source venv/bin/activate # or venv\Scripts\activate on Windows
Then install FastAPI and an ASGI server like uvicorn:
pip install fastapi uvicorn
Now create a main.py file with this boilerplate:
from fastapi import FastAPI
app = FastAPI()
You can now run your server using:
uvicorn main:app --reload
Your FastAPI app is live at http://localhost:8000. Let’s add a WebSocket endpoint next.
FastAPI WebSocket Example: First Endpoint
Defining a WebSocket endpoint in FastAPI is refreshingly simple. Unlike other frameworks that require additional setup or third-party libraries, FastAPI handles it natively — thanks to its ASGI foundation.
Let’s start with a basic example. We’ll create a /ws route that accepts a WebSocket connection, sends a greeting, and then closes the connection. It’s the WebSocket equivalent of “Hello, world.”
Once a client connects, FastAPI passes in a WebSocket object. With this, we can accept the connection, send or receive messages, and close the connection when needed. Everything is handled asynchronously, which means your app can scale efficiently and respond to multiple clients in real time.
Building a Real-Time Chat Example
Now let’s make things more dynamic: we’ll build a mini real-time chat system. Each client that connects gets added to a list. When one client sends a message, the server broadcasts it to everyone in that list — instant communication.
This simple setup already captures the essence of WebSockets with FastAPI: persistent, two-way communication between client and server. We also make sure to handle disconnections properly, removing clients from the list when they drop out. It’s a small but powerful foundation, ready to evolve into a full-featured real-time app.
Client-Side WebSocket Integration
With the backend ready, it’s time to connect from the frontend. No need for frameworks—just a basic HTML file with a bit of JavaScript.
At the core is this line:
const socket = new WebSocket("ws://localhost:8000/ws");
This opens a persistent connection to the FastAPI server. Once connected, we can listen for messages using socket.onmessage and send new ones via socket.send().
When a message arrives, it’s displayed in the browser:
socket.onmessage = (event) => {
console.log("Received:", event.data);
};
This simple setup turns a static HTML page into a live chat interface. You can open it in multiple browser tabs and see messages flowing in real time.
Handling Multiple Connections
In real-time apps, managing active connections is crucial. A simple approach is to keep track of connected clients using a set().
Each time a user connects, we store the WebSocket object:
connections.add(websocket)
When they send a message, we loop through the connections and forward it:
for conn in connections:
await conn.send_text(f"{data}")
But connections can drop unexpectedly. To avoid errors, we wrap the loop in a try/except block and clean up disconnected clients using connections.remove(websocket). This ensures your app doesn’t crash when a user suddenly closes the browser.
Improving Your WebSocket App
With the basics working, there are several ways to upgrade your app.
First, authentication: you can pass a JWT token during the connection and verify the user before accepting it. This adds a layer of security and personalization.
Next, consider adding chat rooms or channels. By grouping clients based on their desired room, you can isolate conversations and scale the app naturally.
Finally, for apps running on multiple servers, use Redis pub/sub to sync messages across instances. This is essential for scaling WebSocket-based apps in production.
The result? A real-time system that’s not only fast, but production-ready.
Conclusion
Just a few lines of code and you can bring real-time features to your WebSockets with FastAPI. Whether it’s a chat, live dashboard, or multiplayer game, the foundation is the same—lightweight, fast, and scalable. Now you’re ready to build interactive apps that feel truly alive.