> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dodopayments.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python

> Use the Dodo Payments Python SDK, with sync and async clients, to create checkout sessions, customers, subscriptions, and usage events from Python 3.9+.

The Python SDK gives Python applications typed access to the Dodo Payments REST API. It has a synchronous client, `DodoPayments`, and an asynchronous client, `AsyncDodoPayments`, both built on `httpx`. Nested request parameters are typed dictionaries, and responses are Pydantic models.

## Installation

Install the SDK with pip:

```bash theme={null}
pip install dodopayments
```

To use aiohttp as the HTTP backend for the async client, install the `aiohttp` extra:

```bash theme={null}
pip install "dodopayments[aiohttp]"
```

To verify webhook signatures with `client.webhooks.unwrap()`, also install the `webhooks` extra: `pip install "dodopayments[webhooks]"`.

<Info>
  The SDK requires Python 3.9 or later. Use the latest stable Python release to get security updates.
</Info>

## Quick Start

### Synchronous Client

Create a client, then create a checkout session:

```python theme={null}
import os
from dodopayments import DodoPayments

client = DodoPayments(
    bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"),  # This is the default and can be omitted
    environment="test_mode",  # defaults to "live_mode"
)

checkout_session_response = client.checkout_sessions.create(
    product_cart=[
        {
            "product_id": "pdt_123",
            "quantity": 1
        }
    ],
)
print(checkout_session_response.session_id)
```

If you omit `bearer_token`, the client reads the `DODO_PAYMENTS_API_KEY` environment variable. If you omit `environment`, the client connects to live mode. A test mode API key works only with `environment="test_mode"`.

### Asynchronous Client

`AsyncDodoPayments` has the same methods as `DodoPayments`. Await each call:

```python theme={null}
import os
import asyncio
from dodopayments import AsyncDodoPayments

client = AsyncDodoPayments(
    bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"),
    environment="test_mode",
)


async def main() -> None:
    checkout_session_response = await client.checkout_sessions.create(
        product_cart=[
            {
                "product_id": "pdt_123",
                "quantity": 1,
            }
        ],
    )
    print(checkout_session_response.session_id)


asyncio.run(main())
```

<Warning>
  Keep API keys in environment variables or a secrets manager. Never commit them to version control.
</Warning>

## Core Features

<CardGroup cols={2}>
  <Card title="Pythonic Interface" icon="code">
    Keyword arguments for parameters, `TypedDict` types for nested objects, and Pydantic models for responses.
  </Card>

  <Card title="Async/Await" icon="bolt">
    `AsyncDodoPayments` for asyncio, with aiohttp as an optional HTTP backend.
  </Card>

  <Card title="Type Hints" icon="check">
    Type hints on every method, for editor autocomplete and type checking with mypy.
  </Card>

  <Card title="Auto-Pagination" icon="arrows-rotate">
    List methods return iterators that fetch the next page as you loop.
  </Card>
</CardGroup>

## Configuration

### Environment Variables

Store your API key in an environment variable:

```bash .env theme={null}
DODO_PAYMENTS_API_KEY=your_api_key_here
```

The client reads these variables when you don't pass the matching argument:

