FastAPI 0.140.12 is now available, addressing a critical bug in Server-Sent Events (SSE) handling that could produce malformed messages. The fix ensures compliance with the SSE specification, improving real-time event streaming reliability.
- Bug Fix: Corrected line splitting in
format_sse_eventto comply with the SSE spec (PR #15515 by @Zawwarsami16). The previous implementation mishandled newlines within event data, potentially causing events to be improperly concatenated or truncated. The updated logic now correctly splits lines using the\ndelimiter and sends each line with a leadingdata:field, per the SSE specification.
For developers using FastAPI's StreamingResponse with SSE, or relying on sse-starlette or similar integrations, this patch ensures that events are parsed correctly by clients. An example of the corrected behavior would be:
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import asyncio
app = FastAPI()
async def event_generator():
for i in range(3):
await asyncio.sleep(1)
yield f"data: event {i}\n\n"
@app.get("/events")
async def get_events():
return StreamingResponse(event_generator(), media_type="text/event-stream")
Prior to the fix, multi-line event data might have resulted in invalid event streams, causing clients like EventSource to fail or misinterpret events. FastAPI 0.140.12 resolves this without introducing breaking changes; your existing SSE code remains compatible, but now strictly adheres to the spec.
Upgrade via pip:
pip install --upgrade fastapi==0.140.12
Source: https://github.com/fastapi/fastapi/releases/tag/0.140.12