Requests-SSE Client

0.5.3 · active · verified Fri Apr 17

requests-sse is a Python client library for Server-Sent Events (SSE), built on top of the popular 'requests' HTTP library. It provides an `EventSource` object for consuming event streams, handling reconnections and message parsing according to the WHATWG SSE specification. The current stable version is 0.5.3, with a beta 0.6.0b0 indicating an upcoming major release. The library generally follows an active release cadence with minor updates and bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a Server-Sent Events stream using `EventSource` and iterate over incoming `MessageEvent` objects. It uses the `with` statement for proper resource management and shows how to access event properties like `id`, `event` (type), and `data`.

import os
from requests_sse import EventSource

# Example of a public SSE endpoint (Wikimedia recent changes stream)
SSE_ENDPOINT = os.environ.get('SSE_URL', 'https://stream.wikimedia.org/v2/stream/recentchange')

try:
    with EventSource(SSE_ENDPOINT) as es:
        print(f"Connected to SSE stream: {SSE_ENDPOINT}")
        message_count = 0
        for event in es:
            if event.event == "message":
                print(f"Received message: ID={event.id}, Type='{event.type}', Data='{event.data[:100]}...' ")
            else:
                print(f"Received event '{event.event}': ID={event.id}, Data='{event.data[:100]}...' ")
            message_count += 1
            # For demonstration, break after receiving 3 messages
            if message_count >= 3:
                break
except Exception as e:
    print(f"An error occurred: {e}")

view raw JSON →