### Install Lago Python Client Source: https://github.com/getlago/lago-python-client/blob/main/README.md Install the lago-python-client via pip or poetry. ```bash python -m pip install "lago-python-client" ``` ```bash poetry add "lago-python-client" ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/getlago/lago-python-client/blob/main/README.md Install development and linting dependencies for the Lago Python Client. ```bash python -m pip install --upgrade pip setuptools wheel python -m pip install '.[test,lint]' ``` -------------------------------- ### Create Wallet and Handle API Errors Source: https://github.com/getlago/lago-python-client/blob/main/README.md Example of creating a wallet using the Lago API client and handling potential LagoApiError exceptions. Access detailed error information like status code, detail, headers, response body, and URL. ```python try: response = client.wallets().create(wallet) except LagoApiError as error: do_something(status=error.status_code) ``` ```python error.status_code ``` ```python error.detail ``` ```python error.headers ``` ```python error.response ``` ```python error.response['error_details']['customer'][0] ``` ```python error.url ``` -------------------------------- ### Get Current Usage for a Subscription Source: https://context7.com/getlago/lago-python-client/llms.txt Retrieves the current usage details for a specific customer and subscription, with an option to apply taxes. ```python usage = client.customers.current_usage( "cust_001", external_subscription_id="sub_001", apply_taxes="true", ) print(usage.from_datetime, usage.to_datetime, usage.total_amount_cents) ``` -------------------------------- ### Get Self-Service Customer Portal URL Source: https://context7.com/getlago/lago-python-client/llms.txt Generates a URL for the customer to access their self-service portal. ```python url = client.customers.portal_url("cust_001") print(url) # "https://..." ``` -------------------------------- ### Get Past Usage Periods Source: https://context7.com/getlago/lago-python-client/llms.txt Fetches historical usage periods for a customer's subscription, with support for pagination. ```python past = client.customers.past_usage( "cust_001", external_subscription_id="sub_001", options={"page": 1, "per_page": 5}, ) ``` -------------------------------- ### Get Projected End-of-Period Usage Source: https://context7.com/getlago/lago-python-client/llms.txt Calculates the projected usage for a customer's subscription at the end of the current period. ```python projected = client.customers.projected_usage("cust_001", external_subscription_id="sub_001") ``` -------------------------------- ### Get Payment Provider Hosted Checkout URL Source: https://context7.com/getlago/lago-python-client/llms.txt Generates a URL for a payment provider's hosted checkout page for a customer. ```python checkout = client.customers.checkout_url("cust_001") print(checkout) # "https://checkout.stripe.com/..." ``` -------------------------------- ### Client Initialization Source: https://context7.com/getlago/lago-python-client/llms.txt Instantiate the Client class with an API key and optional configurations for base URL, ingest service, and rate-limit retries. ```APIDOC ## Client Initialization The `Client` class is the entry point for all API interactions. Instantiate it with an API key and, optionally, a custom base URL (for self-hosted Lago instances), ingest service settings, and rate-limit retry configuration. ```python from lago_python_client import Client # Minimal – connect to Lago Cloud client = Client(api_key="your_lago_api_key") # Self-hosted Lago with custom base URL client = Client( api_key="your_lago_api_key", api_url="https://lago.your-company.com/", ) # High-throughput ingest via dedicated ingest service client = Client( api_key="your_lago_api_key", use_ingest_service=True, ingest_api_url="https://ingest.your-lago.com/", max_retries=5, retry_on_rate_limit=True, ) # Disable automatic rate-limit retries client = Client( api_key="your_lago_api_key", retry_on_rate_limit=False, ) ``` ``` -------------------------------- ### Create a Plan Source: https://context7.com/getlago/lago-python-client/llms.txt Defines a new pricing plan with a name, code, interval, base fee, currency, and trial period. ```python from lago_python_client.models.plan import Plan from lago_python_client.models.charge import Charges plan = client.plans.create(Plan( name="Starter", code="starter", interval="monthly", # weekly | monthly | yearly | quarterly amount_cents=1000, # $10.00 base fee amount_currency="USD", pay_in_advance=True, trial_period=14.0, # 14-day trial )) print(plan.lago_id, plan.code) ``` -------------------------------- ### Initialize Lago Python Client Source: https://context7.com/getlago/lago-python-client/llms.txt Instantiate the Client with an API key. Optionally configure a custom base URL for self-hosted instances, enable the ingest service for high-throughput, or adjust rate-limit retry settings. ```python from lago_python_client import Client # Minimal – connect to Lago Cloud client = Client(api_key="your_lago_api_key") # Self-hosted Lago with custom base URL client = Client( api_key="your_lago_api_key", api_url="https://lago.your-company.com/", ) # High-throughput ingest via dedicated ingest service client = Client( api_key="your_lago_api_key", use_ingest_service=True, ingest_api_url="https://ingest.your-lago.com/", max_retries=5, retry_on_rate_limit=True, ) # Disable automatic rate-limit retries client = Client( api_key="your_lago_api_key", retry_on_rate_limit=False, ) ``` -------------------------------- ### Format Code Source: https://github.com/getlago/lago-python-client/blob/main/README.md Format the code using ruff. ```bash ruff format ``` -------------------------------- ### Create, Update, Find, and Destroy Add-Ons Source: https://context7.com/getlago/lago-python-client/llms.txt Manage one-time charges for invoices. The 'AddOn' model requires name, code, amount, and currency. Use 'amount_cents' for precise monetary values. ```python from lago_python_client.models.add_on import AddOn add_on = client.add_ons.create(AddOn( name="Professional Setup", code="setup_fee", amount_cents=49900, amount_currency="USD", description="One-time professional setup fee", )) print(add_on.lago_id, add_on.code) client.add_ons.update(AddOn(amount_cents=59900), identifier="setup_fee") client.add_ons.find("setup_fee") client.add_ons.find_all({"page": 1, "per_page": 20}) client.add_ons.destroy("setup_fee") ``` -------------------------------- ### Create or Activate a Subscription Source: https://context7.com/getlago/lago-python-client/llms.txt Assigns a customer to a plan, creating a new subscription or activating an existing one. Specify the customer, plan, and billing time. ```python from lago_python_client.models.subscription import Subscription from lago_python_client.models.alert import AlertsList, AlertResponse sub = client.subscriptions.create(Subscription( external_customer_id="cust_001", external_id="sub_001", plan_code="starter", billing_time="anniversary", # calendar | anniversary subscription_at="2024-01-01T00:00:00Z", )) print(sub.lago_id, sub.status) ``` -------------------------------- ### Create and Manage Coupons Source: https://context7.com/getlago/lago-python-client/llms.txt This section covers the creation, updating, retrieval, and deletion of discount coupons. Coupons can be percentage-based or fixed-amount and have various frequency and expiration settings. ```python from lago_python_client.models.coupon import Coupon from lago_python_client.models.applied_coupon import AppliedCoupon # Create a coupon coupon = client.coupons.create(Coupon( name="20% Off First Month", code="FIRST20", coupon_type="percentage", percentage_rate=20.0, frequency="once", expiration="time_limit", expiration_at="2025-12-31T23:59:59Z", reusable=False, )) print(coupon.lago_id, coupon.code) # Update / find / list / delete client.coupons.update(Coupon(name="20% Off – Extended"), identifier="FIRST20") client.coupons.find("FIRST20") client.coupons.find_all({"page": 1, "per_page": 20}) client.coupons.destroy("FIRST20") # Apply a coupon to a customer applied = client.applied_coupons.create(AppliedCoupon( external_customer_id="cust_001", coupon_code="FIRST20", )) print(applied.lago_id, applied.status) # List applied coupons all_applied = client.applied_coupons.find_all({"external_customer_id": "cust_001"}) # Revoke an applied coupon client.applied_coupons.destroy("cust_001", applied.lago_id) ``` -------------------------------- ### Manage Subscriptions with Lago Python Client Source: https://context7.com/getlago/lago-python-client/llms.txt Use these methods to update, retrieve, list, terminate, and track usage for subscriptions. Ensure the client is initialized before use. ```python updated = client.subscriptions.update(Subscription( name="Primary subscription", ending_at="2025-01-01T00:00:00Z", ), identifier="sub_001") ``` ```python sub = client.subscriptions.find("sub_001") ``` ```python all_subs = client.subscriptions.find_all({ "external_customer_id": "cust_001", "status": ["active", "pending"], }) ``` ```python client.subscriptions.destroy("sub_001") ``` ```python usage = client.subscriptions.lifetime_usage("sub_001") print(usage.usage_amount_cents) ``` ```python client.subscriptions.update_lifetime_usage("sub_001", external_historical_usage_amount_cents=5000_00) ``` ```python from lago_python_client.models.alert import AlertsList alerts = client.subscriptions.create_alerts("sub_001", AlertsList(...)) ``` ```python client.subscriptions.delete_alerts("sub_001") ``` ```python filters = client.subscriptions.find_all_charge_filters("sub_001", "api_calls") ``` -------------------------------- ### Retrieve and List Plans Source: https://context7.com/getlago/lago-python-client/llms.txt Fetches a single plan by its identifier or a paginated list of all plans. ```python plan = client.plans.find("starter") all_plans = client.plans.find_all({"page": 1, "per_page": 20}) ``` -------------------------------- ### Manage Wallets and Wallet Transactions Source: https://context7.com/getlago/lago-python-client/llms.txt Handles the creation and management of prepaid credit wallets, including setting up recurring top-up rules. It also covers creating, listing, and managing wallet transactions for top-ups. ```python from lago_python_client.models.wallet import Wallet, RecurringTransactionRule, RecurringTransactionRuleList from lago_python_client.models.wallet_transaction import WalletTransaction # Create a wallet wallet = client.wallets.create(Wallet( external_customer_id="cust_001", rate_amount="1.0", name="Prepaid Credits", currency="USD", paid_credits="100.0", granted_credits="10.0", recurring_transaction_rules=RecurringTransactionRuleList(__root__=[ RecurringTransactionRule( trigger="interval", interval="monthly", paid_credits="50.0", granted_credits="0", method="fixed", ), ]), )) print(wallet.lago_id, wallet.credits_balance, wallet.status) # Update / find / list / terminate client.wallets.update(Wallet(name="Main Credits Wallet"), identifier=wallet.lago_id) client.wallets.find(wallet.lago_id) client.wallets.find_all({"external_customer_id": "cust_001"}) client.wallets.destroy(wallet.lago_id) # Wallet metadata client.wallets.replace_metadata(wallet.lago_id, {"purpose": "api-credits"}) client.wallets.merge_metadata(wallet.lago_id, {"env": "production"}) client.wallets.delete_all_metadata(wallet.lago_id) # Top up a wallet (create a wallet transaction) tx_list = client.wallet_transactions.create(WalletTransaction( wallet_id=wallet.lago_id, paid_credits="50.0", granted_credits="0", )) # tx_list["wallet_transactions"] → list of WalletTransactionResponse # List transactions for a wallet txns = client.wallet_transactions.find_all(wallet.lago_id, {"transaction_type": "inbound"}) # Get hosted payment URL for a top-up pay_url = client.wallet_transactions.payment_url(tx_list["wallet_transactions"][0].lago_id) # Consumption and funding breakdown consumptions = client.wallet_transactions.consumptions(tx_list["wallet_transactions"][0].lago_id) fundings = client.wallet_transactions.fundings(tx_list["wallet_transactions"][0].lago_id) ``` -------------------------------- ### Create or Update a Customer Source: https://context7.com/getlago/lago-python-client/llms.txt Use this to create a new customer or update an existing one using their external_id. Ensure all required fields like name, email, currency, and country are provided. ```python from lago_python_client.models.customer import Customer, CustomerBillingConfiguration customer = client.customers.create(Customer( external_id="cust_001", name="Acme Corp", email="billing@acme.com", currency="USD", country="US", timezone="America/New_York", billing_configuration=CustomerBillingConfiguration( payment_provider="stripe", provider_customer_id="cus_stripe_abc123", sync_with_provider=True, ), )) print(customer.lago_id, customer.applicable_timezone) ``` -------------------------------- ### List All Customers with Pagination Source: https://context7.com/getlago/lago-python-client/llms.txt Fetches a paginated list of all customers. Use the 'page' and 'per_page' parameters to control the results. The response includes customer data and pagination metadata. ```python result = client.customers.find_all({"page": 1, "per_page": 20}) # result["customers"] → list of CustomerResponse objects # result["meta"] → {"current_page": 1, "next_page": 2, "prev_page": None, "total_pages": 5, "total_count": 95} ``` -------------------------------- ### Run Tests Source: https://github.com/getlago/lago-python-client/blob/main/README.md Execute tests for the Lago Python Client using pytest. ```bash pytest ``` -------------------------------- ### Create, Update, and Retrieve Credit Notes Source: https://context7.com/getlago/lago-python-client/llms.txt Use these methods to manage credit notes, including creation, updates, retrieval, and PDF downloads. Ensure you have the necessary invoice and credit note IDs. ```python from lago_python_client.models.credit_note import CreditNote, CreditNoteItemsList, CreditNoteItem # Create a credit note cn = client.credit_notes.create(CreditNote( invoice_id="lago-invoice-uuid", credit_amount_cents=2500, refund_amount_cents=0, reason="duplicated_charge", items=CreditNoteItemsList(__root__=[ CreditNoteItem(fee_id="lago-fee-uuid", amount_cents=2500), ]), )) print(cn.lago_id, cn.credit_status) # Update credit note updated = client.credit_notes.update(CreditNote(refund_status="succeeded"), identifier=cn.lago_id) # Retrieve / list note = client.credit_notes.find(cn.lago_id) all_notes = client.credit_notes.find_all({"external_customer_id": "cust_001"}) # Trigger PDF download pdf = client.credit_notes.download(cn.lago_id) # Void a credit note voided = client.credit_notes.void(cn.lago_id) # Metadata management client.credit_notes.replace_metadata(cn.lago_id, {"reason_code": "CC-001"}) client.credit_notes.merge_metadata(cn.lago_id, {"reviewed_by": "finance"}) client.credit_notes.delete_all_metadata(cn.lago_id) ``` -------------------------------- ### Issue Credit Notes with Lago Python Client Source: https://context7.com/getlago/lago-python-client/llms.txt Estimate and issue credit notes for full or partial refunds against finalized invoices. Requires importing specific credit note models. ```python from lago_python_client.models.credit_note import CreditNote, CreditNoteEstimate, CreditNoteItem, CreditNoteItemsList # Estimate a credit note before issuing estimated = client.credit_notes.estimate(CreditNoteEstimate( invoice_id="lago-invoice-uuid", items=CreditNoteItemsList(__root__=[ CreditNoteItem(fee_id="lago-fee-uuid", amount_cents=2500), ]), )) ``` -------------------------------- ### Customers Resource Source: https://context7.com/getlago/lago-python-client/llms.txt Manage customers using the `client.customers` interface, which supports creating, retrieving, listing, and deleting customers. It also includes methods for accessing customer usage and portal links. ```APIDOC ## Customers — `client.customers` Create, retrieve, list, and delete customers. Includes specialized methods for current/past usage, projected usage, portal URL, and checkout URL. ```python from lago_python_client.models.customer import Customer, CustomerBillingConfiguration ``` -------------------------------- ### Manage Invoices with Lago Python Client Source: https://context7.com/getlago/lago-python-client/llms.txt Handle the full invoice lifecycle, including creation, updates, downloads, finalization, retries, voids, and previews. Requires importing relevant models. ```python from lago_python_client.models.invoice import Invoice, OneOffInvoice, InvoiceFee, InvoiceFeesList, InvoicePreview from lago_python_client.models.customer import Customer # Create a one-off invoice invoice = client.invoices.create(OneOffInvoice( external_customer_id="cust_001", currency="USD", fees=InvoiceFeesList(__root__=[ InvoiceFee(add_on_code="setup_fee", unit_amount_cents=5000, units=1.0, description="One-time setup"), ]), )) ``` ```python # Update payment status updated = client.invoices.update(Invoice(payment_status="succeeded"), identifier=invoice.lago_id) ``` ```python # Retrieve / list with filters inv = client.invoices.find(invoice.lago_id) all_inv = client.invoices.find_all({ "status": "finalized", "payment_status": "pending", "external_customer_id": "cust_001", "page": 1, "per_page": 25, }) ``` ```python # Trigger PDF generation (async – returns None until ready) pdf = client.invoices.download(invoice.lago_id) ``` ```python # Finalize a draft invoice finalized = client.invoices.finalize(invoice.lago_id) ``` ```python # Refresh a draft invoice with latest data refreshed = client.invoices.refresh(invoice.lago_id) ``` ```python # Retry a failed payment retried = client.invoices.retry_payment(invoice.lago_id) ``` ```python # Void an invoice voided = client.invoices.void(invoice.lago_id) ``` ```python # Generate a hosted payment URL pay_url = client.invoices.payment_url(invoice.lago_id) print(pay_url) ``` ```python # Preview an invoice before subscription starts preview = client.invoices.preview(InvoicePreview( plan_code="starter", billing_time="anniversary", customer=Customer(external_id="cust_preview", email="test@example.com", currency="USD"), )) ``` -------------------------------- ### Create and Retrieve Payments Source: https://context7.com/getlago/lago-python-client/llms.txt Record manual payments against invoices. Requires 'invoice_id', 'amount_cents', 'reference', and 'paid_at' timestamp. Use 'find' for a single payment and 'find_all' for lists. ```python from lago_python_client.models.payment import Payment # Create a payment against an invoice payment = client.payments.create(Payment( invoice_id="lago-invoice-uuid", amount_cents=10000, reference="wire-transfer-ref-001", paid_at="2024-06-01T10:00:00Z", )) print(payment.lago_id, payment.amount_cents) # Retrieve / list p = client.payments.find(payment.lago_id) all_payments = client.payments.find_all({"invoice_id": "lago-invoice-uuid"}) ``` -------------------------------- ### Replace Plan Metadata Source: https://context7.com/getlago/lago-python-client/llms.txt Replaces all existing metadata associated with a plan. Provide a dictionary of key-value pairs for the new metadata. ```python meta = client.plans.replace_metadata("starter", {"tier": "basic", "region": "us-east"}) ``` -------------------------------- ### Ingest and Manage Events with Lago Python Client Source: https://context7.com/getlago/lago-python-client/llms.txt Use the events client to ingest single or batched usage events, retrieve events by transaction ID, and estimate fees. Ensure the correct models are imported. ```python from lago_python_client.models.event import Event, BatchEvent # Ingest a single usage event event = client.events.create(Event( transaction_id="txn_abc_001", external_subscription_id="sub_001", code="api_calls", timestamp=1700000000, properties={"endpoint": "/v1/users", "method": "GET", "request_count": 1}, )) ``` ```python # Retrieve an event by transaction ID found = client.events.find("txn_abc_001") print(found.lago_id, found.timestamp) ``` ```python # Batch ingest multiple events client.events.batch_create(BatchEvent(events=[ Event(transaction_id="txn_001", external_subscription_id="sub_001", code="api_calls", timestamp=1700000001), Event(transaction_id="txn_002", external_subscription_id="sub_001", code="api_calls", timestamp=1700000002), ])) ``` ```python # Estimate fees for a hypothetical event before ingesting fees = client.events.estimate_fees(Event( transaction_id="txn_estimate", external_subscription_id="sub_001", code="api_calls", timestamp=1700000000, )) ``` -------------------------------- ### Fetch Revenue and Usage Metrics Source: https://context7.com/getlago/lago-python-client/llms.txt Access read-only analytics for reporting on MRR, gross revenue, invoiced usage, collections, and overdue balances. Specify currency and time periods as needed. ```python # Monthly Recurring Revenue mrr = client.mrrs.find_all({"currency": "USD", "months": 12}) # mrr["mrrs"] → list of MrrResponse with month, amount_cents, currency # Gross Revenue revenue = client.gross_revenues.find_all({"currency": "USD", "months": 6}) # Invoiced Usage (usage-based revenue breakdown) invoiced = client.invoiced_usages.find_all({"currency": "USD"}) # Invoice Collection totals (paid / unpaid breakdown) collections = client.invoice_collections.find_all({"currency": "USD"}) # Overdue Balances overdue = client.overdue_balances.find_all({"currency": "USD"}) ``` -------------------------------- ### Retrieve Activity and API Logs Source: https://context7.com/getlago/lago-python-client/llms.txt Access read-only audit trails for user actions ('activity_logs') and raw API requests/responses ('api_logs'). Use 'find_all' for lists and 'find' with a log ID for specific entries. ```python # Activity logs (user/system audit trail) logs = client.activity_logs.find_all({"page": 1, "per_page": 50}) log = client.activity_logs.find("lago-activity-log-uuid") print(log.activity_type, log.activity_source, log.created_at) # API logs (raw HTTP request/response audit) api_logs = client.api_logs.find_all({"page": 1, "per_page": 50}) api_log = client.api_logs.find("lago-api-log-uuid") print(api_log.method, api_log.url, api_log.status, api_log.response_body) ``` -------------------------------- ### Create a Billable Metric Source: https://context7.com/getlago/lago-python-client/llms.txt Defines a new billable metric used for tracking usage signals. Specify the name, code, aggregation type, and whether it's recurring. ```python from lago_python_client.models.billable_metric import ( BillableMetric, BillableMetricEvaluateExpression, BillableMetricEvaluateExpressionEvent ) metric = client.billable_metrics.create(BillableMetric( name="API Calls", code="api_calls", aggregation_type="count_agg", # sum_agg | max_agg | unique_count_agg | weighted_sum_agg recurring=False, )) print(metric.lago_id, metric.code) ``` -------------------------------- ### Find All Charge Filters on a Plan Source: https://context7.com/getlago/lago-python-client/llms.txt Retrieves all charge filters associated with a specific plan and billable metric. ```python filters = client.plans.find_all_charge_filters("starter", "api_calls") ``` -------------------------------- ### Create, Update, Find, and Destroy Taxes Source: https://context7.com/getlago/lago-python-client/llms.txt Manage tax rates and codes. Ensure the 'Tax' model is imported. The 'applied_to_organization' field determines if the tax applies globally. ```python from lago_python_client.models.tax import Tax # Create a tax tax = client.taxes.create(Tax( name="VAT 20%", code="vat_20", rate=20.0, description="EU Value Added Tax", applied_to_organization=False, )) print(tax.lago_id, tax.code, tax.rate) # Full CRUD client.taxes.update(Tax(rate=21.0), identifier="vat_20") client.taxes.find("vat_20") client.taxes.find_all({"page": 1, "per_page": 20}) client.taxes.destroy("vat_20") ``` -------------------------------- ### Coupons API Source: https://context7.com/getlago/lago-python-client/llms.txt Manage discount coupons, including creation, updates, retrieval, deletion, and application to customers. ```APIDOC ## Coupons ### Description Operations for managing coupons and applied coupons. ### Methods **Coupons (`client.coupons`)** - `create(coupon_object)`: Creates a new coupon. - `update(coupon_object, identifier)`: Updates an existing coupon. - `find(identifier)`: Retrieves a specific coupon. - `find_all(params)`: Retrieves a list of coupons with optional filters. - `destroy(identifier)`: Deletes a coupon. **Applied Coupons (`client.applied_coupons`)** - `create(applied_coupon_object)`: Applies a coupon to a customer. - `find_all(params)`: Retrieves a list of applied coupons with optional filters. - `destroy(external_customer_id, applied_coupon_id)`: Revokes an applied coupon. ### Request Example (Create Coupon) ```python from lago_python_client.models.coupon import Coupon coupon = client.coupons.create(Coupon( name="20% Off First Month", code="FIRST20", coupon_type="percentage", percentage_rate=20.0, frequency="once", expiration="time_limit", expiration_at="2025-12-31T23:59:59Z", reusable=False, )) print(coupon.lago_id, coupon.code) ``` ### Request Example (Update Coupon) ```python client.coupons.update(Coupon(name="20% Off – Extended"), identifier="FIRST20") ``` ### Request Example (Find Coupon) ```python client.coupons.find("FIRST20") ``` ### Request Example (List Coupons) ```python client.coupons.find_all({"page": 1, "per_page": 20}) ``` ### Request Example (Destroy Coupon) ```python client.coupons.destroy("FIRST20") ``` ### Request Example (Apply Coupon) ```python from lago_python_client.models.applied_coupon import AppliedCoupon applied = client.applied_coupons.create(AppliedCoupon( external_customer_id="cust_001", coupon_code="FIRST20", )) print(applied.lago_id, applied.status) ``` ### Request Example (List Applied Coupons) ```python all_applied = client.applied_coupons.find_all({"external_customer_id": "cust_001"}) ``` ### Request Example (Revoke Applied Coupon) ```python client.applied_coupons.destroy("cust_001", applied.lago_id) ``` ``` -------------------------------- ### Retrieve and List Billable Metrics Source: https://context7.com/getlago/lago-python-client/llms.txt Fetches a single billable metric by its identifier or a paginated list of all metrics. ```python single = client.billable_metrics.find("api_calls") all_metrics = client.billable_metrics.find_all({"page": 1, "per_page": 50}) ``` -------------------------------- ### Rate-Limit Retry Configuration Source: https://context7.com/getlago/lago-python-client/llms.txt Configure automatic retry logic for HTTP 429 responses using exponential back-off via `Client` constructor arguments or by overriding the `rate_limit_retry_config` attribute. ```APIDOC ## Rate-Limit Retry Configuration Automatic retry logic for HTTP 429 responses uses exponential back-off. Configure via `Client` constructor arguments, which create a `RateLimitRetryConfig` internally. ```python from lago_python_client import Client # Custom retry policy: 5 retries, starting at 2s, multiplying by 3, capped at 30s client = Client( api_key="your_lago_api_key", max_retries=5, retry_on_rate_limit=True, # RateLimitRetryConfig defaults: base_backoff_seconds=1.0, backoff_multiplier=2.0, max_retry_delay=20.0 # To customize further, pass a RateLimitRetryConfig to the client internals directly: ) # Override retry config after construction via the rate_limit_retry_config attribute: from lago_python_client.services.rate_limit import RateLimitRetryConfig client.rate_limit_retry_config = RateLimitRetryConfig( max_retries=5, retry_on_rate_limit=True, base_backoff_seconds=2.0, backoff_multiplier=3.0, max_retry_delay=30.0, ) ``` ``` -------------------------------- ### Configure Rate-Limit Retries Source: https://context7.com/getlago/lago-python-client/llms.txt Customize the automatic retry policy for HTTP 429 responses using `max_retries`, `base_backoff_seconds`, `backoff_multiplier`, and `max_retry_delay`. These can be set during client initialization or by modifying the `rate_limit_retry_config` attribute. ```python from lago_python_client import Client # Custom retry policy: 5 retries, starting at 2s, multiplying by 3, capped at 30s client = Client( api_key="your_lago_api_key", max_retries=5, retry_on_rate_limit=True, # RateLimitRetryConfig defaults: base_backoff_seconds=1.0, backoff_multiplier=2.0, max_retry_delay=20.0 # To customize further, pass a RateLimitRetryConfig to the client internals directly: ) # Override retry config after construction via the rate_limit_retry_config attribute: from lago_python_client.services.rate_limit import RateLimitRetryConfig client.rate_limit_retry_config = RateLimitRetryConfig( max_retries=5, retry_on_rate_limit=True, base_backoff_seconds=2.0, backoff_multiplier=3.0, max_retry_delay=30.0, ) ``` -------------------------------- ### Subscription Management Source: https://context7.com/getlago/lago-python-client/llms.txt Operations for managing customer subscriptions to plans. ```APIDOC ## Subscriptions — `client.subscriptions` ### Description Assign customers to plans, manage subscription lifecycle, and access lifetime usage and charge filters. ### Methods - `create(subscription_data)`: Creates or activates a subscription for a customer. ### Request Example (Create Subscription) ```python from lago_python_client.models.subscription import Subscription sub = client.subscriptions.create(Subscription( external_customer_id="cust_001", external_id="sub_001", plan_code="starter", billing_time="anniversary", # calendar | anniversary subscription_at="2024-01-01T00:00:00Z", )) print(sub.lago_id, sub.status) ``` ``` -------------------------------- ### Manage Fees Source: https://context7.com/getlago/lago-python-client/llms.txt This section details how to find, update the payment status of, and delete individual fee line items. Ensure you have the correct fee identifier. ```python from lago_python_client.models.fee import Fee # Find a specific fee fee = client.fees.find("lago-fee-uuid") print(fee.lago_id, fee.amount_cents, fee.invoice_id) # List all fees with filters all_fees = client.fees.find_all({ "external_subscription_id": "sub_001", "fee_type": "charge", "page": 1, "per_page": 50, }) # Update payment status updated = client.fees.update(Fee(payment_status="succeeded"), identifier="lago-fee-uuid") # Delete a pending/unsettled fee client.fees.destroy("lago-fee-uuid") ``` -------------------------------- ### Manage Webhook Endpoints Source: https://context7.com/getlago/lago-python-client/llms.txt Register, update, retrieve, and delete webhook listener URLs. Requires 'webhook_url' and 'signature_algo'. Use the endpoint's 'lago_id' for subsequent operations. ```python from lago_python_client.models.webhook_endpoint import WebhookEndpoint endpoint = client.webhook_endpoints.create(WebhookEndpoint( webhook_url="https://your-app.com/webhooks/lago", signature_algo="hmac_sha256", )) print(endpoint.lago_id, endpoint.webhook_url) client.webhook_endpoints.update( WebhookEndpoint(webhook_url="https://your-app.com/webhooks/lago-v2"), identifier=endpoint.lago_id, ) client.webhook_endpoints.find(endpoint.lago_id) client.webhook_endpoints.find_all({"page": 1, "per_page": 20}) client.webhook_endpoints.destroy(endpoint.lago_id) ``` -------------------------------- ### Evaluate a Custom Expression Source: https://context7.com/getlago/lago-python-client/llms.txt Tests a custom billing expression against a sample event to see the calculated value. Useful for validating complex pricing logic. ```python result = client.billable_metrics.evaluate_expression( BillableMetricEvaluateExpression( expression="event.properties.request_count * 1.5", event=BillableMetricEvaluateExpressionEvent( code="api_calls", timestamp=1700000000, properties={"request_count": 10}, ), ) ) print(result.value) # 15.0 ``` -------------------------------- ### Find a Single Customer Source: https://context7.com/getlago/lago-python-client/llms.txt Retrieves a specific customer by their external_id. ```python customer = client.customers.find("cust_001") ``` -------------------------------- ### Fetch Public Key for Webhook Verification Source: https://context7.com/getlago/lago-python-client/llms.txt Retrieve the RSA public key required for verifying webhook signatures. The implementation of the verification logic depends on your chosen crypto library. ```python import hashlib, hmac # Fetch the public key bytes (base64-decoded DER format) public_key_bytes = client.webhooks.public_key() # Use the public key to verify an incoming webhook payload # (verification implementation depends on the crypto library you use) print(f"Public key ({len(public_key_bytes)} bytes) fetched successfully") ``` -------------------------------- ### Merge Plan Metadata Source: https://context7.com/getlago/lago-python-client/llms.txt Updates or adds individual metadata keys to a plan's existing metadata. Provide a dictionary of key-value pairs to merge. ```python meta = client.plans.merge_metadata("starter", {"region": "eu-west"}) ``` -------------------------------- ### Invoices API Source: https://context7.com/getlago/lago-python-client/llms.txt Manage the full invoice lifecycle, including creation, updates, downloads, and payment status. ```APIDOC ## Create One-Off Invoice ### Description Creates a one-off invoice for a customer. ### Method `client.invoices.create` ### Parameters - `one_off_invoice` (OneOffInvoice object) - Required - The one-off invoice details, including customer ID and fees. ### Request Example ```python from lago_python_client.models.invoice import Invoice, OneOffInvoice, InvoiceFee, InvoiceFeesList invoice = client.invoices.create(OneOffInvoice( external_customer_id="cust_001", currency="USD", fees=InvoiceFeesList(__root__=[ InvoiceFee(add_on_code="setup_fee", unit_amount_cents=5000, units=1.0, description="One-time setup"), ]), )) print(invoice.lago_id, invoice.number, invoice.total_amount_cents) ``` ``` ```APIDOC ## Update Invoice Payment Status ### Description Updates the payment status of an existing invoice. ### Method `client.invoices.update` ### Parameters - `invoice` (Invoice object) - Required - The invoice object with the updated payment status. - `identifier` (string) - Required - The Lago ID or external ID of the invoice to update. ### Request Example ```python from lago_python_client.models.invoice import Invoice updated = client.invoices.update(Invoice(payment_status="succeeded"), identifier=invoice.lago_id) ``` ``` ```APIDOC ## Find Invoice ### Description Retrieves a specific invoice by its identifier. ### Method `client.invoices.find` ### Parameters - `identifier` (string) - Required - The Lago ID or external ID of the invoice to retrieve. ### Request Example ```python inv = client.invoices.find(invoice.lago_id) ``` ``` ```APIDOC ## Find All Invoices ### Description Retrieves a list of invoices with filtering options. ### Method `client.invoices.find_all` ### Parameters - `params` (dict) - Optional - A dictionary containing filter parameters such as `status`, `payment_status`, `external_customer_id`, `page`, and `per_page`. ### Request Example ```python all_inv = client.invoices.find_all({ "status": "finalized", "payment_status": "pending", "external_customer_id": "cust_001", "page": 1, "per_page": 25, }) ``` ``` ```APIDOC ## Download Invoice PDF ### Description Triggers the generation of a PDF for an invoice. This is an asynchronous operation. ### Method `client.invoices.download` ### Parameters - `identifier` (string) - Required - The Lago ID or external ID of the invoice. ### Request Example ```python pdf = client.invoices.download(invoice.lago_id) ``` ### Response Returns the PDF content once generated, or `None` if not yet ready. ``` ```APIDOC ## Finalize Invoice ### Description Finalizes a draft invoice, making it ready for payment processing. ### Method `client.invoices.finalize` ### Parameters - `identifier` (string) - Required - The Lago ID or external ID of the invoice to finalize. ### Request Example ```python finalized = client.invoices.finalize(invoice.lago_id) ``` ``` ```APIDOC ## Refresh Invoice ### Description Refreshes a draft invoice with the latest data. ### Method `client.invoices.refresh` ### Parameters - `identifier` (string) - Required - The Lago ID or external ID of the invoice to refresh. ### Request Example ```python refreshed = client.invoices.refresh(invoice.lago_id) ``` ``` ```APIDOC ## Retry Invoice Payment ### Description Retries the payment for an invoice that failed. ### Method `client.invoices.retry_payment` ### Parameters - `identifier` (string) - Required - The Lago ID or external ID of the invoice. ### Request Example ```python retried = client.invoices.retry_payment(invoice.lago_id) ``` ``` ```APIDOC ## Void Invoice ### Description Voids an invoice. ### Method `client.invoices.void` ### Parameters - `identifier` (string) - Required - The Lago ID or external ID of the invoice to void. ### Request Example ```python voided = client.invoices.void(invoice.lago_id) ``` ``` ```APIDOC ## Get Invoice Payment URL ### Description Generates a hosted payment URL for an invoice. ### Method `client.invoices.payment_url` ### Parameters - `identifier` (string) - Required - The Lago ID or external ID of the invoice. ### Request Example ```python pay_url = client.invoices.payment_url(invoice.lago_id) print(pay_url) ``` ``` ```APIDOC ## Preview Invoice ### Description Generates a preview of an invoice before it is finalized or subscription starts. ### Method `client.invoices.preview` ### Parameters - `invoice_preview` (InvoicePreview object) - Required - An InvoicePreview object containing details for the preview. ### Request Example ```python from lago_python_client.models.invoice import InvoicePreview from lago_python_client.models.customer import Customer preview = client.invoices.preview(InvoicePreview( plan_code="starter", billing_time="anniversary", customer=Customer(external_id="cust_preview", email="test@example.com", currency="USD"), )) print(preview.total_amount_cents) ``` ``` -------------------------------- ### Plans Management Source: https://context7.com/getlago/lago-python-client/llms.txt Operations for defining and managing pricing plans, including charges, metadata, and filters. ```APIDOC ## Plans — `client.plans` ### Description Define pricing plans with charges, fixed charges, minimum commitments, and usage thresholds. ### Methods - `create(plan_data)`: Creates a new plan. - `update(plan_data, identifier)`: Updates an existing plan. - `find(code)`: Retrieves a single plan by its code. - `find_all(options)`: Retrieves a list of all plans with pagination options. - `replace_metadata(code, metadata)`: Replaces all metadata keys for a plan. - `merge_metadata(code, metadata)`: Merges individual metadata keys into a plan's metadata. - `delete_metadata_key(code, key)`: Deletes a specific metadata key from a plan. - `delete_all_metadata(code)`: Deletes all metadata from a plan. - `find_all_charge_filters(code, billable_metric_code)`: Retrieves all charge filters for a plan and billable metric. ### Request Example (Create Plan) ```python from lago_python_client.models.plan import Plan plan = client.plans.create(Plan( name="Starter", code="starter", interval="monthly", # weekly | monthly | yearly | quarterly amount_cents=1000, # $10.00 base fee amount_currency="USD", pay_in_advance=True, trial_period=14.0, # 14-day trial )) print(plan.lago_id, plan.code) ``` ### Request Example (Update Plan) ```python updated = client.plans.update(Plan( name="Starter v2", amount_cents=1500, ), identifier="starter") ``` ### Request Example (Find Plan) ```python plan = client.plans.find("starter") ``` ### Request Example (List Plans) ```python all_plans = client.plans.find_all({"page": 1, "per_page": 20}) ``` ### Request Example (Replace Metadata) ```python meta = client.plans.replace_metadata("starter", {"tier": "basic", "region": "us-east"}) ``` ### Request Example (Merge Metadata) ```python meta = client.plans.merge_metadata("starter", {"region": "eu-west"}) ``` ### Request Example (Delete Metadata Key) ```python client.plans.delete_metadata_key("starter", "region") ``` ### Request Example (Delete All Metadata) ```python client.plans.delete_all_metadata("starter") ``` ### Request Example (Find Charge Filters) ```python filters = client.plans.find_all_charge_filters("starter", "api_calls") ``` ``` -------------------------------- ### Credit Notes API Source: https://context7.com/getlago/lago-python-client/llms.txt Manage credit notes, including creation, updates, retrieval, PDF downloads, voiding, and metadata management. ```APIDOC ## Credit Notes ### Description Operations for managing credit notes within the Lago system. ### Methods - `create(credit_note_object)`: Creates a new credit note. - `update(credit_note_object, identifier)`: Updates an existing credit note. - `find(identifier)`: Retrieves a specific credit note. - `find_all(params)`: Retrieves a list of credit notes with optional filters. - `download(identifier)`: Downloads the PDF for a credit note. - `void(identifier)`: Voids a credit note. - `replace_metadata(identifier, metadata)`: Replaces all metadata for a credit note. - `merge_metadata(identifier, metadata)`: Merges new metadata with existing metadata for a credit note. - `delete_all_metadata(identifier)`: Deletes all metadata associated with a credit note. ### Request Example (Create) ```python from lago_python_client.models.credit_note import CreditNote, CreditNoteItemsList, CreditNoteItem cn = client.credit_notes.create(CreditNote( invoice_id="lago-invoice-uuid", credit_amount_cents=2500, refund_amount_cents=0, reason="duplicated_charge", items=CreditNoteItemsList(__root__=[ CreditNoteItem(fee_id="lago-fee-uuid", amount_cents=2500), ]), )) print(cn.lago_id, cn.credit_status) ``` ### Request Example (Update) ```python updated = client.credit_notes.update(CreditNote(refund_status="succeeded"), identifier=cn.lago_id) ``` ### Request Example (Retrieve) ```python note = client.credit_notes.find(cn.lago_id) ``` ### Request Example (List) ```python all_notes = client.credit_notes.find_all({"external_customer_id": "cust_001"}) ``` ### Request Example (Download PDF) ```python pdf = client.credit_notes.download(cn.lago_id) ``` ### Request Example (Void) ```python voided = client.credit_notes.void(cn.lago_id) ``` ### Request Example (Replace Metadata) ```python client.credit_notes.replace_metadata(cn.lago_id, {"reason_code": "CC-001"}) ``` ### Request Example (Merge Metadata) ```python client.credit_notes.merge_metadata(cn.lago_id, {"reviewed_by": "finance"}) ``` ### Request Example (Delete All Metadata) ```python client.credit_notes.delete_all_metadata(cn.lago_id) ``` ``` -------------------------------- ### Payments API Source: https://context7.com/getlago/lago-python-client/llms.txt Create manual payments and retrieve payment records. Supports creation and retrieval of payments, including listing by invoice ID. ```APIDOC ## Payments — `client.payments` Create manual payments and retrieve payment records. ### Create Payment Creates a manual payment against an invoice. ```python from lago_python_client.models.payment import Payment payment = client.payments.create(Payment( invoice_id="lago-invoice-uuid", amount_cents=10000, reference="wire-transfer-ref-001", paid_at="2024-06-01T10:00:00Z", )) print(payment.lago_id, payment.amount_cents) ``` ### Find Payment Retrieves a specific payment by its ID. ```python p = client.payments.find(payment.lago_id) ``` ### Find All Payments Retrieves a list of payments, optionally filtered by invoice ID. ```python all_payments = client.payments.find_all({"invoice_id": "lago-invoice-uuid"}) ``` ``` -------------------------------- ### Taxes API Source: https://context7.com/getlago/lago-python-client/llms.txt Manage tax rates and codes. Allows for creation, retrieval, update, and deletion of tax configurations. ```APIDOC ## Taxes — `client.taxes` Define tax rates and codes to apply to customers and plans. ### Create Tax Creates a new tax rate. ```python from lago_python_client.models.tax import Tax tax = client.taxes.create(Tax( name="VAT 20%", code="vat_20", rate=20.0, description="EU Value Added Tax", applied_to_organization=False, )) print(tax.lago_id, tax.code, tax.rate) ``` ### Update Tax Updates an existing tax rate. ```python client.taxes.update(Tax(rate=21.0), identifier="vat_20") ``` ### Find Tax Retrieves a specific tax rate by its identifier. ```python client.taxes.find("vat_20") ``` ### Find All Taxes Retrieves a list of all tax rates with pagination. ```python client.taxes.find_all({"page": 1, "per_page": 20}) ``` ### Destroy Tax Deletes a tax rate. ```python client.taxes.destroy("vat_20") ``` ```