Setting Up Server-Sent Events (SSE) with FastAPI - Simple Guide
As a data scientist, you can think of SSE as a way to stream data from your FastAPI backend to your frontend in real-time, like a continuous data pipeline.
Basic Setup
Here's the simplest way to implement SSE in FastAPI:
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import asyncio
import time
app = FastAPI()
async def generate_data():
"""This is your data generator function"""
for i in range(10):
# Simulate some data processing
data = {"message": f"Data point {i}", "value": i * 10}
# Format as SSE
yield f"data: {data}\n\n"
# Wait a bit before sending next data point
await asyncio.sleep(1)
@app.get("/stream")
async def stream_data():
"""Endpoint that streams data"""
return StreamingResponse(generate_data(), media_type="text/event-stream")
How to Use It
-
Frontend Connection: In your JavaScript frontend, you'd connect like this:
const eventSource = new EventSource('/stream');
eventSource.onmessage = function(event) {
const data = JSON.parse(event.data);
console.log('New data:', data);
// Update your UI here
};
-
Testing: You can test the endpoint with curl:
curl -N http://localhost:8000/stream
Key Concepts
- StreamingResponse: FastAPI's way to send data in chunks rather than all at once
- SSE Format: Each message must end with
\n\n and start with data:
- Async Generator: The
generate_data() function yields data points one at a time
Practical Example for Data Science
Here's a more data-science-relevant example that streams model predictions:
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import asyncio
import numpy as np
app = FastAPI()
async def generate_predictions():
"""Simulate streaming model predictions"""
for i in range(20):
# Simulate some model prediction
prediction = {
"timestamp": time.time(),
"prediction": float(np.random.randn()),
"confidence": float(np.random.rand())
}
yield f"data: {prediction}\n\n"
await asyncio.sleep(0.5) # Simulate processing time
@app.get("/predictions")
async def stream_predictions():
return StreamingResponse(generate_predictions(), media_type="text/event-stream")
This gives you a real-time stream of model predictions that your frontend can display as they're generated.