### Run Example Script Source: https://github.com/metronome-industries/metronome-python/blob/main/CONTRIBUTING.md Execute an example script located in the 'examples/' directory against your API after making it executable. ```sh chmod +x examples/.py # run the example against your api ./examples/.py ``` -------------------------------- ### Add and Make Example Executable Source: https://github.com/metronome-industries/metronome-python/blob/main/CONTRIBUTING.md Add a new example script to the 'examples/' directory and make it executable. The script is intended to be run with Python provisioned by Rye. ```python # add an example to examples/.py #!/usr/bin/env -S rye run python … ``` -------------------------------- ### Install from Wheel File Source: https://github.com/metronome-industries/metronome-python/blob/main/CONTRIBUTING.md Install the Metronome Python package efficiently using a pre-built wheel file located in the 'dist/' directory. ```sh pip install ./path-to-wheel-file.whl ``` -------------------------------- ### Tiered Pricing Configuration Example Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/types.md Example of how to configure tiered pricing for a rate. Note that the last tier can omit 'last_unit' to signify unlimited volume. ```python rate_config = { "tiers": [ {"first_unit": 0, "last_unit": 100, "unit_price": 1.0}, {"first_unit": 100, "last_unit": 1000, "unit_price": 0.80}, {"first_unit": 1000, "unit_price": 0.50}, ] } ``` -------------------------------- ### Install Metronome Python SDK Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/README.md Install the Metronome Python SDK using pip. Ensure you have Python and pip installed. ```bash pip install metronome-sdk ``` -------------------------------- ### Install from Git Source: https://github.com/metronome-industries/metronome-python/blob/main/CONTRIBUTING.md Install the Metronome Python package directly from its Git repository using pip. ```sh pip install git+ssh://git@github.com/Metronome-Industries/metronome-python.git ``` -------------------------------- ### Install Metronome SDK with aiohttp support Source: https://github.com/metronome-industries/metronome-python/blob/main/README.md Install the Metronome SDK with aiohttp support for improved concurrency performance. ```sh pip install metronome-sdk[aiohttp] ``` -------------------------------- ### Set up Mock Server Source: https://github.com/metronome-industries/metronome-python/blob/main/CONTRIBUTING.md Start a mock server against the OpenAPI spec to run tests. This is a prerequisite for most tests. ```sh ./scripts/mock ``` -------------------------------- ### Basic AsyncMetronome Usage Example Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/client.md Demonstrates how to initialize and use the `AsyncMetronome` client within an asynchronous function to list customers. ```python import asyncio from metronome import AsyncMetronome async def main(): async with AsyncMetronome() as client: customers = await client.v1.customers.list() print(customers) asyncio.run(main()) ``` -------------------------------- ### Create Customer with Billing Configuration Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/types.md Example of creating a new customer and specifying their billing provider and delivery method using Stripe. ```python customer = client.v1.customers.create( name="Acme", billing_config={ "billing_provider": "stripe", "delivery_method": "direct_to_billing_provider", "stripe": { "customer_id": "cus_123", }, }, ) ``` -------------------------------- ### Filtered Pagination Example Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/pagination.md Illustrates how to apply filters to list endpoints to retrieve specific subsets of data. This example filters contracts by a customer ID. ```python # Contracts for a specific customer contracts = client.v1.contracts.list( customer_id="cust_123", ) for contract in contracts: print(contract.name) ``` -------------------------------- ### Full Configuration Example Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/configuration.md Demonstrates a comprehensive Metronome client initialization, combining environment variable lookups with explicit parameter settings for authentication, base URL, timeouts, retries, custom headers, and HTTP client configuration including proxy and SSL verification. ```python import os import httpx from metronome import Metronome, DefaultHttpxClient client = Metronome( bearer_token=os.environ.get("METRONOME_BEARER_TOKEN"), webhook_secret=os.environ.get("METRONOME_WEBHOOK_SECRET"), base_url=os.environ.get("METRONOME_BASE_URL", "https://api.metronome.com"), timeout=httpx.Timeout(60.0, read=10.0), max_retries=3, default_headers={ "X-App-Version": "1.0.0", }, http_client=DefaultHttpxClient( proxy=os.environ.get("HTTP_PROXY"), verify=os.environ.get("VERIFY_SSL", "true").lower() == "true", ), ) ``` -------------------------------- ### Sync Dependencies with Rye Source: https://github.com/metronome-industries/metronome-python/blob/main/CONTRIBUTING.md Install dependencies using Rye after manual installation. Ensures all features are synced. ```sh rye sync --all-features ``` -------------------------------- ### DefaultAioHttpClient Initialization Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/configuration.md Initializes the default aiohttp-based asynchronous HTTP client. Requires the 'aiohttp' extra to be installed. ```python from metronome import DefaultAioHttpClient http_client = DefaultAioHttpClient() Requires: `pip install metronome-sdk[aiohttp]` ``` -------------------------------- ### Manual Pagination Example Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/v1-resources.md Demonstrates manual iteration over paginated results from a list method. Use this when you need to process all items across multiple pages. ```python # Manual iteration for item in client.v1.customers.list(): print(item.name) # Check pagination info first_page = client.v1.customers.list() if first_page.has_next_page(): next_page = first_page.get_next_page() print(f"Next cursor: {first_page.next_page}") ``` -------------------------------- ### Install Dependencies with Pip Source: https://github.com/metronome-industries/metronome-python/blob/main/CONTRIBUTING.md Install development dependencies using pip if you choose not to install Rye. Ensure the Python version matches .python-version. ```sh pip install -r requirements-dev.lock ``` -------------------------------- ### Create a Contract Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/00-START-HERE.md Create a new contract for a customer. Specify the customer ID, start date, rate card ID, and commit details. ```python from datetime import datetime contract = client.v1.contracts.create( customer_id="cust_456", starting_at=datetime(2024, 1, 1), rate_card_id="rate_789", commits=[{"amount": 50000.0, "invoice_schedule": "ADVANCE"}], ) ``` -------------------------------- ### Get Plan Details v1 Source: https://github.com/metronome-industries/metronome-python/blob/main/api.md Fetches detailed information for a specific plan using its ID. ```python client.v1.plans.get_details(*, plan_id) -> PlanGetDetailsResponse ``` -------------------------------- ### Example: Accessing Headers Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/advanced-features.md Illustrates how to access specific HTTP headers from the raw response object, such as `X-Request-ID` and `X-RateLimit-Remaining`. ```APIDOC ## Example: Accessing Headers ```python response = client.with_raw_response.v1.customers.retrieve("id") # Get specific headers request_id = response.headers.get('X-Request-ID') rate_limit_remaining = response.headers.get('X-RateLimit-Remaining') print(f"Request ID: {request_id}") print(f"Rate limit remaining: {rate_limit_remaining}") ``` ``` -------------------------------- ### Create a New Contract Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/contracts-api.md Use this method to create a new contract for a customer, specifying details like start date, pricing, discounts, and subscriptions. It supports various configurations for commitments, credits, and billing providers. ```python from datetime import datetime contract = client.v1.contracts.create( customer_id="cust_123", starting_at=datetime(2024, 1, 1), ending_before=datetime(2024, 12, 31), # Fixed-term contract name="Enterprise 2024", rate_card_id="rate_456", commits=[ { "amount": 50000.0, "invoice_schedule": "ADVANCE", } ], discounts=[ { "percentage": 10.0, "applicable_product_ids": ["product_1"], } ], subscriptions=[ { "product_id": "product_2", "quantity": 100, "price": 10.0, } ], billing_provider_configuration={ "billing_provider": "stripe", "delivery_method": "direct_to_billing_provider", "stripe": { "customer_id": "cus_abc123", }, }, ) print(f"Contract created: {contract.data.id}") ``` -------------------------------- ### Create a Contract with Metronome Python SDK Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/README.md This code demonstrates how to create a new contract, linking it to a customer, defining its start and end dates, associating it with a rate card, and specifying commit details for invoicing. ```python from datetime import datetime contract = client.v1.contracts.create( customer_id="cust_123", starting_at=datetime(2024, 1, 1), ending_before=datetime(2024, 12, 31), rate_card_id="rate_456", commits=[ { "amount": 50000.0, "invoice_schedule": "ADVANCE", } ], ) ``` -------------------------------- ### Create Contract Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/contracts-api.md Creates a new contract for a customer, specifying details like start date, pricing, commitments, and subscriptions. ```APIDOC ## create ### Description Create a new contract for a customer. ### Method `client.v1.contracts.create` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - `customer_id` (str) - Required - Metronome customer ID - `starting_at` (str | datetime) - Required - Contract start date (ISO 8601 or Python datetime) - `ending_before` (str | datetime | Omit) - Optional - Contract end date. Omit for perpetual contracts. - `rate_card_id` (str | Omit) - Optional - ID of the rate card defining usage-based pricing - `rate_card_alias` (str | Omit) - Optional - Alias of the rate card (alternative to `rate_card_id`) - `name` (str | Omit) - Optional - Contract display name - `commits` (Iterable[Commit] | Omit) - Optional - Prepaid/postpaid spending commitments - `recurring_commits` (Iterable[RecurringCommit] | Omit) - Optional - Recurring commitments (monthly, quarterly, etc.) - `credits` (Iterable[Credit] | Omit) - Optional - Free usage allowances - `discounts` (Iterable[Discount] | Omit) - Optional - Pricing discounts (percentage, fixed, or tiered) - `overrides` (Iterable[Override] | Omit) - Optional - Time-bounded custom pricing and access rules - `subscriptions` (Iterable[Subscription] | Omit) - Optional - Recurring subscription charges (seats, monthly) - `billing_provider_configuration` (BillingProviderConfiguration | Omit) - Optional - Where and how invoices are delivered - `custom_fields` (Dict[str, str] | Omit) - Optional - Custom metadata key-value pairs ### Returns **`ContractCreateResponse`** — Created contract with full details ### Raises - **`BadRequestError`** — Missing required fields or invalid values - **`UnprocessableEntityError`** — Business logic validation failed (e.g., end date before start date) - **`APIStatusError`** — Other API errors ### Example ```python from datetime import datetime contract = client.v1.contracts.create( customer_id="cust_123", starting_at=datetime(2024, 1, 1), ending_before=datetime(2024, 12, 31), # Fixed-term contract name="Enterprise 2024", rate_card_id="rate_456", commits=[ { "amount": 50000.0, "invoice_schedule": "ADVANCE", } ], discounts=[ { "percentage": 10.0, "applicable_product_ids": ["product_1"], } ], subscriptions=[ { "product_id": "product_2", "quantity": 100, "price": 10.0, } ], billing_provider_configuration={ "billing_provider": "stripe", "delivery_method": "direct_to_billing_provider", "stripe": { "customer_id": "cus_abc123", }, }, ) print(f"Contract created: {contract.data.id}") ``` ``` -------------------------------- ### Create a New Contract Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/v1-resources.md Use this method to create a new customer contract. It requires a customer ID and a starting date, and accepts optional parameters for rate cards, billing configurations, commits, and discounts. ```python from datetime import datetime contract = client.v1.contracts.create( customer_id="customer_id", starting_at=datetime.fromisoformat("2024-01-01T00:00:00.000"), name="Enterprise Plan", rate_card_id="rate_card_123", billing_provider_configuration={ "billing_provider": "stripe", "delivery_method": "direct_to_billing_provider", }, commits=[ { "netsuite_commit_id": "commit_123", "amount": 10000.0, "invoice_schedule": "ADVANCE", } ], discounts=[ { "percentage": 10.0, "applicable_product_ids": ["product_1"], } ], ) ``` -------------------------------- ### AsyncMetronome with aiohttp Backend Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/client.md Configures `AsyncMetronome` to use `aiohttp` as the HTTP client backend for potentially improved concurrency performance. Ensure `metronome-sdk[aiohttp]` is installed. ```python from metronome import DefaultAioHttpClient, AsyncMetronome async with AsyncMetronome( http_client=DefaultAioHttpClient(), ) as client: await client.v1.usage.ingest(...) ``` -------------------------------- ### Get Installed SDK Version (Python) Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/client.md Retrieves the currently installed version of the Metronome SDK. Requires Python 3.9+. ```python import metronome print(metronome.__version__) ``` -------------------------------- ### AsyncMetronome Initialization and Usage Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/client.md Demonstrates how to initialize and use the `AsyncMetronome` client, including making a sample API call to list customers. ```APIDOC ## AsyncMetronome Initialization and Usage ### Description This snippet shows how to instantiate the `AsyncMetronome` client and perform an asynchronous API operation, such as listing customers. ### Method `AsyncMetronome` constructor and `client.v1.customers.list()` method. ### Parameters (Constructor) - `bearer_token` (str | None) - Optional: Authentication token. - `webhook_secret` (str | None) - Optional: Secret for webhook verification. - `base_url` (str | httpx.URL | None) - Optional: Base URL for API requests. - `timeout` (float | Timeout | None | NotGiven) - Optional: Request timeout settings. - `max_retries` (int) - Optional: Maximum number of retries for failed requests (default: `DEFAULT_MAX_RETRIES`). - `default_headers` (Mapping[str, str] | None) - Optional: Default headers to include in all requests. - `default_query` (Mapping[str, object] | None) - Optional: Default query parameters for all requests. - `http_client` (httpx.AsyncClient | None) - Optional: Custom asynchronous HTTP client. - `_strict_response_validation` (bool) - Optional: Whether to strictly validate API responses (default: False). ### Usage Example ```python import asyncio from metronome import AsyncMetronome async def main(): async with AsyncMetronome() as client: customers = await client.v1.customers.list() print(customers) asyncio.run(main()) ``` ``` -------------------------------- ### Client Initialization Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/MANIFEST.txt Demonstrates how to initialize the Metronome and AsyncMetronome clients, including authentication and configuration options. ```APIDOC ## Client Initialization ### Description Initialize the Metronome or AsyncMetronome client with optional authentication and HTTP configuration. ### Usage ```python from metronome import Metronome, AsyncMetronome # Synchronous client client = Metronome(bearer_token="YOUR_BEARER_TOKEN") # Asynchronous client async_client = AsyncMetronome(bearer_token="YOUR_BEARER_TOKEN") # With custom HTTP configuration (e.g., timeout) from metronome.http import HTTPClient custom_http_client = HTTPClient(timeout=30.0) client_with_config = Metronome(bearer_token="YOUR_BEARER_TOKEN", http_client=custom_http_client) ``` ### Parameters - **bearer_token** (str) - Required - The authentication token for the Metronome API. - **http_client** (HTTPClient, optional) - An instance of HTTPClient for custom configuration (e.g., timeout, custom headers). ``` -------------------------------- ### Creating Customers with TypedDict Parameters Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/types.md Shows how to use TypedDict for request parameters, enabling IDE autocompletion and validation during customer creation. ```python from metronome import Metronome from metronome.types.v1 import customer_create_params client = Metronome() # IDE provides full autocomplete and validation customer = client.v1.customers.create( name="Acme Corp", billing_config={ "billing_provider": "stripe", "delivery_method": "direct_to_billing_provider", "stripe": { "customer_id": "cus_123", }, }, ) ``` -------------------------------- ### Create a Free Trial Contract Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/contracts-api.md Illustrates the creation of a free trial contract with a large credit amount that effectively makes it unlimited for a specified duration. ```python from datetime import datetime, timedelta trial_end = datetime.now() + timedelta(days=30) contract = client.v1.contracts.create( customer_id="trial_cust", starting_at=datetime.now(), ending_before=trial_end, rate_card_id="standard_rate_card", credits=[ { "amount": 999999999.0, # Effectively unlimited "expires_at": trial_end.isoformat(), } ], ) ``` -------------------------------- ### Get Raw HTTP Response Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/client.md Use the `with_raw_response` prefix to retrieve the complete HTTP response, including headers and status code. Call `.parse()` on the response object to get the deserialized model. ```python response = client.with_raw_response.v1.contracts.create(...) print(response.headers.get('X-My-Header')) contract = response.parse() # Get the parsed model ``` -------------------------------- ### Get Net Balance for Contract Source: https://github.com/metronome-industries/metronome-python/blob/main/api.md Retrieves the net balance for a contract. ```APIDOC ## POST /v1/contracts/customerBalances/getNetBalance ### Description Retrieves the net balance for a contract. ### Method POST ### Endpoint /v1/contracts/customerBalances/getNetBalance ### Parameters #### Request Body - **params** (object) - Required - Parameters for retrieving the net balance. ``` -------------------------------- ### Create Customer Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/README.md Demonstrates how to create a new customer with specified details and billing configuration. ```APIDOC ## Create Customer ### Description Creates a new customer with their associated billing configuration. ### Method `client.v1.customers.create()` ### Parameters - **name** (string) - Required - The name of the customer. - **external_id** (string) - Required - An external identifier for the customer. - **ingest_aliases** (list of strings) - Optional - Aliases for ingesting usage data. - **billing_config** (object) - Required - Configuration for billing. - **billing_provider** (string) - Required - The billing provider (e.g., "stripe"). - **delivery_method** (string) - Required - How billing information is delivered. - **stripe** (object) - Optional - Stripe-specific configuration. - **customer_id** (string) - Required - The Stripe customer ID. ### Request Example ```python customer = client.v1.customers.create( name="Acme Corporation", external_id="ext_123", ingest_aliases=["acme", "acme-corp"], billing_config={ "billing_provider": "stripe", "delivery_method": "direct_to_billing_provider", "stripe": {"customer_id": "cus_abc123"}, }, ) ``` ``` -------------------------------- ### Get Subscription Seats History for Contract Source: https://github.com/metronome-industries/metronome-python/blob/main/api.md Retrieves the subscription seats history for a contract. ```APIDOC ## POST /v1/contracts/getSubscriptionSeatsHistory ### Description Retrieves the subscription seats history for a contract. ### Method POST ### Endpoint /v1/contracts/getSubscriptionSeatsHistory ### Parameters #### Request Body - **params** (object) - Required - Parameters for retrieving the subscription seats history. ``` -------------------------------- ### Create Product Source: https://github.com/metronome-industries/metronome-python/blob/main/api.md Creates a new product. ```APIDOC ## POST /v1/contract-pricing/products/create ### Description Creates a new product. ### Method POST ### Endpoint /v1/contract-pricing/products/create ### Parameters #### Request Body - **params** (object) - Required - Parameters for creating a product. ``` -------------------------------- ### get /v1/customers Source: https://github.com/metronome-industries/metronome-python/blob/main/api.md Lists all customers. Supports filtering and pagination using provided parameters. ```APIDOC ## GET /v1/customers ### Description Lists all customers with support for filtering and pagination. ### Method GET ### Endpoint /v1/customers ### Parameters #### Query Parameters - **params** (CustomerListParams) - Optional - Parameters for filtering and pagination. ### Response #### Success Response (200) - **SyncCursorPage[CustomerDetail]** - A paginated list of customer details. ``` -------------------------------- ### Get Plan Details Source: https://github.com/metronome-industries/metronome-python/blob/main/api.md Retrieves detailed information for a specific plan identified by its ID. ```APIDOC ## GET /v1/planDetails/{plan_id} ### Description Retrieves detailed information for a specific plan. ### Method GET ### Endpoint /v1/planDetails/{plan_id} ### Parameters #### Path Parameters - **plan_id** (string) - Required - The unique identifier of the plan. ### Response #### Success Response (200) - **PlanGetDetailsResponse** (object) - The detailed information for the plan. ``` -------------------------------- ### Create an Enterprise Contract Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/contracts-api.md Demonstrates creating an enterprise-level contract with specific commit amounts, invoice schedules, and rollover options. Includes setting up rate cards and overrides for discounts. ```python from datetime import datetime contract = client.v1.contracts.create( customer_id="enterprise_cust", starting_at=datetime(2024, 1, 1), ending_before=datetime(2025, 1, 1), name="Enterprise Annual", rate_card_id="enterprise_rate_card", commits=[ { "amount": 100000.0, "invoice_schedule": "ADVANCE", "rollover_fraction": 0.25, # 25% of unused rolls over } ], overrides=[ { "starting_at": "2024-06-01", "ending_before": "2024-08-31", "rate_overrides": [ { "billable_metric_id": "metric_123", "unit_price": 0.05, # 50% discount } ], } ], ) ``` -------------------------------- ### Get Net Balance Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/contracts-api.md Retrieves the total prepaid amount remaining for a specific contract. ```APIDOC ## get_net_balance ### Description Get the net balance (total prepaid amount remaining) for a contract. ### Method Signature ```python def get_net_balance(self, contract_id: str, **options) -> ContractGetNetBalanceResponse: ... ``` ### Parameters * **contract_id** (str) - Required - The ID of the contract. ### Returns * **ContractGetNetBalanceResponse** - An object containing the net balance information. ### Example ```python balance_info = client.v1.contracts.get_net_balance("contract_123") print(f"Remaining balance: ${balance_info.data.balance}") ``` ``` -------------------------------- ### get /v1/customers/{customer_id} Source: https://github.com/metronome-industries/metronome-python/blob/main/api.md Retrieves a specific customer by their ID. Returns detailed information about the customer. ```APIDOC ## GET /v1/customers/{customer_id} ### Description Retrieves a specific customer by their ID. ### Method GET ### Endpoint /v1/customers/{customer_id} ### Parameters #### Path Parameters - **customer_id** (string) - Required - The unique identifier of the customer. ### Response #### Success Response (200) - **CustomerRetrieveResponse** - Detailed information about the customer. ``` -------------------------------- ### Get Contract Balance Summary Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/v1-resources.md Retrieves a summary of the balance for a specific contract using its ID. ```python balances = client.v1.contracts.list_balances("contract_id") ``` -------------------------------- ### Client Copy and Context Management Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/client.md Create a new client instance with overridden parameters using `copy()`, or use the client as a context manager for automatic resource cleanup. ```APIDOC ## Client Management ### `copy()` Create a new client instance with optionally overridden parameters. ```python new_client = client.copy( bearer_token="new-token", timeout=30.0, ) ``` ### `close()` Manually close the underlying HTTP connection. Called automatically on garbage collection. ### `__enter__` / `__exit__` Context manager support for automatic cleanup. ```python with Metronome() as client: client.v1.usage.ingest(...) # HTTP connection automatically closed ``` ``` -------------------------------- ### List Resources with Pagination Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/README.md Explains how to list resources and handle pagination, including automatic iteration and manual page retrieval. ```APIDOC ## List Resources with Pagination ### Description Provides methods for listing resources and handling pagination, allowing for automatic iteration through all pages or manual control over page retrieval. ### Method `client.v1.customers.list()` ### Usage #### Auto-iteration ```python all_customers = [] for customer in client.v1.customers.list(): all_customers.append(customer) ``` #### Manual Pagination ```python first_page = client.v1.customers.list() if first_page.has_next_page(): second_page = first_page.get_next_page() ``` ``` -------------------------------- ### Retrieve Customer Details Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/v1-resources.md Get the details of a specific customer using their unique customer ID. ```python customer = client.v1.customers.retrieve("customer_id") ``` -------------------------------- ### Create an Alert Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/v1-resources.md Sets up a new alert for a customer based on usage, balance, or other defined thresholds. Requires customer ID, alert type, and specific parameters like threshold value. ```python alert = client.v1.alerts.create( customer_id="customer_id", alert_type="usage_threshold", threshold=100.0, ) ``` -------------------------------- ### get /v1/customers/{customer_id}/costs Source: https://github.com/metronome-industries/metronome-python/blob/main/api.md Lists costs associated with a specific customer. Supports filtering and pagination. ```APIDOC ## GET /v1/customers/{customer_id}/costs ### Description Lists costs associated with a specific customer. ### Method GET ### Endpoint /v1/customers/{customer_id}/costs ### Parameters #### Path Parameters - **customer_id** (string) - Required - The unique identifier of the customer. #### Query Parameters - **params** (CustomerListCostsParams) - Optional - Parameters for filtering and pagination. ### Response #### Success Response (200) - **SyncCursorPage[CustomerListCostsResponse]** - A paginated list of costs for the customer. ``` -------------------------------- ### Minimal Configuration (Environment Variable) Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/configuration.md Initializes the Metronome client, reading the bearer token from the `METRONOME_BEARER_TOKEN` environment variable if not explicitly provided. ```python from metronome import Metronome # Read bearer_token from METRONOME_BEARER_TOKEN env var client = Metronome() ``` -------------------------------- ### get /v1/customers/{customer_id}/billable-metrics Source: https://github.com/metronome-industries/metronome-python/blob/main/api.md Lists billable metrics for a specific customer. Supports filtering and pagination. ```APIDOC ## GET /v1/customers/{customer_id}/billable-metrics ### Description Lists billable metrics for a specific customer. ### Method GET ### Endpoint /v1/customers/{customer_id}/billable-metrics ### Parameters #### Path Parameters - **customer_id** (string) - Required - The unique identifier of the customer. #### Query Parameters - **params** (CustomerListBillableMetricsParams) - Optional - Parameters for filtering and pagination. ### Response #### Success Response (200) - **SyncCursorPage[CustomerListBillableMetricsResponse]** - A paginated list of billable metrics for the customer. ``` -------------------------------- ### Configure HTTP Client with Proxies and Transports Source: https://github.com/metronome-industries/metronome-python/blob/main/README.md Customize the `httpx` client by passing proxy and transport configurations during `Metronome` client initialization. ```python import httpx from metronome import Metronome, DefaultHttpxClient client = Metronome( # Or use the `METRONOME_BASE_URL` env var base_url="http://my.test.server.example.com:8083", http_client=DefaultHttpxClient( proxy="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) ``` -------------------------------- ### Get Customer Costs Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/v1-resources.md Retrieve the cost data for a specific customer within a given date range. ```python costs = client.v1.customers.list_costs( customer_id="customer_id", starting_on="2024-01-01", ending_before="2024-01-31", ) ``` -------------------------------- ### Configure httpx with Custom Settings Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/advanced-features.md Use DefaultHttpxClient to configure httpx with custom settings like proxy, SSL verification, and client certificates. ```python import httpx from metronome import Metronome, DefaultHttpxClient # Configure httpx with custom settings client = Metronome( http_client=DefaultHttpxClient( proxy="http://proxy.example.com:8080", verify=False, # Disable SSL verification (not recommended for production) cert="path/to/client.pem", # Client certificate mounts={ "https://": httpx.HTTPTransport( verify=False, ), }, ) ) ``` -------------------------------- ### Create New Client Instance Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/client.md Use the `copy()` method to create a new client instance with potentially overridden parameters, such as a new bearer token or timeout value. ```python new_client = client.copy( bearer_token="new-token", timeout=30.0, ) ``` -------------------------------- ### Bootstrap Environment with Rye Source: https://github.com/metronome-industries/metronome-python/blob/main/CONTRIBUTING.md Use this command to automatically provision a Python environment with the expected Python version using Rye. ```sh ./scripts/bootstrap ``` -------------------------------- ### Get Embeddable Dashboard URL Source: https://github.com/metronome-industries/metronome-python/blob/main/api.md Retrieves a URL to embed a dashboard. This is useful for integrating Metronome dashboards into other applications. ```APIDOC ## POST /v1/dashboards/getEmbeddableUrl ### Description Retrieves a URL to embed a dashboard. ### Method POST ### Endpoint /v1/dashboards/getEmbeddableUrl ### Parameters #### Request Body - **params** (object) - Required - Parameters for getting the embeddable URL. ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **DashboardGetEmbeddableURLResponse** (object) - The response contains the embeddable URL. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Create Product Source: https://github.com/metronome-industries/metronome-python/blob/main/api.md Creates a new product within the contract pricing system. Requires parameters to define the product's attributes. ```python client.v1.contracts.products.create(**params) -> ProductCreateResponse ``` -------------------------------- ### Get Embeddable Dashboard URL Source: https://github.com/metronome-industries/metronome-python/blob/main/api.md Use this method to obtain a URL for embedding a Metronome dashboard. Requires dashboard parameters. ```python from metronome.types.v1 import DashboardGetEmbeddableURLResponse ``` ```python client.v1.dashboards.get_embeddable_url(**params) -> DashboardGetEmbeddableURLResponse ``` -------------------------------- ### Metronome Client as Synchronous Context Manager Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/configuration.md Demonstrates using the Metronome client as a synchronous context manager for automatic resource cleanup during operations like listing customers. ```python from metronome import Metronome # Synchronous with Metronome() as client: result = client.v1.customers.list() ``` -------------------------------- ### Get Next Page Info with SyncCursorPage Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/pagination.md Retrieve pagination metadata, including the cursor for the next page, using `next_page_info()`. ```python info = customers.next_page_info() if info: print(f"Next page cursor: {info.params['next_page']}") ``` -------------------------------- ### Create Free Trial Contract Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/contracts-api.md Creates a new contract configured as a free trial with a large amount of credits. ```APIDOC ## Creating a Free Trial Contract ### Description Creates a new contract configured as a free trial with a large amount of credits. ### Example ```python from datetime import datetime, timedelta trial_end = datetime.now() + timedelta(days=30) contract = client.v1.contracts.create( customer_id="trial_cust", starting_at=datetime.now(), ending_before=trial_end, rate_card_id="standard_rate_card", credits=[ { "amount": 999999999.0, # Effectively unlimited "expires_at": trial_end.isoformat(), } ], ) ``` ``` -------------------------------- ### Streaming Large Responses Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/v1-resources.md Provides an example of how to stream large response payloads line by line, which is efficient for handling substantial data. ```python with client.with_streaming_response.v1.contracts.list() as response: for line in response.iter_lines(): print(line) ``` -------------------------------- ### Create Package Source: https://github.com/metronome-industries/metronome-python/blob/main/api.md Creates a new package with the provided parameters. Returns the details of the created package. ```APIDOC ## POST /v1/packages/create ### Description Creates a new package. ### Method POST ### Endpoint /v1/packages/create ### Parameters #### Request Body - **params** (object) - Required - Parameters for creating a package. See `metronome.types.v1.package_create_params`. ### Response #### Success Response (200) - **PackageCreateResponse** - Details of the created package. ``` -------------------------------- ### List All Plans Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/v1-resources.md Retrieves a list of all available plans within the system. ```python plans = client.v1.plans.list() ``` -------------------------------- ### Get Net Balance for a Contract Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/contracts-api.md Retrieves the total prepaid amount remaining for a specific contract. Use this to check the current balance. ```python balance_info = client.v1.contracts.get_net_balance("contract_123") print(f"Remaining balance: ${balance_info.data.balance}") ``` -------------------------------- ### Configure HTTPS Proxy with Authentication Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/advanced-features.md Configure an HTTPS proxy with basic authentication by including user credentials in the proxy URL. ```python from metronome import Metronome, DefaultHttpxClient client = Metronome( http_client=DefaultHttpxClient( proxy="https://user:password@proxy.example.com:8443", ) ) ``` -------------------------------- ### Get V2 Contract Edit History Source: https://github.com/metronome-industries/metronome-python/blob/main/api.md Calls the client.v2.contracts.get_edit_history method to retrieve the edit history of a V2 contract. Parameters are defined in contract_get_edit_history_params.py. ```python client.v2.contracts.get_edit_history(**params) -> ContractGetEditHistoryResponse ``` -------------------------------- ### Metronome SDK Constructor Options Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/README.md Initialize the Metronome client with various options, including authentication tokens, base URL, timeouts, retry configurations, custom headers, query parameters, and HTTP client settings. ```python from metronome import Metronome, DefaultHttpxClient import httpx client = Metronome( bearer_token="sk_live_xxxxx", webhook_secret="whk_xxxxx", base_url="https://api.metronome.com", timeout=60.0, max_retries=2, default_headers={"X-Custom": "value"}, default_query={"version": "v1"}, http_client=DefaultHttpxClient(proxy="http://proxy:8080"), ) ``` -------------------------------- ### Get Net Contract Balance Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/v1-resources.md Fetches the net balance of a contract, providing a single value for the outstanding amount. Requires the contract ID. ```python balance = client.v1.contracts.get_net_balance("contract_id") ``` -------------------------------- ### Create a Customer with Metronome Python SDK Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/README.md Use this snippet to create a new customer, specifying their name, external ID, ingestion aliases, and billing configuration. Ensure the billing configuration includes the correct billing provider and delivery method. ```python customer = client.v1.customers.create( name="Acme Corporation", external_id="ext_123", ingest_aliases=["acme", "acme-corp"], billing_config={ "billing_provider": "stripe", "delivery_method": "direct_to_billing_provider", "stripe": {"customer_id": "cus_abc123"}, }, ) ``` -------------------------------- ### Amend a Contract Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/v1-resources.md Modifies an existing contract by applying specified amendments, such as adding new commits or changing terms starting from a future date. ```python amended = client.v1.contracts.amend( contract_id="contract_id", amendments=[ { "starting_at": "2024-06-01", "add_commits": [...], } ], ) ``` -------------------------------- ### Configure Multiple Proxies Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/advanced-features.md Define different proxy servers for HTTP and HTTPS traffic using the mounts configuration. ```python from metronome import Metronome, DefaultHttpxClient client = Metronome( http_client=DefaultHttpxClient( mounts={ "http://": "http://http-proxy.example.com:8080", "https://": "https://https-proxy.example.com:8443", } ) ) ``` -------------------------------- ### List Resources with Pagination in Metronome Python SDK Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/README.md Demonstrates both auto-iteration and manual pagination for listing resources. Auto-iteration simplifies fetching all items across multiple pages, while manual pagination allows for explicit control over fetching subsequent pages. ```python # Auto-iteration across all pages all_customers = [] for customer in client.v1.customers.list(): all_customers.append(customer) # Manual pagination first_page = client.v1.customers.list() if first_page.has_next_page(): second_page = first_page.get_next_page() ``` -------------------------------- ### Create Contract with Nested Billing Configuration Source: https://github.com/metronome-industries/metronome-python/blob/main/README.md Demonstrates creating a contract with a nested dictionary for billing provider configuration. Ensure the `billing_provider_configuration` dictionary matches the expected schema for the chosen provider. ```python from metronome import Metronome client = Metronome() contract = client.v1.contracts.create( customer_id="13117714-3f05-48e5-a6e9-a66093f13b4d", starting_at=datetime.fromisoformat("2020-01-01T00:00:00.000"), billing_provider_configuration={ "billing_provider": "stripe", "delivery_method": "direct_to_billing_provider", }, ) print(contract.billing_provider_configuration) ``` -------------------------------- ### Async Streaming Response Lines Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/advanced-features.md Handle streaming responses asynchronously using `AsyncMetronome`. This example demonstrates iterating over lines of a streamed response in an async context. ```python from metronome import AsyncMetronome async def stream_data(): async with AsyncMetronome() as client: async with client.with_streaming_response.v1.contracts.list() as response: async for line in response.iter_lines(): print(line) ``` -------------------------------- ### Configuring the HTTP Client Source: https://github.com/metronome-industries/metronome-python/blob/main/README.md Details how to customize the underlying `httpx` client for advanced use cases like proxies, custom transports, or other advanced configurations. It also shows how to apply these configurations per-request. ```APIDOC ### Configuring the HTTP client You can directly override the [httpx client](https://www.python-httpx.org/api/#client) to customize it for your use case, including: - Support for [proxies](https://www.python-httpx.org/advanced/proxies/) - Custom [transports](https://www.python-httpx.org/advanced/transports/) - Additional [advanced](https://www.python-httpx.org/advanced/clients/) functionality ```python import httpx from metronome import Metronome, DefaultHttpxClient client = Metronome( # Or use the `METRONOME_BASE_URL` env var base_url="http://my.test.server.example.com:8083", http_client=DefaultHttpxClient( proxy="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) ``` You can also customize the client on a per-request basis by using `with_options()`: ```python client.with_options(http_client=DefaultHttpxClient(...)) ``` ``` -------------------------------- ### Enable Type Checking in VS Code Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/types.md Configure VS Code to enable basic static type checking for Python code. Ensure Pyright or Mypy is installed. ```bash python.analysis.typeCheckingMode = basic ``` -------------------------------- ### AsyncMetronome Context Manager Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/client.md Illustrates the recommended way to use `AsyncMetronome` with an asynchronous context manager for automatic resource cleanup. ```APIDOC ## AsyncMetronome Context Manager ### Description Using `AsyncMetronome` as an asynchronous context manager ensures that the underlying HTTP client resources are properly managed and released after use. ### Method `async with AsyncMetronome() as client:` ### Usage Example ```python async with AsyncMetronome() as client: result = await client.v1.contracts.create(...) ``` ``` -------------------------------- ### Stream Response Body Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/advanced-features.md Use `with_streaming_response` to process large response bodies without loading them entirely into memory. This example shows how to iterate over lines of the streamed response. ```python from metronome import Metronome client = Metronome() # Stream response body with client.with_streaming_response.v1.contracts.list() as response: print(f"Status: {response.status_code}") print(f"Headers: {response.headers}") # Stream the content for line in response.iter_lines(): print(line) ``` -------------------------------- ### Retrieve Product Source: https://github.com/metronome-industries/metronome-python/blob/main/api.md Fetches details of a specific product. Requires parameters to identify the product. ```python client.v1.contracts.products.retrieve(**params) -> ProductRetrieveResponse ``` -------------------------------- ### Get Entire Response as Text Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/advanced-features.md Retrieve the entire response body as a string using the `text()` method. Use this when the response is expected to be text and fits comfortably in memory. ```python with client.with_streaming_response.v1.contracts.list() as response: full_text = response.text() ``` -------------------------------- ### Example: Accessing Raw Content Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/advanced-features.md Shows how to retrieve the raw response body as text or a parsed JSON dictionary using the `text` property or `json()` method of the `APIResponse` object. ```APIDOC ## Example: Accessing Raw Content ```python response = client.with_raw_response.v1.contracts.list() # Get raw response raw_json = response.text print(f"Raw response: {raw_json}") # Or as parsed dict data = response.json() ``` ``` -------------------------------- ### Basic Synchronous Iteration Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/pagination.md Shows the simplest way to iterate over a collection of resources. The SDK automatically handles pagination behind the scenes. ```python from metronome import Metronome client = Metronome() # Synchronous iteration for customer in client.v1.customers.list(): print(f"Customer: {customer.name}") ``` -------------------------------- ### Co-term Upsell: Extend and Add Commitments to a Contract Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/contracts-api.md Shows how to extend an existing contract and add new commitments that start from the original contract's end date. This is useful for co-terming. ```python # Retrieve existing contract existing = client.v1.contracts.retrieve("contract_123") # Extend and add new commitment amended = client.v1.contracts.amend( "contract_123", amendments=[ { "starting_at": existing.data.ending_before, # Extend from current end "add_commits": [ { "amount": 50000.0, "invoice_schedule": "ADVANCE", } ], } ], ) ``` -------------------------------- ### Create a New Customer Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/v1-resources.md Create a new customer record with essential details like name, external ID, billing configuration, custom fields, and ingestion aliases. ```python customer = client.v1.customers.create( name="Acme Corp", external_id="ext_123", billing_config={ "billing_provider": "stripe", "delivery_method": "direct_to_billing_provider", "stripe": { "customer_id": "cus_123", }, }, custom_fields={ "industry": "SaaS", }, ingest_aliases=["acme", "acme-corp"], ) ``` -------------------------------- ### Retrieve Aggregated Usage Data Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/v1-resources.md Retrieve aggregated usage data within a specified date range. Supports daily, hourly, or no windowing for aggregation. Includes examples for iterating through pages and manual pagination. ```python usage_data = client.v1.usage.list( starting_on="2024-01-01", ending_before="2024-01-31", window_size="DAY", # "HOUR", "DAY", or "NONE" customer_ids=["customer_1"], billable_metrics=[{"id": "metric_1"}] ) # Iterate through pages for item in usage_data: print(item.value) # Manual pagination if usage_data.has_next_page(): next_page = usage_data.get_next_page() ``` -------------------------------- ### Create Contract Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/README.md Illustrates how to create a new contract with specified customer, duration, rate card, and commit details. ```APIDOC ## Create Contract ### Description Creates a new contract for a customer, defining its duration, rate card, and commit amounts. ### Method `client.v1.contracts.create()` ### Parameters - **customer_id** (string) - Required - The ID of the customer for whom the contract is created. - **starting_at** (datetime) - Required - The start date of the contract. - **ending_before** (datetime) - Required - The date before which the contract ends. - **rate_card_id** (string) - Required - The ID of the rate card to be used. - **commits** (list of objects) - Optional - Commitments associated with the contract. - **amount** (float) - Required - The commit amount. - **invoice_schedule** (string) - Required - The schedule for invoicing (e.g., "ADVANCE"). ### Request Example ```python from datetime import datetime contract = client.v1.contracts.create( customer_id="cust_123", starting_at=datetime(2024, 1, 1), ending_before=datetime(2024, 12, 31), rate_card_id="rate_456", commits=[ { "amount": 50000.0, "invoice_schedule": "ADVANCE", } ], ) ``` ``` -------------------------------- ### Best Practice: Batch Size for Ingestion Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/usage-api.md Optimize ingestion performance by sending events in batches of 100-1000 events per request. This example shows how to iterate through a list of all events and send them in manageable batches. ```python # Good: Batch events batch_size = 500 for i in range(0, len(all_events), batch_size): batch = all_events[i:i + batch_size] client.v1.usage.ingest(usage=batch) ``` -------------------------------- ### AsyncMetronome Context Manager Usage Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/api-reference/client.md Illustrates the recommended way to use `AsyncMetronome` with an asynchronous context manager for automatic resource cleanup. ```python async with AsyncMetronome() as client: result = await client.v1.contracts.create(...) ``` -------------------------------- ### Import Metronome Clients Source: https://github.com/metronome-industries/metronome-python/blob/main/_autodocs/MANIFEST.txt Import the synchronous and asynchronous Metronome client classes. ```python from metronome import Metronome, AsyncMetronome ```