DEV Community

Cover image for Build a Real-Time Chat App with FastAPI WebSockets
Muhammad Saud
Muhammad Saud

Posted on Originally published at logicstack.org

Build a Real-Time Chat App with FastAPI WebSockets

A WebSocket is a single long-lived connection between a browser and a server, and either side can send a message at any time. That makes it the right tool for chat, notifications and dashboards, where polling would waste requests. In this tutorial we build a chat app with FastAPI where two browsers can talk in real time, in separate rooms.

Key takeaways

  • FastAPI has WebSocket support built in through the @app.websocket decorator and the WebSocket class from Starlette.
  • A connection manager keeps one list of live sockets per room, so a message goes only to the people in that room.
  • Every message is a small JSON object with a type, so the browser can tell a chat message apart from a system notice.
  • A send that fails marks the socket as dead, and the manager drops it, so one closed tab never breaks a broadcast.
  • FastAPI TestClient can open real WebSocket connections in tests, so we can test the whole chat without a browser.

What we build

We build a chat app with three parts. A FastAPI server accepts WebSocket connections at /ws/{room}, so each room has its own address. A connection manager tracks who is in each room, broadcasts messages and keeps the last 50 messages per room. A small HTML page in the browser opens the socket, shows messages and reconnects when the user clicks Join. We also write six tests that open real WebSocket connections and check the whole flow. Every script below ran on our machine with Python 3.12.3, FastAPI 0.162.2, Uvicorn 0.54.0, websockets 17.4 and pytest 9.2.0, and every output block is the real output of that script.

Most WebSocket tutorials stop at an echo server that sends your own message back to you. That is not a chat app. Ours adds the parts a real chat needs: rooms, join and leave notices, a short history for late joiners, and cleanup when a socket dies. A guide published in October 2026 makes the same point, that authentication, broadcast, dead-connection cleanup and reconnect logic are the parts most tutorials skip.

Why use WebSockets instead of polling?

Polling means the browser asks the server "anything new?" every few seconds. With ten users that is hundreds of empty requests a minute, and messages still arrive late, up to one polling interval after they were sent. A WebSocket keeps one connection open, and the server pushes each message the moment it arrives. The cost is one connection per user instead of one request per poll, which is far cheaper for chat. WebSockets are bidirectional, so the same connection carries messages both ways. For one-way updates such as a news feed, server-sent events are a simpler option, but chat needs both directions, so WebSockets are the right pick here.

Prerequisites

  • Python 3.10 or newer and pip. FastAPI 0.162 requires Python 3.9 or newer, according to the official FastAPI documentation.
  • Basic Python: functions, classes, dictionaries and lists.
  • A little async and await. If you have used async def once, that is enough.
  • No account, no API key, no database. Everything runs locally.

Step 1: Set up the project and install the libraries

We keep the project in its own folder with a virtual environment, so the packages stay separate from the rest of the system. FastAPI is the web framework, Uvicorn is the server that runs it, websockets is the client library our live smoke test uses, and pytest runs the tests.

mkdir websocket-chat
cd websocket-chat
python3 -m venv .venv
source .venv/bin/activate
pip install fastapi uvicorn websockets pytest
python -c "import fastapi, uvicorn, websockets, pytest; print(fastapi.__version__, uvicorn.__version__, websockets.__version__, pytest.__version__)"
Enter fullscreen mode Exit fullscreen mode

Our machine printed:

0.162.2 0.54.0 17.4 9.2.0
Enter fullscreen mode Exit fullscreen mode

Step 2: Build the connection manager

The manager is the heart of the app. It keeps one list of live sockets per room and one short history per room. The broadcast method is the part that matters most: it sends to every socket in the room, and if a send raises an error, that socket goes on a dead list and is removed. Without that sweep, one ghost connection eventually breaks every broadcast, because the error stops the loop. The history is a deque with a maximum length of 50, so old messages drop off on their own and memory stays bounded.

from collections import defaultdict, deque
from datetime import datetime, timezone

from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse

app = FastAPI(title="FastAPI WebSocket chat")

MAX_HISTORY = 50

def _now() -> str:
    return datetime.now(timezone.utc).strftime("%H:%M:%S")

