Implementing asynchronous Server-Sent Events (SSE)
SSE is a server push mechanism that sends data to the browser without reloading the page. Once subscribed, it generates event-driven streams in real time for various purposes.
Creating SSE in the FastAPI framework only requires the following:
- The
EventSourceResponse
class from thesse_starlette.see
module - An event generator
Above all, the framework also allows non-blocking implementation of the whole server push mechanism using coroutines that can run even on HTTP/2. The following is a coroutine API service that implements a Kafka consumer using SSE’s open and lightweight protocol:
from sse_starlette.sse import EventSourceResponse @router.get('/messenger/sse/add') async def send_message_stream(request: Request): async def event_provider(): while True: ...