Skip to main content

Supermetrics client for Python.

PyPI version Documentation

Official Python client for Supermetrics

Features

  • Type-safe Python client generated from OpenAPI specification
  • Dual sync/async support via separate Client classes
  • Pydantic v2 models for request/response validation
  • Comprehensive API coverage: login links, logins, accounts, queries, DWH backfills, Connector Builder
  • Custom exception hierarchy with HTTP status code mapping
  • Resource-based API organization
  • API key, OAuth bearer token, and dynamic token provider authentication
  • Per-request authorization, header, and timeout overrides on a shared connection pool
  • with_raw_response access to HTTP status codes, headers, and raw payloads

Quick Start

Installation

pip install supermetrics

Basic Usage

from supermetrics import SupermetricsClient

# Initialize client
client = SupermetricsClient(api_key="your_api_key")

# Create login link for data source authentication
link = client.login_links.create(ds_id="GAWA", description="My Analytics Authentication")

# Get login details after user authenticates
login = client.logins.get(login_id=link.login_id)

# List available accounts
accounts = client.accounts.list(ds_id="GAWA", login_usernames=login.username)

# Execute query
result = client.queries.execute(
    ds_id="GAWA",
    ds_accounts=[accounts[0].account_id],
    fields=["Date", "Sessions", "Users"],
    start_date="2024-01-01",
    end_date="2024-01-07",
)

print(f"Retrieved {len(result.data)} rows")

Connector Builder

from supermetrics import SupermetricsClient

client = SupermetricsClient(api_key="your_api_key")

# List connectors
connectors = client.connector_builder.list(team_id=12345)

# Create a connector
created = client.connector_builder.create(
    team_id=12345, title="My Custom Connector", description="Fetches data from a custom API"
)
connector_id = created.connector_identifier

# Manage secrets
client.connector_builder_secrets.create(
    team_id=12345, connector_identifier=connector_id, secret_name="api_key", secret_value="sk-secret-value"
)

# View execution logs
logs = client.connector_builder_logs.list(team_id=12345, connector_identifier=connector_id)

Data Warehouse Backfills

from supermetrics import SupermetricsClient

# Initialize client
client = SupermetricsClient(api_key="your_api_key")

# Create a backfill for historical data
backfill = client.backfills.create(team_id=12345, transfer_id=456789, range_start="2024-01-01", range_end="2024-01-31")

print(f"Backfill created: {backfill.transfer_backfill_id}")
print(f"Status: {backfill.status}")

# Get the latest backfill for a transfer
latest = client.backfills.get_latest(team_id=12345, transfer_id=456789)
print(f"Latest backfill status: {latest.status}")
print(f"Progress: {latest.transfer_runs_completed}/{latest.transfer_runs_total}")

# List all incomplete backfills for a team
backfills = client.backfills.list_incomplete(team_id=12345)
for bf in backfills:
    print(f"Backfill {bf.transfer_backfill_id}: {bf.status}")

# Cancel a backfill
cancelled = client.backfills.cancel(team_id=12345, backfill_id=67890)
print(f"Backfill cancelled: {cancelled.status}")

Authentication

The client accepts exactly one of api_key, bearer_token, or token_provider:

from supermetrics import SupermetricsAsyncClient, SupermetricsClient

# Static API key
client = SupermetricsClient(api_key="api_live_abc123")

# OAuth access token
client = SupermetricsClient(bearer_token="otok_abc123")


# Dynamic provider, re-evaluated on every request so short-lived tokens can be
# refreshed without discarding the connection pool
async def get_valid_token() -> str:
    return await oauth_service.get_access_token(team_id=123)


client = SupermetricsAsyncClient(token_provider=get_valid_token)

Every resource method takes per-request auth_token, headers, and timeout overrides, so one shared client can serve concurrent callers that each bring their own credential and tracing context:

sync_client = SupermetricsClient(api_key="api_live_abc123")

login = sync_client.logins.get(
    "login_abc123",
    auth_token="otok_this_caller",
    headers={"X-Span-Id": "a8f3b2c9", "Idempotency-Key": "req-42"},
    timeout=120.0,
)