class ConnectionManager:
    """Tracks live WebSocket connections, grouped by chat room."""

    def __init__(self) -> None:
        self.rooms: dict[str, list[WebSocket]] = defaultdict(list)
        self.history: dict[str, deque] = defaultdict(
            lambda: deque(maxlen=MAX_HISTORY)
        )

    async def connect(self, websocket: WebSocket, room: str) -> None:
        await websocket.accept()
        self.rooms[room].append(websocket)

    def disconnect(self, websocket: WebSocket, room: str) -> None:
        if websocket in self.rooms[room]:
            self.rooms[room].remove(websocket)

    async def broadcast(self, room: str, message: dict) -> None:
        """Send to every socket in the room and drop dead ones."""
        dead: list[WebSocket] = []
        for connection in self.rooms[room]:
            try:
                await connection.send_json(message)
            except Exception:
                dead.append(connection)
        for connection in dead:
            self.disconnect(connection, room)

    def record(self, room: str, message: dict) -> None:
        self.history[room].append(message)

manager = ConnectionManager()
Enter fullscreen mode Exit fullscreen mode

Two details are worth noting. First, connect calls await websocket.accept() before it records the socket. Until accept runs, the connection is only a handshake, and sending on it would fail. Second, the history lives in memory. Restart the server and it is gone. That is fine for this tutorial, and the "What to try next" section at the end shows how to persist it.

Step 3: Add the WebSocket endpoint and the history endpoint

The endpoint takes the room from the URL and the username from a query string, because a browser WebSocket cannot send custom headers during the handshake. When a user joins, we record a system message and broadcast it, so everyone sees who arrived. Then we loop forever, reading text and broadcasting it as a chat message. When the socket closes, WebSocketDisconnect fires, we remove the socket and broadcast a leave notice. A plain REST endpoint serves the history, so a new client can fetch what it missed.

@app.get("/rooms/{room}/messages")
async def room_history(room: str):
    return {"room": room, "messages": list(manager.history[room])}

@app.websocket("/ws/{room}")
async def websocket_endpoint(websocket: WebSocket, room: str):
    username = websocket.query_params.get("username", "guest")
    await manager.connect(websocket, room)
    join_message = {
        "type": "system",
        "text": f"{username} joined the room",
        "time": _now(),
    }
    manager.record(room, join_message)
    await manager.broadcast(room, join_message)
    try:
        while True:
            text = await websocket.receive_text()
            message = {
                "type": "chat",
                "username": username,
                "text": text,
                "time": _now(),
            }
            manager.record(room, message)
            await manager.broadcast(room, message)
    except WebSocketDisconnect:
        manager.disconnect(websocket, room)
        leave_message = {
            "type": "system",
            "text": f"{username} left the room",
            "time": _now(),
        }
        manager.record(room, leave_message)
        await manager.broadcast(room, leave_message)
Enter fullscreen mode Exit fullscreen mode

Every message is a JSON object with a type field. Chat messages carry username, text and time. System messages carry text and time only. The browser reads the type and renders each one differently, which keeps the client code simple.

Step 4: Add the browser page

The page is plain HTML and JavaScript, no framework. The Join button opens a socket to /ws/{room}?username={name}. Incoming messages are parsed as JSON and appended to the message box, with system notices in grey italics. Sending is a single ws.send() call, and the Enter key sends too. When the socket closes, the page prints a note and waits for the user to click Join again, which is the simplest honest form of reconnect logic.

@app.get("/", response_class=HTMLResponse)
async def home():
    return HTML_PAGE

