DEV Community

Saras Growth Space
Saras Growth Space

Posted on

Build SSE in Python (FastAPI)

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
Enter fullscreen mode Exit fullscreen mode

Optional (for HTML rendering if needed):

pip install jinja2
Enter fullscreen mode Exit fullscreen mode

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>
    """)
Enter fullscreen mode Exit fullscreen mode

✅ 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
Enter fullscreen mode Exit fullscreen mode
  • main → Python file name
  • app → FastAPI instance
  • --reload → auto-reloads on code change

Then open in your browser:

http://127.0.0.1:8000/
Enter fullscreen mode Exit fullscreen mode

You should see messages appear one by one every second.


⚠️ Important Notes

  1. Each SSE message must end with \n\n
  2. Delay in the generator (time.sleep()) simulates real-time updates
  3. 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.

Top comments (0)