| Variable | Client argument | Purpose |
| - | - | - |
| `DODO_PAYMENTS_API_KEY` | `bearer_token` | Your API key. The client raises an error if neither is set. |
| `DODO_PAYMENTS_WEBHOOK_KEY` | `webhook_key` | Your webhook signing secret, used to verify webhooks. |
| `DODO_PAYMENTS_BASE_URL` | `base_url` | A custom API URL that replaces the `environment` URL. |
| `DODO_PAYMENTS_LOG` | No matching argument | The log level. See [Logging](#logging). |

If `DODO_PAYMENTS_BASE_URL` is set and you also pass `environment`, the constructor raises an "Ambiguous URL" error. To use `environment` in that case, pass `base_url=None`.

To verify a webhook, pass the raw request body and headers to `client.webhooks.unwrap(payload, headers=headers)`. It checks the signature with your webhook key and returns the parsed event. `client.webhooks.unsafe_unwrap(payload)` parses the body without verifying it, so use it only for testing. See [Webhooks](/developer-resources/webhooks).

### Timeouts

Requests time out after 1 minute by default, with a 5-second connection timeout. Pass `timeout` in seconds, or an `httpx.Timeout` for separate read, write, and connect limits:

```python theme={null}
import httpx
from dodopayments import DodoPayments

# Configure default for all requests (default is 1 minute)
client = DodoPayments(
    timeout=20.0,  # 20 seconds
)

# More granular control
client = DodoPayments(
    timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),
)

# Override per-request
client.with_options(timeout=5.0).checkout_sessions.create(
    product_cart=[
        {
            "product_id": "pdt_123",
            "quantity": 1,
        }
    ],
)
```

When a request times out, the SDK raises `APITimeoutError`. Timed-out requests are retried, so a call can take longer than `timeout` before it fails.

### Retries

Set `max_retries` on the client, or on a single request with `with_options()`:

```python theme={null}
from dodopayments import DodoPayments

# Configure default for all requests (default is 2)
client = DodoPayments(
    max_retries=0,  # disable retries
)

# Override per-request
client.with_options(max_retries=5).checkout_sessions.create(
    product_cart=[
        {
            "product_id": "pdt_123",
            "quantity": 1,
        }
    ],
)
```

The SDK retries connection errors and responses with status 408, 409, 429, or 500 and above. It retries twice by default, with exponential backoff. When a request still fails, the SDK raises a subclass of `dodopayments.APIError`:

| Status | Exception |
| - | - |
| 400 | `BadRequestError` |
| 401 | `AuthenticationError` |
| 403 | `PermissionDeniedError` |
| 404 | `NotFoundError` |
| 409 | `ConflictError` |
| 422 | `UnprocessableEntityError` |
| 429 | `RateLimitError` |
| 500 and above | `InternalServerError` |
| No response | `APIConnectionError` |

The status exceptions inherit from `dodopayments.APIStatusError`, which has `status_code` and `response` attributes. `APITimeoutError` is a subclass of `APIConnectionError`.

## Common Operations

The examples in this section use the `client` from [Quick Start](#quick-start).

### Create a Checkout Session

Create a checkout session, then redirect the customer to the returned `checkout_url`:

```python theme={null}
session = client.checkout_sessions.create(
    product_cart=[
        {
            "product_id": "pdt_123",
            "quantity": 1
        }
    ],
    return_url="https://yourdomain.com/return"
)

print(f"Checkout URL: {session.checkout_url}")
```

Each `checkout_url` works once and expires after 24 hours. For every session option, see [Checkout Sessions](/developer-resources/checkout-session).

### Manage Customers

Create a customer with an email address and name, then retrieve it by ID:

```python theme={null}
# Create a customer
customer = client.customers.create(
    email="customer@example.com",
    name="John Doe",
    metadata={
        "user_id": "12345"
    }
)

# Retrieve customer
customer = client.customers.retrieve("cus_123")
print(f"Customer: {customer.name} ({customer.email})")
```

### Handle Subscriptions

Create a subscription, charge an on-demand subscription, and read a subscription's usage history.

<Warning>
  `POST /subscriptions` (the SDK's `subscriptions.create` method) is **deprecated**. It still works for existing integrations, but new integrations should create subscriptions through a [Checkout Session](/developer-resources/checkout-session).
</Warning>

```python expandable theme={null}
# Create a subscription
subscription = client.subscriptions.create(
    billing={
        "country": "US",
        "city": "San Francisco",
        "state": "CA",
        "street": "1 Market St",
        "zipcode": "94105",
    },
    customer={"customer_id": "cus_123"},  # or {"email": "...", "name": "..."} for a new customer
    product_id="pdt_456",
    quantity=1,
)

# Charge an on-demand subscription
# product_price is in the lowest currency denomination (e.g., 2500 = $25.00 USD)
charge_response = client.subscriptions.charge(
    subscription_id=subscription.subscription_id,
    product_price=2500,
)

# Retrieve usage history (for metered subscriptions)
usage_history = client.subscriptions.retrieve_usage_history(
    subscription_id=subscription.subscription_id,
    start_date="2024-01-01T00:00:00Z",
)
```

<Info>
  `billing` requires only `country`, a two-letter ISO country code. `customer` takes `{"customer_id": ...}` to attach an existing customer or `{"email": ..., "name": ...}` to create one. `charge` is for [on-demand subscriptions](/developer-resources/ondemand-subscriptions), and `product_price` is in the smallest currency unit. `retrieve_usage_history` returns a paginated list, which you can iterate as shown in [Pagination](#pagination).
</Info>

## Usage-Based Billing

### Ingest Usage Events

Send usage events for a customer:

```python theme={null}
from datetime import datetime, timezone

response = client.usage_events.ingest(
    events=[
        {
            "event_id": "api_call_12345",
            "customer_id": "cus_abc123",
            "event_name": "api_request",
            "timestamp": datetime.now(timezone.utc),
            "metadata": {
                "endpoint": "/api/v1/users",
                "method": "GET",
                "tokens_used": "150"
            }
        }
    ]
)
```

<Info>
  The `event_id` is the idempotency key, so give each event a unique value. If the same `event_id` appears twice in one request, the whole request is rejected. If an `event_id` was already ingested, the new event is ignored. A request accepts up to 1,000 events. `timestamp` defaults to the current time and is rejected if it's more than 1 hour in the past or more than 5 minutes in the future.
</Info>

### List and Retrieve Events

Retrieve a single event by its `event_id`, or list events filtered by customer and event name:

```python theme={null}
# Get a specific event
event = client.usage_events.retrieve("api_call_12345")

# List events with filtering
events = client.usage_events.list(
    customer_id="cus_abc123",
    event_name="api_request",
    page_size=20
)

for event in events.items:
    print(f"Event: {event.event_id} at {event.timestamp}")
```

`usage_events.list` also accepts `meter_id`, `start`, and `end` filters.

## Pagination

### Auto-Pagination

List methods return an iterator that fetches the next page as you loop:

```python theme={null}
from dodopayments import DodoPayments

client = DodoPayments()
all_payments = []

# Automatically fetches more pages as needed
for payment in client.payments.list():
    all_payments.append(payment)
print(all_payments)
```

### Async Pagination

With the async client, loop with `async for`:

```python theme={null}
import asyncio
from dodopayments import AsyncDodoPayments

client = AsyncDodoPayments()


async def main() -> None:
    all_payments = []
    # Iterate through items across all pages
    async for payment in client.payments.list():
        all_payments.append(payment)
    print(all_payments)


asyncio.run(main())
```

### Manual Pagination

To work with one page at a time, read `items` and call `has_next_page()` and `get_next_page()`. `next_page_info()` returns the parameters for the next request:

```python theme={null}
# Access items from current page
first_page = client.payments.list()
for payment in first_page.items:
    print(payment.brand_id)

# Check for more pages
if first_page.has_next_page():
    next_page = first_page.get_next_page()
    print(f"Fetched {len(next_page.items)} more items")
```

## HTTP Client Configuration

To add a proxy, a custom transport, or other `httpx` settings, pass your own `http_client`. `DefaultHttpxClient` keeps the SDK's default connection limits, timeout, and redirect settings:

```python theme={null}
import httpx
from dodopayments import DodoPayments, DefaultHttpxClient

client = DodoPayments(
    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"),
    ),
)
```

To use a different HTTP client for one request, call `client.with_options(http_client=...)`.

## Async with AIOHTTP

By default, the async client sends requests with `httpx`. For better concurrency, install the `aiohttp` extra and pass `DefaultAioHttpClient()` as `http_client`:

```python theme={null}
import os
import asyncio
from dodopayments import DefaultAioHttpClient
from dodopayments import AsyncDodoPayments


async def main() -> None:
    async with AsyncDodoPayments(
        bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"),
        http_client=DefaultAioHttpClient(),
    ) as client:
        checkout_session_response = await client.checkout_sessions.create(
            product_cart=[
                {
                    "product_id": "pdt_123",
                    "quantity": 1,
                }
            ],
        )
        print(checkout_session_response.session_id)


asyncio.run(main())
```

## Logging

The SDK logs with the standard library `logging` module. To turn on logging, set `DODO_PAYMENTS_LOG` to `info`:

```bash theme={null}
export DODO_PAYMENTS_LOG=info
```

For more detail, set it to `debug`:

```bash theme={null}
export DODO_PAYMENTS_LOG=debug
```

## Framework Integration

These examples create a checkout session from a web endpoint and return its URL.

### FastAPI

This endpoint uses the async client:

```python theme={null}
from fastapi import FastAPI, HTTPException
from dodopayments import AsyncDodoPayments
from pydantic import BaseModel
import os

app = FastAPI()
dodo = AsyncDodoPayments(bearer_token=os.getenv("DODO_PAYMENTS_API_KEY"))

class CheckoutRequest(BaseModel):
    product_id: str
    quantity: int

@app.post("/create-checkout")
async def create_checkout(request: CheckoutRequest):
    try:
        session = await dodo.checkout_sessions.create(
            product_cart=[{
                "product_id": request.product_id,
                "quantity": request.quantity
            }],
            return_url="https://yourdomain.com/return"
        )
        return {"checkout_url": session.checkout_url}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))
```

### Django

This view uses the sync client:

```python theme={null}
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
from dodopayments import DodoPayments
import os
import json

client = DodoPayments(bearer_token=os.getenv("DODO_PAYMENTS_API_KEY"))

@csrf_exempt
@require_POST
def create_checkout(request):
    try:
        data = json.loads(request.body)
        session = client.checkout_sessions.create(
            product_cart=[{
                "product_id": data.get("product_id"),
                "quantity": data.get("quantity", 1)
            }],
            return_url="https://yourdomain.com/return"
        )
        return JsonResponse({
            "status": "success",
            "checkout_url": session.checkout_url,
            "session_id": session.session_id
        })
    except Exception as e:
        return JsonResponse({
            "status": "error",
            "message": str(e)
        }, status=400)
```

## Resources

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-python">
    Source code, releases, and the full method list.
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Every endpoint, parameter, and response.
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    Ask questions and talk with other developers.
  </Card>

  <Card title="Report Issues" icon="bug" href="https://github.com/dodopayments/dodopayments-python/issues">
    Report bugs or request features.
  </Card>
</CardGroup>

## Support

For help with the Python SDK:

* **Discord**: Join the [community server](https://discord.gg/bYqAp4ayYh) for real-time help.
* **Email**: Contact [support@dodopayments.com](mailto:support@dodopayments.com).
* **GitHub**: Open an issue on the [repository](https://github.com/dodopayments/dodopayments-python).

## Contributing

To contribute, read the [contributing guidelines](https://github.com/dodopayments/dodopayments-python/blob/main/CONTRIBUTING.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.