Skip to main content

The official Python SDK for the Autumn billing API

Project description

autumn-sdk

The official Python SDK for the Autumn billing API.

PyPI version License: Apache-2.0

Summary

Developer-friendly & type-safe Python SDK for the Autumn billing API. Manage customers, plans, features, usage tracking, and billing operations.

Table of Contents

SDK Installation

The SDK can be installed with pip, uv, or poetry package managers.

PIP

pip install autumn-sdk

uv

uv add autumn-sdk

Poetry

poetry add autumn-sdk

Shell and script usage with uv

You can use this SDK in a Python shell with uv and the uvx command that comes with it like so:

uvx --from autumn-sdk python

It's also possible to write a standalone Python script without needing to set up a whole project like so:

#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10"
# dependencies = [
#     "autumn-sdk",
# ]
# ///

from autumn_sdk import Autumn

sdk = Autumn(
  # SDK arguments
)

# Rest of script here...

Once that is saved to a file, you can run it with uv run script.py where script.py can be replaced with the actual file name.

IDE Support

PyCharm

Generally, the SDK will work well with most IDEs out of the box. However, when using PyCharm, you can enjoy much better integration with Pydantic by installing an additional plugin.

SDK Example Usage

Example

# Synchronous Example
from autumn_sdk import Autumn


with Autumn(
    x_api_version="2.2.0",
    secret_key="<YOUR_BEARER_TOKEN_HERE>",
) as autumn:

    res = autumn.check(customer_id="cus_123", feature_id="messages")

    # Handle response
    print(res)

The same SDK client can also be used to make asynchronous requests by importing asyncio.

# Asynchronous Example
import asyncio
from autumn_sdk import Autumn

async def main():

    async with Autumn(
        x_api_version="2.2.0",
        secret_key="<YOUR_BEARER_TOKEN_HERE>",
    ) as autumn:

        res = await autumn.check_async(customer_id="cus_123", feature_id="messages")

        # Handle response
        print(res)

asyncio.run(main())

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme
secret_key http HTTP Bearer

To authenticate with the API the secret_key parameter must be set when initializing the SDK client instance. For example:

from autumn_sdk import Autumn


with Autumn(
    secret_key="<YOUR_BEARER_TOKEN_HERE>",
    x_api_version="2.2.0",
) as autumn:

    res = autumn.check(customer_id="cus_123", feature_id="messages")

    # Handle response
    print(res)

Available Resources and Operations

Available methods

Autumn SDK

  • check - Checks whether a customer currently has enough balance to use a feature.

Use this to gate access before a feature action. Enable sendEvent when you want to check and consume balance atomically in one request.

  • track - Records usage for a customer feature and returns updated balances.

Use this after an action happens to decrement usage, or send a negative value to credit balance back.

Balances

  • create - Create a balance for a customer feature.
  • update - Update a customer balance.
  • delete - Delete a balance for a customer feature. Can only delete a balance that is not attached to a price (eg. you cannot delete messages that have an overage price).
  • finalize - Finalize a previously locked balance. Use 'confirm' to commit the deduction, or 'release' to return the held balance.

Billing

  • attach - Attaches a plan to a customer. Handles new subscriptions, upgrades and downgrades.

Use this endpoint to subscribe a customer to a plan, upgrade/downgrade between plans, or add an add-on product.

  • multi_attach - Attaches multiple plans to a customer in a single request. Creates a single Stripe subscription with all plans consolidated.

Use this endpoint when you need to subscribe a customer to multiple plans at once, such as a base plan plus add-ons, or to create a bundle of products.

  • preview_attach - Previews the billing changes that would occur when attaching a plan, without actually making any changes.

Use this endpoint to show customers what they will be charged before confirming a subscription change.

  • preview_multi_attach - Previews the billing changes that would occur when attaching multiple plans, without actually making any changes.

Use this endpoint to show customers what they will be charged before confirming a multi-plan subscription.

  • update - Updates an existing subscription. Use to modify feature quantities, cancel, or change plan configuration.

Use this endpoint to update prepaid quantities, cancel a subscription (immediately or at end of cycle), or modify subscription settings.

  • preview_update - Previews the billing changes that would occur when updating a subscription, without actually making any changes.

Use this endpoint to show customers prorated charges or refunds before confirming subscription modifications.

  • open_customer_portal - Create a billing portal session for a customer to manage their subscription.
  • setup_payment - Create a payment setup session for a customer to add or update their payment method.

Customers

  • get_or_create - Creates a customer if they do not exist, or returns the existing customer by your external customer ID.

Use this as the primary entrypoint before billing operations so the customer record is always present and up to date.

  • list - Lists customers with pagination and optional filters.
  • update - Updates an existing customer by ID.
  • delete - Deletes a customer by ID.

