Skip to main content

AWS AppSync WebSocket Client

A Python client for subscribing to AWS AppSync GraphQL APIs via WebSockets. This package allows you to connect to the AWS AppSync WebSocket API, handle GraphQL subscriptions, and manage reconnections and retries seamlessly.

Features

  • GraphQL Subscriptions: Easily subscribe to GraphQL queries over WebSockets.
  • Automatic Reconnection: Handles reconnection attempts in case of dropped WebSocket connections.
  • Thread-safe: Manages multiple subscriptions with thread-safe operations.
  • Callback Handling: Provides a way to specify callback functions that process subscription data.

Installation

Install the package via pip:

pip install appsync-ws-client

Usage

1. Initialize the Client

To use the client, provide the WebSocket URL and an authentication function that returns the necessary headers.

from appsync_ws_client.client import GraphQLWebSocketClient

def get_auth_headers():
    return {
        "host": "xxx.appsync-api.<region>.amazonaws.com",
        "Authorization": "<ACCESS_TOKEN>",
    }

url = "wss://<your-appsync-endpoint>"
client = GraphQLWebSocketClient(url, auth_function=get_auth_headers)
client.connect()

2. Subscribing to a GraphQL Query

You can subscribe to a GraphQL query using the subscribe method. The subscription requires a GraphQL query, variables (if any), and a callback function to handle the subscription data.

query = '''
subscription OnPriceUpdate {
    onPriceUpdate {
        id
        price
        timestamp
    }
}
'''

def handle_subscription_data(data):
    print("Received subscription data:", data)

subscription_id = client.subscribe(query, variables={}, callback=handle_subscription_data)

3. Unsubscribing

To unsubscribe from a subscription, use the unsubscribe method with the subscription_id that was returned when you subscribed.

client.unsubscribe(subscription_id)

4. Closing the Connection

Ensure you close the WebSocket connection properly when done:

client.close()

5. Handling Reconnection

The client automatically attempts to reconnect when a WebSocket connection drops. You can control the number of retry attempts by passing max_retries to the client. For example:

client = GraphQLWebSocketClient(url, auth_function=get_auth_headers, max_retries=10)
client.connect()

Error Handling

The package will raise the following errors:

  • TimeoutError: Raised when the connection acknowledgment times out.
  • MaxRetriesExceeded: Raised when the maximum number of reconnection attempts is exceeded.

You can also handle WebSocket errors using the client’s internal logging.

Logging

Logging is built in to help monitor the WebSocket connection and subscription process. Make sure to configure logging in your application as necessary:

import logging

logging.basicConfig(level=logging.INFO)

Example

Here is a full example of setting up the client and subscribing to a GraphQL subscription:

import time
import logging
from appsync_ws_client.client import GraphQLWebSocketClient

logging.basicConfig(level=logging.INFO)

def get_auth_headers():
    return {
        "host": "xxx.appsync-api.<region>.amazonaws.com",
        "Authorization": "<ACCESS_TOKEN>",
    }

url = "wss://<your-appsync-endpoint>"
client = GraphQLWebSocketClient(url, auth_function=get_auth_headers)
client.connect()

query = '''
subscription OnPriceUpdate {
    onPriceUpdate {
        id
        price
        timestamp
    }
}
'''

def handle_subscription_data(data):
    print("Received subscription data:", data)

subscription_id = client.subscribe(query, variables={}, callback=handle_subscription_data)

try:
    while True:
        time.sleep(1)  # Keeps the main program alive
except KeyboardInterrupt:
    print("Closing WebSocket and shutting down...")
    client.close()


# Later, if you want to unsubscribe
client.unsubscribe(subscription_id)

# Always remember to close the connection when done
client.close()

License

This package is licensed under the MIT License. See the LICENSE file for more details.

Contributing

Feel free to open an issue or submit a pull request if you want to contribute!

Metadata

Release files for appsync-ws-client 0.1.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for appsync-ws-client 0.1.3
File Size Uploaded
appsync_ws_client-0.1.3.tar.gz 7.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for appsync-ws-client 0.1.3
File Interpreter ABI Platform
appsync_ws_client-0.1.3-py3-none-any.whl Python 3 none any Details

Total release size: 16.4 kB

Release files / appsync_ws_client-0.1.3.tar.gz

Download URL appsync_ws_client-0.1.3.tar.gz
Size 7.6 kB
Tags Source
SHA-256 checksum
How to use checksums
f0dded477dcc0ada5f4298babb3da4fd890e979e84e385373ae8c94c3164ca2f
BLAKE2b-256 checksum
How to use checksums
4dfbe3f8f8526983d03d64fdb157c9c5ccd167adc2b80ef2790ed0b2fb554b3b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.1 CPython/3.12.7

Release files / appsync_ws_client-0.1.3-py3-none-any.whl

Download URL appsync_ws_client-0.1.3-py3-none-any.whl
Size 8.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e3099c7ab83425ec5dc81f0aec06ab0d4ad0049150c898b063c5e15747672484
BLAKE2b-256 checksum
How to use checksums
34d93a203dbf17ae6eb23902a65e55b418ed4c4d6647596718e5972e549c2291
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.1 CPython/3.12.7

Release history Release notifications | RSS feed

This release

0.1.3 This release

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page