InterviewHubPRO
Section Overview
Q52

Question 52 of 65

Part 4: Web Frameworks, APIs & FastAPI (41 - 55)

80%
Python & FastAPI•Part 4: Web Frameworks, APIs & FastAPI (41 - 55)

Server-Sent Events (SSE) in FastAPI:

In Simple Words: Stream real-time text events to clients over a persistent HTTP connection using StreamingResponse.

python
import asyncio
from fastapi.responses import StreamingResponse

async def event_generator():
    for i in range(5):
        await asyncio.sleep(1)
        yield f"data: {{"count": {i}}}

"

@app.get("/stream")
async def stream():
    return StreamingResponse(event_generator(), media_type="text/event-stream")