Entities

  • create - Creates an entity for a customer and feature, then returns the entity with balances and subscriptions.

Use entities when usage and access must be scoped to sub-resources (for example seats, projects, or workspaces) instead of only the customer.

  • get - Fetches an entity by its ID.

Use this to read one entity's current state. Pass customerId when you want to scope the lookup to a specific customer.

  • update - Updates an existing entity and returns the refreshed entity object.

Use this to change entity billing controls or other mutable entity fields after the entity has already been created.

  • delete - Deletes an entity by entity ID.

Use this when the underlying resource is removed and you no longer want entity-scoped balances or subscriptions tracked for it.

Events

  • list - List usage events for your organization. Filter by customer, feature, or time range.
  • aggregate - Aggregate usage events by time period. Returns usage totals grouped by feature and optionally by a custom property.

Features

  • create - Creates a new feature.

Use this to programmatically create features for metering usage, managing access, or building credit systems.

  • get - Retrieves a single feature by its ID.

Use this when you need to fetch the details of a specific feature.

  • list - Lists all features in the current environment.

Use this to retrieve all features configured for your organization to display in dashboards or for feature management.

  • update - Updates an existing feature.

Use this to modify feature properties like name, display settings, or to archive a feature.

  • delete - Deletes a feature by its ID.

Use this to permanently remove a feature. Note: features that are used in products cannot be deleted - archive them instead.

Plans

Referrals

  • create_code - Create or fetch a referral code for a customer in a referral program.
  • redeem_code - Redeem a referral code for a customer.

Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply provide a RetryConfig object to the call:

from autumn_sdk import Autumn
from autumn_sdk.utils import BackoffStrategy, RetryConfig


with Autumn(
    x_api_version="2.2.0",
    secret_key="<YOUR_BEARER_TOKEN_HERE>",
) as autumn:

    res = autumn.check(customer_id="cus_123", feature_id="messages",
        RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False))

    # Handle response
    print(res)

If you'd like to override the default retry strategy for all operations that support retries, you can use the retry_config optional parameter when initializing the SDK:

from autumn_sdk import Autumn
from autumn_sdk.utils import BackoffStrategy, RetryConfig


with Autumn(
    retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
    x_api_version="2.2.0",
    secret_key="<YOUR_BEARER_TOKEN_HERE>",
) as autumn:

    res = autumn.check(customer_id="cus_123", feature_id="messages")

    # Handle response
    print(res)

Error Handling

AutumnError is the base class for all HTTP error responses. It has the following properties:

Property Type Description
err.message str Error message
err.status_code int HTTP response status code eg 404
err.headers httpx.Headers HTTP response headers
err.body str HTTP body. Can be empty string if no body is returned.
err.raw_response httpx.Response Raw HTTP response

Example

from autumn_sdk import Autumn, errors


with Autumn(
    x_api_version="2.2.0",
    secret_key="<YOUR_BEARER_TOKEN_HERE>",
) as autumn:
    res = None
    try:

        res = autumn.check(customer_id="cus_123", feature_id="messages")

        # Handle response
        print(res)


    except errors.AutumnError as e:
        # The base class for HTTP error responses
        print(e.message)
        print(e.status_code)
        print(e.body)
        print(e.headers)
        print(e.raw_response)

Error Classes

Primary error:

  • AutumnError: The base class for HTTP error responses.
Less common errors (5)

Network errors:

Inherit from AutumnError:

  • ResponseValidationError: Type mismatch between the response data and the expected Pydantic model. Provides access to the Pydantic validation error via the cause attribute.

Server Selection

Override Server URL Per-Client

The default server can be overridden globally by passing a URL to the server_url: str optional parameter when initializing the SDK client instance. For example:

from autumn_sdk import Autumn


with Autumn(
    server_url="https://api.useautumn.com",
    x_api_version="2.2.0",
    secret_key="<YOUR_BEARER_TOKEN_HERE>",
) as autumn:

    res = autumn.check(customer_id="cus_123", feature_id="messages")

    # Handle response
    print(res)

Custom HTTP Client

The Python SDK makes API calls using the httpx HTTP library. In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance. Depending on whether you are using the sync or async version of the SDK, you can pass an instance of HttpClient or AsyncHttpClient respectively, which are Protocol's ensuring that the client has the necessary methods to make API calls. This allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of httpx.Client or httpx.AsyncClient directly.

For example, you could specify a header for every request that this sdk makes as follows:

from autumn_sdk import Autumn
import httpx

http_client = httpx.Client(headers={"x-custom-header": "someValue"})
s = Autumn(client=http_client)