Use with_raw_response when you need the HTTP status, headers, or raw payload alongside the parsed model:

response = sync_client.with_raw_response.logins.get("login_abc123")
print(response.status_code, response.span_id, response.retry_after)
print(response.data.username)

See Authentication & Transport for the full guide.

Examples

See the examples/ directory for complete working examples:

  • complete_flow.py - Full sync workflow from authentication to query execution
  • async_flow.py - Async version of complete workflow
  • connector_builder_flow.py - Connector Builder end-to-end operations (supports --base-url for local dev)

See examples/README.md for setup and running instructions.

Error Handling

The SDK provides specific exception types for different error scenarios:

from supermetrics import (
    APIError,
    NetworkError,
    SupermetricsAuthError,
    SupermetricsNotFoundError,
    SupermetricsRateLimitError,
    SupermetricsValidationError,
    SupermetricsClient,
)

client = SupermetricsClient(api_key="your_key")

try:
    link = client.login_links.create(ds_id="GAWA", description="Test")
except SupermetricsAuthError as e:
    # e.error_code carries the upstream OAuth code, e.g. ACCESS_TOKEN_INVALID
    print(f"Credential rejected ({e.error_code}): {e.message}")
except SupermetricsValidationError as e:
    print(f"Invalid parameters: {e.message}")
except SupermetricsNotFoundError as e:
    print(f"Not found: {e.message}")
except SupermetricsRateLimitError as e:
    print(f"Throttled; retry after {e.retry_after}s")
except APIError as e:
    # Any other HTTP error. Carries status_code, headers, error_code and details.
    print(f"API error {e.status_code}: {e.message}")
except NetworkError as e:
    print(f"Network error: {e.message}")

AuthenticationError and ValidationError remain available as aliases of SupermetricsAuthError and SupermetricsValidationError, and every HTTP error is a subclass of APIError.

Documentation

OpenAPI Client Regeneration

The SDK client is auto-generated from the Supermetrics OpenAPI specification.

Source Specifications

  • Location: openapi-specs/ directory (contains openapi-data.yaml, openapi-managment.yaml, openapi-team.yaml, openapi-connector-builder.yaml)
  • Merged Spec: openapi-spec.yaml (project root) - filtered, patched, and merged from source specs
  • Configuration: scripts/references/sdk-endpoint-filters.yaml - controls which endpoints are included and applies patches/customizations
  • Documentation: See scripts/README.md for detailed patch system documentation

SDK Endpoint Filtering and Customization

The SDK uses a configuration-driven process to create a focused, customizable client from multiple OpenAPI specifications.

scripts/references/sdk-endpoint-filters.yaml - Endpoint Configuration

This YAML file defines which API endpoints to include in the SDK and allows you to apply patches/customizations to both endpoints and shared components.

Key Features:

  • Endpoint Filtering: Include only the endpoints your application needs
  • Endpoint Patches: Customize individual endpoint definitions (descriptions, parameters, responses, etc.)
  • Component Patches: Apply surgical modifications to shared schemas, responses, and other components
  • Merge & Replace Strategies: Deep merge or complete replacement of OpenAPI sections

Basic Example:

endpoints:
  - method: GET
    path: /ds/logins

  - method: GET
    path: /query/data/json

component_patches:
  schemas:
    DataResponse:
      merge:
        properties:
          meta:
            properties:
              result:
                properties:
                  cache_time:
                    nullable: true

For detailed documentation on the configuration format, patch strategies, and comprehensive examples, see scripts/README.md.

scripts/filter_openapi_spec.py - Specification Filter, Patcher, and Merger

This Python script processes multiple OpenAPI specifications, applies customizations, and creates a single openapi-spec.yaml file.

