Thursday, 20 November 2025

#11 WebSockets (Real-Time Chat)

FastAPI Module 11 — WebSockets (Real-Time Chat)

Module 11 — WebSockets (Real-Time Chat)

In this module, you’ll learn how to build a real-time chat system using FastAPI’s WebSocket support. We’ll also create a simple frontend chat UI to test instantly.


1️⃣ WebSocket Basics

A WebSocket connection stays open and allows bi-directional messaging, unlike normal HTTP.

from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket("/ws") async def websocket_demo(ws: WebSocket): await ws.accept() await ws.send_text("Connection established!") while True: msg = await ws.receive_text() await ws.send_text(f"You said: {msg}")

2️⃣ Chat Manager — Handle Multiple Connected Clients

We create a class to store and broadcast messages to all active users.

class ConnectionManager: def __init__(self): self.active: list[WebSocket] = [] async def connect(self, ws: WebSocket): await ws.accept() self.active.append(ws) def disconnect(self, ws: WebSocket): self.active.remove(ws) async def broadcast(self, message: str): for conn in self.active: await conn.send_text(message) manager = ConnectionManager()

3️⃣ Full WebSocket Chat Route

from fastapi import FastAPI, WebSocket, WebSocketDisconnect from manager import manager app = FastAPI() @app.websocket("/chat") async def chat_socket(ws: WebSocket): await manager.connect(ws) await manager.broadcast("🔵 A new user joined the chat") try: while True: msg = await ws.receive_text() await manager.broadcast(f"User: {msg}") except WebSocketDisconnect: manager.disconnect(ws) await manager.broadcast("🔴 A user left the chat")

4️⃣ Frontend Chat UI (HTML + JavaScript)

Save this as chat.html and open in a browser.

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>FastAPI Chat</title> <style> body {background:#0e1522; color:white; font-family:Arial; padding:20px;} #chat {border:1px solid #333; padding:10px; height:300px; overflow-y:auto; background:#111;} input {width:80%; padding:8px;} button {padding:8px 12px; cursor:pointer;} </style> </head> <body> <h2>FastAPI WebSocket Chat</h2> <div id="chat"></div> <input id="msg" placeholder="Type message..." /> <button onclick="sendMsg()">Send</button> <script> let socket = new WebSocket("ws://127.0.0.1:8000/chat"); socket.onmessage = (e) => { let chat = document.getElementById("chat"); chat.innerHTML += "<div>" + e.data + "</div>"; chat.scrollTop = chat.scrollHeight; } function sendMsg(){ let input = document.getElementById("msg"); socket.send(input.value); input.value = ""; } </script> </body> </html>

5️⃣ Run the Chat Server

uvicorn chat_ws:app --reload

Then open chat.html in 2–3 browser tabs — chat live!


6️⃣ What You Learned

  • WebSocket protocol basics
  • Building async real-time communication in FastAPI
  • Maintaining active client pool
  • Broadcast messaging
  • Creating a front-end chat to test features

No comments:

Post a Comment

Diagnosis for running all Scripts

 Great — here is the complete ready-to-run folder structure for all 12 FastAPI modules , including: ✅ __init__.py (so Python treats folder...