or you could wrap the client with your own custom logic:

from autumn_sdk import Autumn
from autumn_sdk.httpclient import AsyncHttpClient
import httpx

class CustomClient(AsyncHttpClient):
    client: AsyncHttpClient

    def __init__(self, client: AsyncHttpClient):
        self.client = client

    async def send(
        self,
        request: httpx.Request,
        *,
        stream: bool = False,
        auth: Union[
            httpx._types.AuthTypes, httpx._client.UseClientDefault, None
        ] = httpx.USE_CLIENT_DEFAULT,
        follow_redirects: Union[
            bool, httpx._client.UseClientDefault
        ] = httpx.USE_CLIENT_DEFAULT,
    ) -> httpx.Response:
        request.headers["Client-Level-Header"] = "added by client"

        return await self.client.send(
            request, stream=stream, auth=auth, follow_redirects=follow_redirects
        )

    def build_request(
        self,
        method: str,
        url: httpx._types.URLTypes,
        *,
        content: Optional[httpx._types.RequestContent] = None,
        data: Optional[httpx._types.RequestData] = None,
        files: Optional[httpx._types.RequestFiles] = None,
        json: Optional[Any] = None,
        params: Optional[httpx._types.QueryParamTypes] = None,
        headers: Optional[httpx._types.HeaderTypes] = None,
        cookies: Optional[httpx._types.CookieTypes] = None,
        timeout: Union[
            httpx._types.TimeoutTypes, httpx._client.UseClientDefault
        ] = httpx.USE_CLIENT_DEFAULT,
        extensions: Optional[httpx._types.RequestExtensions] = None,
    ) -> httpx.Request:
        return self.client.build_request(
            method,
            url,
            content=content,
            data=data,
            files=files,
            json=json,
            params=params,
            headers=headers,
            cookies=cookies,
            timeout=timeout,
            extensions=extensions,
        )

s = Autumn(async_client=CustomClient(httpx.AsyncClient()))

Resource Management

The Autumn class implements the context manager protocol and registers a finalizer function to close the underlying sync and async HTTPX clients it uses under the hood. This will close HTTP connections, release memory and free up other resources held by the SDK. In short-lived Python programs and notebooks that make a few SDK method calls, resource management may not be a concern. However, in longer-lived programs, it is beneficial to create a single SDK instance via a context manager and reuse it across the application.

from autumn_sdk import Autumn
def main():

    with Autumn(
        x_api_version="2.2.0",
        secret_key="<YOUR_BEARER_TOKEN_HERE>",
    ) as autumn:
        # Rest of application here...


# Or when using async:
async def amain():

    async with Autumn(
        x_api_version="2.2.0",
        secret_key="<YOUR_BEARER_TOKEN_HERE>",
    ) as autumn:
        # Rest of application here...

Debugging

You can setup your SDK to emit debug logs for SDK requests and responses.

You can pass your own logger class directly into your SDK.

from autumn_sdk import Autumn
import logging

logging.basicConfig(level=logging.DEBUG)
s = Autumn(debug_logger=logging.getLogger("autumn_sdk"))

Development

Contributions

We welcome contributions! Feel free to open a PR or an issue on the Autumn GitHub repository.

Project details


Download files

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

Source Distribution

autumn_sdk-1.0.1.tar.gz (162.2 kB view details)

Uploaded Source

Built Distribution

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

autumn_sdk-1.0.1-py3-none-any.whl (216.0 kB view details)

Uploaded Python 3

File details

Details for the file autumn_sdk-1.0.1.tar.gz.

File metadata

  • Download URL: autumn_sdk-1.0.1.tar.gz
  • Upload date:
  • Size: 162.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.18 {"installer":{"name":"uv","version":"0.9.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for autumn_sdk-1.0.1.tar.gz
Algorithm Hash digest
SHA256 50d32e959f2b965740eaa4b8d737353ad88f382ec4a2a8fcd3cead365caeaebf
MD5 498a6e72360e3152a4222c3a4a75c179
BLAKE2b-256 b264eabe40f04d9752f0b50069699d9a0be8edf8df08afaa94a5ade381e75be8

See more details on using hashes here.

File details

Details for the file autumn_sdk-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: autumn_sdk-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 216.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.18 {"installer":{"name":"uv","version":"0.9.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for autumn_sdk-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 eab8b14617d2fb0aea97eb1f02f1134628ad8aa2a6114d953dfb70c8b51636e1
MD5 c6add0b0f61ab7e294f94cff4871e66c
BLAKE2b-256 cf9f28cc73e2d1d8997752d0174cbce3b5ae546a2bd59c061cb412ad5998b30f

See more details on using hashes here.

Supported by

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