Skip to main content

A package for connecting to AWS AppSync WebSocket API using graphql subscriptions

Project description

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!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

appsync_ws_client-0.1.0.tar.gz (3.7 kB view details)

Uploaded Source

Built Distribution

appsync_ws_client-0.1.0-py3-none-any.whl (3.6 kB view details)

Uploaded Python 3

File details

Details for the file appsync_ws_client-0.1.0.tar.gz.

File metadata

  • Download URL: appsync_ws_client-0.1.0.tar.gz
  • Upload date:
  • Size: 3.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.7

File hashes

Hashes for appsync_ws_client-0.1.0.tar.gz
Algorithm Hash digest
SHA256 efce3eece12a24e37d4918b417d8c4e12880f401eeaf89ba2e2bcf93e0d3b284
MD5 845795915cd9052b453021de58810619
BLAKE2b-256 627bcc6d474e0e363cb244a7a75f695b7cf3112a3b855918246e8377f8f5f97e

See more details on using hashes here.

File details

Details for the file appsync_ws_client-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for appsync_ws_client-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 57f88d19eb3e5b1c59ba7a715685aff9271b4268d4a3ccbfc6bc5135cdae02c3
MD5 b95ef600164e5d301eb469514a0466a7
BLAKE2b-256 2043c276f406e8b3de3103a9c45f1ac68d96781e43b3e63d6e5747d6db9c8a3f

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page