Basic SSE Endpoint
Create an SSE endpoint usingEventSourceResponse and yield:
When you yield plain objects (dicts, Pydantic models, etc.), FastAPI automatically JSON-encodes them and sends them as SSE
data: fields.ServerSentEvent Model
For fine-grained control over SSE events, use theServerSentEvent model:
ServerSentEvent Fields
data
The event payload. Can be any JSON-serializable value:raw_data
Send raw string data without JSON encoding:Use
raw_data when you need to send pre-formatted text, HTML fragments, CSV lines, or any non-JSON payload. The data and raw_data fields are mutually exclusive.event
Optional event type name that maps toaddEventListener(event, ...) on the browser:
message event.
id
Optional event ID for resuming streams:Last-Event-ID header on automatic reconnection.
retry
Optional reconnection time in milliseconds:comment
Optional comment line(s) for keep-alive pings:: in the SSE wire format and are ignored by EventSource clients. Useful for preventing proxy/load-balancer timeouts.
Resuming Streams with Last-Event-ID
Handle reconnections by reading theLast-Event-ID header:
SSE with POST Requests
EventSourceResponse works with any HTTP method, including POST:
SSE over POST is useful for protocols like MCP (Model Context Protocol) that require streaming responses with request bodies.
Synchronous Generators
You can use regular (non-async) generator functions:Client-Side JavaScript
Connect to SSE endpoints using theEventSource API:
SSE with POST (JavaScript)
For POST requests, usefetch with a ReadableStream:
SSE Wire Format
SSE events follow thetext/event-stream format:
\n\n).
FastAPI automatically handles SSE wire format encoding. You don’t need to manually format events.
When to Use SSE vs WebSockets
Use Server-Sent Events when:- You only need server-to-client communication
- You want automatic reconnection with event replay
- You prefer working over standard HTTP/HTTPS
- You’re building notifications, live feeds, or progress updates
- You need bidirectional communication
- You require lower latency
- You’re building chat applications or real-time collaboration tools