Skip to content

Instantly share code, notes, and snippets.

@rocapp
Forked from johnidm/readme.md
Created July 27, 2025 01:13
Show Gist options
  • Save rocapp/e9e300b96330cd823fd6b597f8e2af2f to your computer and use it in GitHub Desktop.
Save rocapp/e9e300b96330cd823fd6b597f8e2af2f to your computer and use it in GitHub Desktop.
Basic Real-Time Applications with WebSockets and FastAPI

Install dependencies - pip install fastapi 'uvicorn[standard]'

Run the example - uvicorn main:app --host 0.0.0.0 --port 8000

Access multiple pages from http://localhost:8000/ and send messages

Source code files

main.py

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

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 send_message(self, message: str, websocket: WebSocket):
        await websocket.send_text(message)

    async def broadcast(self, message: str):
        for connection in self.active_connections:
            await connection.send_text(message)


manager = ConnectionManager()


@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: int):
    await manager.connect(websocket)
    try:
        while True:
            print("Waiting for websocket connection {client_id}")
            print("Data received {data} bytes")

            data = await websocket.receive_text()
            await manager.send_message(f"Client {client_id}: {data}", websocket)
            await manager.broadcast(f"Client {client_id} says: {data}")
    except WebSocketDisconnect:
        manager.disconnect(websocket)
        await manager.broadcast(f"Client {client_id} disconnected")


@app.get("/")
async def get():
    with open("index.html") as f:
        return HTMLResponse(f.read())

index.html

<!DOCTYPE html>
<html>

<head>
    <title>WebSocket Chat</title>
</head>

<body>
    <h1>WebSocket Chat</h1>
    <input type="text" id="messageInput" autocomplete="off" />
    <button onclick="sendMessage()">Send</button>
    <ul id="messages"></ul>

    <script>
        const clientId = Math.floor(Math.random() * 1000);
        const ws = new WebSocket(`ws://localhost:8000/ws/${clientId}`);

        ws.onmessage = function (event) {
            const messages = document.getElementById('messages');
            const message = document.createElement('li');
            message.textContent = event.data;
            messages.appendChild(message);
        };

        function sendMessage() {
            const input = document.getElementById("messageInput");
            ws.send(input.value);
            input.value = '';
        }
    </script>
</body>

</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment