This project demonstrates real-time chat communication using FastAPI’s WebSocket feature. Messages sent by any connected client are broadcasted instantly to all users — a simple group chat over a local WebSocket server.
Project_27_CLI_Chat_App/
│
├── main.py # FastAPI WebSocket backend
├── index.html # Simple chat frontend
└── requirements.txt # Dependencies list
git clone https://github.com/Raxku2/Noob_to_Monstar_Python/edit/main/Project_27.git
cd cli-chat-apppython -m venv venv
source venv/bin/activate # macOS/Linux
venv\Scripts\activate # Windowspip install -r requirements.txtuvicorn main:app --reloadServer will start at: 👉 http://127.0.0.1:8000
- Clients connect via a WebSocket endpoint
/msg. - Each message is broadcasted to all connected clients.
- The
/sendroute allows sending messages from any HTTP client (even curl or JSfetch()). - HTML frontend connects automatically using JavaScript WebSocket.
The frontend is a minimal chat UI that:
- Connects to
ws://127.0.0.1:8000/msg - Displays connection status (🟢 connected / 🔴 disconnected)
- Sends messages using
/send?msg=... - Auto-scrolls message log
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_methods=['*'],
allow_headers=['*'],
allow_credentials=True,
)
connections = []
@app.websocket('/msg')
async def message(websck: WebSocket):
await websck.accept()
connections.append(websck)
try:
while True:
data = await websck.receive_text()
except WebSocketDisconnect:
connections.remove(websck)
@app.get('/send')
async def send(msg: str):
for conn in connections:
await conn.send_text(msg)
return {"status": "ok", "message": msg}<script>
const BASEAPI = "http://127.0.0.1:8000";
const socket = new WebSocket("ws://127.0.0.1:8000/msg");
socket.onmessage = e => {
const message = document.createElement('p');
message.textContent = '> ' + e.data;
document.getElementById('msgbox').appendChild(message);
};
</script>fastapi==0.117.1
uvicorn==0.37.0
anyio==4.11.0
h11==0.16.0
idna==3.10
sniffio==1.3.1
- Open two terminals or browsers with
index.html. - Type a message → It appears on both screens instantly!
- You’ve built a real-time communication system. 🔥
- Add username and message timestamps
- Persist chat history in MongoDB
- Build a React/Vue chat UI
- Deploy with WebSocket support on Render or Railway
YantraYodha 💡 Project from CodeShiksha Python Mastery Course (2025) 🧩 Real-world implementation of Socket Programming using FastAPI.