Skip to main content

Python client library for the SuperOps GraphQL API with async support, type safety, and comprehensive error handling

Project description

py-superops

Python client library for the SuperOps GraphQL API.

Overview

This package provides a comprehensive Python SDK for interacting with the SuperOps GraphQL API, featuring async/await support, comprehensive error handling, rate limiting, and type safety.

Features

  • Async/await support for high-performance applications
  • Comprehensive error handling with custom exception hierarchy
  • Built-in rate limiting and retry logic
  • Type safety with full type hint support
  • Configuration management with environment variable support
  • Authentication handling with token validation
  • Connection pooling and resource management

Installation

pip install py-superops

Quick Start

Basic Usage

import asyncio
from py_superops import SuperOpsClient, SuperOpsConfig

async def main():
    # Create configuration
    config = SuperOpsConfig(
        api_key="your-api-key",
        base_url="https://api.superops.com/v1"
    )

    # Create and use the client
    async with SuperOpsClient(config) as client:
        # Test connection
        connection_info = await client.test_connection()
        print(f"Connected: {connection_info['connected']}")

        # Execute a query
        query = '''
        query GetClients {
            clients {
                id
                name
                email
            }
        }
        '''

        response = await client.execute_query(query)
        clients = response['data']['clients']

        for client in clients:
            print(f"Client: {client['name']} ({client['email']})")

if __name__ == "__main__":
    asyncio.run(main())

Configuration from Environment

import os
from py_superops import create_client

# Set environment variable
os.environ["SUPEROPS_API_KEY"] = "your-api-key"

# Create client from environment
client = create_client()

Advanced Configuration

from py_superops import SuperOpsConfig, SuperOpsClient

config = SuperOpsConfig(
    api_key="your-api-key",
    base_url="https://api.superops.com/v1",
    timeout=60.0,
    max_retries=5,
    rate_limit_per_minute=120,
    enable_caching=True,
    cache_ttl=600,
    debug=True
)

async with SuperOpsClient(config) as client:
    # Your code here
    pass

Configuration

The client can be configured through multiple methods:

  1. Direct instantiation
  2. Environment variables (prefixed with SUPEROPS_)
  3. Configuration files (JSON or YAML)

Environment Variables

  • SUPEROPS_API_KEY - Your SuperOps API key (required)
  • SUPEROPS_BASE_URL - API base URL (default: https://api.superops.com/v1)
  • SUPEROPS_TIMEOUT - Request timeout in seconds (default: 30.0)
  • SUPEROPS_MAX_RETRIES - Maximum request retries (default: 3)
  • SUPEROPS_RATE_LIMIT_PER_MINUTE - Rate limit (default: 60)
  • SUPEROPS_DEBUG - Enable debug mode (default: false)

Configuration File

# superops.yaml
api_key: "your-api-key"
base_url: "https://api.superops.com/v1"
timeout: 30.0
max_retries: 3
rate_limit_per_minute: 60
enable_caching: true
cache_ttl: 300
debug: false
from py_superops import SuperOpsConfig

config = SuperOpsConfig.from_file("superops.yaml")

Error Handling

The library provides a comprehensive exception hierarchy:

from py_superops import (
    SuperOpsError,
    SuperOpsAPIError,
    SuperOpsAuthenticationError,
    SuperOpsRateLimitError,
    SuperOpsNetworkError,
    SuperOpsValidationError,
)

try:
    response = await client.execute_query(query)
except SuperOpsAuthenticationError:
    print("Authentication failed - check your API key")
except SuperOpsRateLimitError as e:
    print(f"Rate limit exceeded - retry after {e.retry_after} seconds")
except SuperOpsAPIError as e:
    print(f"API error: {e.message} (status: {e.status_code})")
except SuperOpsNetworkError:
    print("Network error - check your connection")

GraphQL Operations

Queries

query = '''
query GetClients($limit: Int) {
    clients(limit: $limit) {
        id
        name
        email
        sites {
            id
            name
        }
    }
}
'''

variables = {"limit": 10}
response = await client.execute_query(query, variables=variables)

Mutations

mutation = '''
mutation CreateClient($input: ClientInput!) {
    createClient(input: $input) {
        id
        name
        email
    }
}
'''

variables = {
    "input": {
        "name": "New Client",
        "email": "client@example.com"
    }
}

response = await client.execute_mutation(mutation, variables=variables)

Development

Requirements

  • Python 3.8+
  • httpx
  • pydantic
  • pydantic-settings

Optional Dependencies

  • PyYAML (for YAML configuration files)

Testing

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run tests with coverage
pytest --cov=py_superops --cov-report=html

Code Quality

# Format code
black src/ tests/

# Sort imports
isort src/ tests/

# Type checking
mypy src/

# Linting
flake8 src/ tests/

API Documentation

SuperOpsClient

Main client class for interacting with the SuperOps API.

Methods

  • execute_query(query, variables=None, operation_name=None) - Execute a GraphQL query
  • execute_mutation(mutation, variables=None, operation_name=None) - Execute a GraphQL mutation
  • test_connection() - Test API connection and authentication
  • get_schema() - Get GraphQL schema information
  • close() - Close HTTP client connections

SuperOpsConfig

Configuration class for the SuperOps client.

Class Methods

  • from_env() - Load configuration from environment variables
  • from_file(path) - Load configuration from file

Methods

  • validate_config() - Validate current configuration
  • get_headers() - Get HTTP headers for requests
  • is_us_datacenter() - Check if using US datacenter
  • is_eu_datacenter() - Check if using EU datacenter

Convenience Functions

  • create_client(**kwargs) - Create client with minimal configuration
  • get_version() - Get package version
  • get_package_info() - Get package metadata

License

MIT License - see LICENSE file for details.

Support

For issues and questions:

Changelog

See CHANGELOG.md for version history and changes.

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

py_superops-0.2.9.tar.gz (235.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

py_superops-0.2.9-py3-none-any.whl (158.5 kB view details)

Uploaded Python 3

File details

Details for the file py_superops-0.2.9.tar.gz.

File metadata

  • Download URL: py_superops-0.2.9.tar.gz
  • Upload date:
  • Size: 235.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for py_superops-0.2.9.tar.gz
Algorithm Hash digest
SHA256 99468a008869e21961d975962e7d33341e67d48c8978a5e3ec3d8756e19e65fe
MD5 d3d89fae59be2e653dad36a93c859195
BLAKE2b-256 2b8a7b837ff7c4621af2205777c3b951b7b08e33129904d23f401d3e02027d0b

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_superops-0.2.9.tar.gz:

Publisher: release.yml on asachs01/py-superops

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file py_superops-0.2.9-py3-none-any.whl.

File metadata

  • Download URL: py_superops-0.2.9-py3-none-any.whl
  • Upload date:
  • Size: 158.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for py_superops-0.2.9-py3-none-any.whl
Algorithm Hash digest
SHA256 1831a5bca9e56f420982562279cdc5df8f59970a4321f8362ffa4a796d296c7f
MD5 3b14da57d0ed50fc6f218d386ffd3a16
BLAKE2b-256 4ae93ba73e06cbafff98e542e94216de6a1c2c32b6ba61e00e6ac894d4fe0095

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_superops-0.2.9-py3-none-any.whl:

Publisher: release.yml on asachs01/py-superops

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

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