Event and State WebSocket API - Python

This sample demonstrates how to access the Events and State WebSocket API through the API Gateway from a Python application.

Event and State WebSocket API - Python

Prerequisites

Run

python main.py

The sample demonstrates

Subscription options

The basic subscription filter is defined in the top of main.py and can be modified for different sources, a source types and/or an event types. A few ids for some common events types can be found in event_type.py.

To define a more advanced subscription with multiple filters (potentially including ‘exclude’ filters), see the create_subscription() method in ess_api.py.

Simplified example

gateway_ws_uri = "wss://localhost/api/ws/events/v1/"
access_token = "<insert token>"
session_id = ""
last_event_id = ""
subscription_filters =  [
    {
        "modifier": "include",
        "resourceTypes": [ "outputs" ],
        "sourceIds": [ "*" ],
        "eventTypes": [ "*" ]
    }
]
while True:
    try:
        async with connect(gateway_ws_uri, extra_headers={"Authorization": f"Bearer {access_token}"}) as web_socket:
            # Start or resume session
            session = await ess_api.start_session(web_socket, session_id, last_event_id)
            if session["status"] == 201:
                # Create subscription
                subscription = await ess_api.create_subscription(web_socket, subscription_filters)
                # Save session id once subscription is successfully created
                session_id = session["sessionId"]
                # Get state (if needed)
                state = await ess_api.get_state(web_socket)
                # TODO: Process state
            # Receive events loop
            while True:
                events = await ess_api.receive_events(web_socket)
                last_event_id = events["events"][-1]["id"]
                
                # TODO: Process events
    except:
        # TODO: Exception handling
        # Sleep 1 second before reconnecting
        await asyncio.sleep(1)
        print("Reconnecting...")

Using

Visual Studio Python project