HTML_PAGE = """


  FastAPI WebSocket Chat

    body { font-family: sans-serif; max-width: 600px; margin: 2rem auto; }
    #messages { border: 1px solid #ccc; height: 300px; overflow-y: auto; padding: 1rem; }
    .system { color: #888; font-style: italic; }


  FastAPI WebSocket Chat
  Room: 
  Name: 
  Join


  Send

    let ws = null;
    function connect() {
      const room = document.getElementById("room").value;
      const name = document.getElementById("name").value;
      ws = new WebSocket(`ws://${location.host}/ws/${room}?username=${name}`);
      ws.onmessage = (event) => {
        const msg = JSON.parse(event.data);
        const div = document.createElement("div");
        div.textContent = msg.type === "system"
          ? `[${msg.time}] ${msg.text}`
          : `[${msg.time}] ${msg.username}: ${msg.text}`;
        if (msg.type === "system") div.className = "system";
        document.getElementById("messages").appendChild(div);
      };
      ws.onclose = () => {
        const div = document.createElement("div");
        div.className = "system";
        div.textContent = "Connection closed. Click Join to reconnect.";
        document.getElementById("messages").appendChild(div);
      };
    }
    function sendMessage() {
      const input = document.getElementById("text");
      if (input.value.trim() && ws && ws.readyState === WebSocket.OPEN) {
        ws.send(input.value);
        input.value = "";
      }
    }
    document.getElementById("text").addEventListener("keydown", (e) => {
      if (e.key === "Enter") sendMessage();
    });


"""
Enter fullscreen mode Exit fullscreen mode

Step 5: Run the server and chat in two tabs

Start Uvicorn and open http://127.0.0.1:8000 in two browser tabs. Pick different names and the same room, and a message typed in one tab appears in the other at once.

uvicorn main:app --port 8000
Enter fullscreen mode Exit fullscreen mode

Our machine printed the usual startup lines, then served the page and an empty history:

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
{"room":"general","messages":[]}
Enter fullscreen mode Exit fullscreen mode

We then ran a live smoke test with two real WebSocket clients, Alice and Bob, against the running server. This is the part that proves the app works over a real socket, not only inside the test client.

alice join: {'type': 'system', 'text': 'alice joined the room', 'time': '02:52:08'}
bob join: {'type': 'system', 'text': 'bob joined the room', 'time': '02:52:08'}
alice sees bob join: {'type': 'system', 'text': 'bob joined the room', 'time': '02:52:08'}
alice receives: {'type': 'chat', 'username': 'alice', 'text': 'Hello from the live server', 'time': '02:52:08'}
bob receives: {'type': 'chat', 'username': 'alice', 'text': 'Hello from the live server', 'time': '02:52:08'}
SMOKE TEST OK
Enter fullscreen mode Exit fullscreen mode

The history endpoint afterwards showed the full story of the room: both joins, the chat message, and both leave notices, in order. That is the whole flow working end to end.

How do we test WebSockets without a browser?

FastAPI TestClient can open WebSocket connections in tests, using the same websocket_connect context manager. We wrote six tests: the home page serves, an empty room returns an empty history, two clients chat and both receive every message, rooms are isolated, a disconnect broadcasts a leave notice, and the history endpoint holds the full conversation afterwards. The room isolation test is the one that catches the most common bug, a broadcast that leaks into every room instead of one.

python -m pytest test_chat.py -v
Enter fullscreen mode Exit fullscreen mode

Our machine printed:

test_chat.py::test_home_page_serves PASSED
test_chat.py::test_empty_history PASSED
test_chat.py::test_two_clients_chat PASSED
test_chat.py::test_rooms_are_isolated PASSED
test_chat.py::test_disconnect_broadcasts_leave_notice PASSED
test_chat.py::test_history_endpoint_after_chat PASSED

============================== 6 passed in 0.82s ===============================
Enter fullscreen mode Exit fullscreen mode

One honest limit of these tests: TestClient runs the app in the same process, so it cannot catch a bug that only appears over a real network socket. That is why step 5 ran the live smoke test as well. Both layers together give us real confidence.

What to try next

  • Add JWT authentication to the handshake. A browser cannot send an Authorization header when it opens a WebSocket, so the usual answer is a token in the query string, verified before accept() runs. Our tutorial on adding JWT authentication to FastAPI covers the token side of that.
  • Persist the history in SQLite instead of memory, so a restart keeps the conversation. Our SQLite full-text search tutorial shows the same database patterns in a small app.
  • Scale past one worker with Redis pub and sub, so a message sent to worker A also reaches clients connected to worker B. The manager stays the same, and the broadcast step publishes to a Redis channel first.

Originally published on LogicStack. Run the code examples right in your browser with our free interactive Python and SQL playgrounds — no setup, no sign-up.

Top comments (0)