What it does:

  1. Reads configuration from scripts/references/sdk-endpoint-filters.yaml
  2. Scans and loads all .yaml/.yml files from openapi-specs/ directory
  3. Filters endpoints based on configuration
  4. Applies endpoint patches (merge/replace operations)
  5. Collects all referenced components via $ref traversal (dependency resolution)
  6. Resolves external file references
  7. Applies component patches to shared schemas, responses, etc.
  8. Detects and fails on duplicate METHOD|PATH across specs
  9. Merges everything into single specification
  10. Validates all requested endpoints were found

Usage:

python scripts/filter_openapi_spec.py

Configuration:

  • Input: openapi-specs/*.yaml and scripts/references/sdk-endpoint-filters.yaml
  • Output: openapi-spec.yaml

Exit codes:

  • 0 - Success
  • 1 - Error (missing files, duplicates, or validation failure)

For detailed documentation on patch strategies, troubleshooting, and examples, see scripts/README.md.

How to Regenerate

Full Regeneration (recommended):

# 1. Update source specs in openapi-specs/ if needed
# 2. Update scripts/references/sdk-endpoint-filters.yaml to add/remove endpoints or apply patches
# 3. Run filter script to regenerate merged spec
python scripts/filter_openapi_spec.py

# 4. Regenerate SDK from merged spec
./scripts/regenerate_client.sh

Quick Regeneration (if openapi-spec.yaml unchanged):

./scripts/regenerate_client.sh

When to Regenerate

  • Monthly (or when Supermetrics API changes)
  • After updating source specs in openapi-specs/
  • After modifying scripts/references/sdk-endpoint-filters.yaml (adding/removing endpoints or changing patches)

Adding/Removing Endpoints or Applying Patches

  1. Edit scripts/references/sdk-endpoint-filters.yaml:
    • Add/remove endpoints in the endpoints list
    • Add/modify patches in component_patches or endpoint-level patches
  2. Run python scripts/filter_openapi_spec.py to regenerate the merged spec
  3. Run ./scripts/regenerate_client.sh to regenerate the SDK client

See scripts/README.md for detailed documentation on:

  • Configuration file format
  • Endpoint and component patch strategies
  • Comprehensive examples
  • Troubleshooting guide

Note: The adapter pattern (implemented in Story 1.3+) protects users from breaking changes during regeneration

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines on how to contribute, run tests, and deploy releases.

Note: Every pull request must include an update to HISTORY.md describing the change under the relevant version section.

Credits

This package was created with Cookiecutter and the audreyfeldroy/cookiecutter-pypackage project template.

Download files

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

Source Distribution

supermetrics-0.4.0.tar.gz (983.2 kB view details)

Uploaded Source

Built Distribution

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

supermetrics-0.4.0-py3-none-any.whl (436.9 kB view details)

Uploaded Python 3

File details

Details for the file supermetrics-0.4.0.tar.gz.

File metadata

  • Download URL: supermetrics-0.4.0.tar.gz
  • Upload date:
  • Size: 983.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.12.5 {"installer":{"name":"uv","version":"0.12.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for supermetrics-0.4.0.tar.gz
Algorithm Hash digest
SHA256 8392d4c3f89aaf311f0400781d9f932b50fcd07237731bb3c477225100e328bf
MD5 fb06ff95877b708ed0a7749c900d87a9
BLAKE2b-256 ba7faba8505a564aac4c95b4761381d93115d47413ee54fabf9cd217f156f548

See more details on using hashes here.

File details

Details for the file supermetrics-0.4.0-py3-none-any.whl.

File metadata

  • Download URL: supermetrics-0.4.0-py3-none-any.whl
  • Upload date:
  • Size: 436.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.12.5 {"installer":{"name":"uv","version":"0.12.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for supermetrics-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d1677e1a5f48ac60e111962b82eee7a0117f84487fc376fbc93adf061afef3aa
MD5 386bb56890810118dd63b0226cda4ac3
BLAKE2b-256 fe2a04b9710d47068f2ba979876c58a6eddd9db24dd904503e3ba36504ef187c

See more details on using hashes here.

Release history Release notifications | RSS feed

0.5.1

2 files

0.5.0

2 files

This release

0.4.0 This release

2 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