Sure, setting up Server-Sent Events (SSE) with FastAPI can be straightforward. Here’s a simple guide to get you started:
What is SSE?
Server-Sent Events (SSE) allow a web page to get updates from a server. This is a one-way stream of data from the server to the client.
Steps to Set Up SSE with FastAPI
1. Install FastAPI and Uvicorn
First, you need to install FastAPI and Uvicorn (an ASGI server).
pip install fastapi uvicorn
2. Create a Simple FastAPI App
Create a Python file, let’s call it main.py.
from fastapi import FastAPI, Response
import asyncio
import time
app = FastAPI()
@app.get("/events")
async def sse_events(response: Response):
response.headers["Content-Type"] = "text/event-stream"
response.headers["Cache-Control"] = "no-cache"
response.headers["Connection"] = "keep-alive"
i = 0
while True:
data = f"data: {{'count': {i}}}\n\n"
await response.write(data)
await asyncio.sleep(1) # Send data every second
i += 1
3. Run the FastAPI App
Run your FastAPI app using Uvicorn.
uvicorn main:app --reload
Explanation
- Endpoint
/events: This endpoint will send events to the client.
- Response Headers:
Content-Type: Set to text/event-stream for SSE.
Cache-Control: Set to no-cache to ensure the browser doesn’t cache the stream.
Connection: Set to keep-alive to keep the connection open.
- Event Loop: The
while True loop keeps sending data every second. The await response.write(data) sends the data to the client.
Client-Side (HTML)
To receive these events on the client side, you can use the following HTML:
<!DOCTYPE html>
<html>
<head>
<title>SSE Example</title>
</head>
<body>
<h1>Server-Sent Events</h1>
<p id="result"></p>
<script>
const eventSource = new EventSource("http://127.0.0.1:8000/events");
eventSource.onmessage = function(event) {
document.getElementById("result").innerText = `Received: ${event.data}`;
};
eventSource.onerror = function(err) {
console.error("EventSource failed:", err);
eventSource.close();
};
</script>
</body>
</html>
Summary
- Install FastAPI and Uvicorn.
- Create a FastAPI app with an endpoint to send SSE.
- Run the app using Uvicorn.
- Create an HTML page to receive and display the events.
This should help you get started with SSE in FastAPI!