EventSourceResponse is a specialized streaming response class for Server-Sent Events (SSE). It enables real-time, unidirectional communication from server to client over HTTP.
Import
Class Signature
Usage
Basic SSE Stream
Yield data objects that are automatically JSON-encoded:Using ServerSentEvent
Full control over SSE event fields:Synchronous Generator
Use regular (non-async) generators:Mixed Content Types
Mix regular objects with ServerSentEvent:Raw Data (No JSON Encoding)
Send pre-formatted text without JSON encoding:POST Method Support
SSE works with any HTTP method, including POST:ServerSentEvent Fields
Any
default:"None"
The event payload. Can be any JSON-serializable value (dict, list, string, number, Pydantic model, etc.). Always JSON-encoded, including strings.Mutually exclusive with
raw_data.str | None
default:"None"
Raw string to send as the
data: field without JSON encoding. Use for pre-formatted text, HTML, CSV, or non-JSON payloads.Mutually exclusive with data.str | None
default:"None"
Optional event type name. Maps to
addEventListener(event, ...) on the client. When omitted, the browser dispatches on the generic message event.str | None
default:"None"
Optional event ID. The browser sends this value back as the
Last-Event-ID header on automatic reconnection. Must not contain null (\0) characters.int | None
default:"None"
Optional reconnection time in milliseconds. Tells the browser how long to wait before reconnecting after the connection is lost. Must be a non-negative integer.
str | None
default:"None"
Optional comment line(s). Comments start with
: in the SSE wire format and are ignored by EventSource clients. Useful for keep-alive pings.Client-Side JavaScript
Basic EventSource
Named Events
With Reconnection
SSE Wire Format
Events are formatted as text with specific field prefixes:Automatic Keep-Alive
FastAPI automatically sends keep-alive comments every 15 seconds when the generator is idle, preventing proxy/load-balancer timeouts:Properties
media_type
Notes
- SSE is unidirectional (server to client only)
- Browsers automatically reconnect on connection loss
- Compatible with all HTTP methods (GET, POST, etc.)
- The
EventSourceAPI is built into modern browsers - Maximum concurrent SSE connections per domain is typically 6
- Use WebSockets for bidirectional communication
- All
datavalues are JSON-serialized, including plain strings - Use
raw_datafor non-JSON content
Data vs Raw Data
data (JSON-encoded)
raw_data (No encoding)
Error Handling
Best Practices
- Use event types: Name your events for easier client-side handling
- Include IDs: Event IDs enable automatic reconnection from the last received event
- Set retry intervals: Control how quickly clients reconnect after disconnection
- Handle errors gracefully: Send error events before closing the stream
- Consider scaling: SSE connections are long-lived; plan for horizontal scaling
- Monitor connections: Track active SSE connections for capacity planning
Related
- StreamingResponse - Generic streaming
- WebSockets - Bidirectional communication
- ServerSentEvent - SSE specification