Build SSE in Python (FastAPI)
Weโre building a Server-Sent Events (SSE) demo using FastAPI. immediately and reliably. Install the required packages: pip install fastapi uvicorn Optional (for HTML rendering if needed): pip install jinja2 Save this as main.py: from fastapi import FastAPI from fastapi.responses import StreamingResp
Saras Growth Space
Weโre building a Server-Sent Events (SSE) demo using FastAPI.
This example streams messages to a browser immediately and reliably.
1๏ธโฃ Dependencies
Install the required packages:
pip install fastapi uvicorn
Optional (for HTML rendering if needed):
pip install jinja2
2๏ธโฃ Python Code (SSE + HTML)
Save this as main.py:
from fastapi import FastAPI
from fastapi.responses import StreamingResponse, HTMLResponse
import time
app = FastAPI()
# SSE generator
def event_generator():
for i in range(1, 6):
yield f"data: Message {i}\n\n" # Each message ends with two newlines
time.sleep(1) # simulate delay
# SSE endpoint
@app.get("/events")
async def sse():
return StreamingResponse(event_generator(), media_type="text/event-stream")
# Serve HTML page for testing
@app.get("/")
async def index():
return HTMLResponse("""
<!DOCTYPE html>
<html>
<body>
<h1>SSE Test</h1>
<ul id="messages"></ul>
<script>
const source = new EventSource("/events");
const messages = document.getElementById("messages");
source.onmessage = function(event) {
const li = document.createElement("li");
li.textContent = event.data;
messages.appendChild(li);
};
</script>
</body>
</html>
""")
โ Key points:
-
StreamingResponseโ streams events continuously -
data: ...\n\nโ required format for SSE - HTML served directly from FastAPI for easy testing
- Browser automatically reconnects if connection drops
3๏ธโฃ How to Run
Open terminal in the folder with main.py:
uvicorn main:app --reload
-
mainโ Python file name -
appโ FastAPI instance -
--reloadโ auto-reloads on code change
Then open in your browser:
http://127.0.0.1:8000/
You should see messages appear one by one every second.
โ ๏ธ Important Notes
- Each SSE message must end with
\n\n - Delay in the generator (
time.sleep()) simulates real-time updates - Browser handles reconnection automatically
๐ Next Steps
Next, weโll cover production challenges with SSE:
- Heartbeats to keep connections alive
- Automatic reconnection tips
- Proxy & load balancer considerations
- Scaling SSE for many clients
These are critical for building real-world SSE systems.
Found this useful? Share it!
Read the Full Story
Continue reading on Dev.to
Related Stories
Majority Element
about 2 hours ago
Building a SQL Tokenizer and Formatter From Scratch โ Supporting 6 Dialects
about 2 hours ago
Markdown Knowledge Graph for Humans and Agents
about 2 hours ago

Moving Beyond Disk: How Redis Supercharges Your App Performance
about 2 hours ago