> ## 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.

# Rust

> Integrate Dodo Payments into your Rust applications with an async-first, strongly typed SDK built on Tokio and reqwest

The Rust SDK provides convenient, async-first access to the Dodo Payments REST API from applications written in Rust. It offers strongly typed requests and responses, built-in pagination helpers, and configurable timeouts and environments.

## Installation

Add the SDK to your project with Cargo:

```bash theme={null}
cargo add dodopayments
```

Or add it to your `Cargo.toml` manually:

```toml theme={null}
[dependencies]
dodopayments = "1.106.0"
tokio = { version = "1", features = ["full"] }
serde_json = "1"
futures = "0.3" # required for streaming paginated results
```

<Info>
  The SDK requires Rust 1.75 or later, leveraging modern async features for optimal performance.
</Info>

## Quick Start

The client reads your API key from the `DODO_PAYMENTS_API_KEY` environment variable by default. Initialize the client and create your first checkout session:

```rust theme={null}
use dodopayments::Client;

#[tokio::main]
async fn main() -> dodopayments::Result<()> {
    let client = Client::from_env()?;

    let result = client
        .checkout_sessions()
        .create()
        .body(dodopayments::models::CheckoutSessionsCreateParams {
            product_cart: Some(vec![dodopayments::models::ProductItemReq {
                product_id: "product_id".to_string(),
                quantity: 1,
                addons: None,
                amount: None,
                credit_entitlements: None,
            }]),
            ..Default::default()
        })
        .await?;

    println!("{result:?}");
    Ok(())
}
```

<Warning>
  Always store your API keys securely using environment variables. Never hardcode them in your source code.
</Warning>

## Core Features

<CardGroup cols={2}>
  <Card title="Async First" icon="bolt">
    Built on Tokio and reqwest with `async`/`await` support throughout
  </Card>

  <Card title="Strong Typing" icon="shield-check">
    Strongly typed requests and responses for compile-time safety
  </Card>

  <Card title="Auto-Pagination" icon="layer-group">
    Stream every item across pages or advance one page at a time
  </Card>

  <Card title="Configurable" icon="sliders">
    Configure environments, timeouts, and base URLs per client
  </Card>
</CardGroup>

## Configuration

### Environment Variables

By default, `Client::from_env()` reads your API key from the `DODO_PAYMENTS_API_KEY` environment variable and uses the default base URL unless you set `DODO_PAYMENTS_BASE_URL`:

```bash theme={null}
export DODO_PAYMENTS_API_KEY="your_api_key"
export DODO_PAYMENTS_BASE_URL="https://test.dodopayments.com" # optional
```

You can also configure the client explicitly. `Client::new` returns a `Result`, so unwrap it with `?` inside a function that returns `dodopayments::Result`:

```rust theme={null}
use dodopayments::{Client, ClientConfig};

#[tokio::main]
async fn main() -> dodopayments::Result<()> {
    let client = Client::new(
        ClientConfig::new("https://live.dodopayments.com").with_api_key("My API Key"),
    )?;
    println!("{}", client.base_url());
    Ok(())
}
```

### Environments

| Name        | Base URL                        |
| ----------- | ------------------------------- |
| `live_mode` | `https://live.dodopayments.com` |
| `test_mode` | `https://test.dodopayments.com` |

The default base URL is `https://live.dodopayments.com`. Select another environment with the `Environment` enum instead of hard-coding URLs:

```rust theme={null}
use dodopayments::{Client, ClientConfig, Environment};

let client = Client::new(
    ClientConfig::from_environment(Environment::TestMode).with_api_key("My API Key"),
)?;
```

To keep reading the API key from `DODO_PAYMENTS_API_KEY` via `from_env()` while targeting a non-default environment, override it on the config:

```rust theme={null}
use dodopayments::{Client, ClientConfig, Environment};

let client = Client::new(ClientConfig::from_env()?.with_environment(Environment::TestMode))?;
```

### Timeouts

The default request timeout is 30 seconds. Override it per client:

```rust theme={null}
use std::time::Duration;
use dodopayments::{Client, ClientConfig};

let client = Client::new(
    ClientConfig::new("https://live.dodopayments.com")
        .with_api_key("My API Key")
        .with_timeout(Duration::from_secs(60)),
)?;
```

## Common Operations

### Create a Checkout Session

Generate a checkout session:

```rust theme={null}
let session = client
    .checkout_sessions()
    .create()
    .body(dodopayments::models::CheckoutSessionsCreateParams {
        product_cart: Some(vec![dodopayments::models::ProductItemReq {
            product_id: "prod_123".to_string(),
            quantity: 1,
            addons: None,
            amount: None,
            credit_entitlements: None,
        }]),
        return_url: Some("https://yourdomain.com/return".to_string()),
        ..Default::default()
    })
    .await?;

println!("{session:?}");
```

### Manage Customers

Create and retrieve customer information:

```rust theme={null}
// Create a customer
let customer = client
    .customers()
    .create()
    .body(dodopayments::models::CustomerCreateParams {
        email: "customer@example.com".to_string(),
        name: "John Doe".to_string(),
        ..Default::default()
    })
    .await?;

// Retrieve a customer
let customer = client
    .customers()
    .retrieve("cus_123")
    .await?;

println!("{customer:?}");
```

### Handle Subscriptions

Create and manage recurring subscriptions:

```rust theme={null}
let subscription = client
    .subscriptions()
    .create()
    .body(dodopayments::models::SubscriptionCreateParams {
        billing: dodopayments::models::BillingAddress {
            country: "US".to_string(),
            city: "San Francisco".to_string(),
            state: "CA".to_string(),
            street: "1 Market St".to_string(),
            zipcode: "94105".to_string(),
        },
        customer: dodopayments::models::CustomerRequest::AttachExisting(
            dodopayments::models::AttachExistingCustomer {
                customer_id: "cus_123".to_string(),
            },
        ),
        product_id: "pdt_456".to_string(),
        quantity: 1,
        ..Default::default()
    })
    .await?;

println!("{subscription:?}");
```

<Info>
  `billing` requires at minimum the two-letter ISO `country` code. `customer` is a `CustomerRequest` enum — pass `AttachExisting` for an existing customer or `New` for a new one. Amount fields such as `product_price` are in the lowest currency denomination (e.g., `2500` = \$25.00 USD).
</Info>

## Usage-Based Billing

### Ingest Usage Events

Track custom events:

```rust theme={null}
let response = client
    .usage_events()
    .ingest()
    .body(dodopayments::models::UsageEventsIngestParams {
        events: vec![dodopayments::models::EventInput {
            event_id: "api_call_12345".to_string(),
            customer_id: "cus_abc123".to_string(),
            event_name: "api_request".to_string(),
            ..Default::default()
        }],
    })
    .await?;

println!("{response:?}");
```

### List Usage Events

```rust theme={null}
let events = client
    .usage_events()
    .list()
    .query(serde_json::json!({
        "customer_id": "cus_abc123",
        "event_name": "api_request",
    }))
    .await?;

for event in &events.items {
    println!("{event:?}");
}
```

## Pagination

List endpoints return a typed page whose `items` field holds the current page of results. Stream every item across all pages with `into_stream`:

```rust theme={null}
use futures::StreamExt;

let mut items = Box::pin(
    client
        .payments()
        .list()
        .query(serde_json::json!({}))
        .await?
        .into_stream(),
);

while let Some(item) = items.next().await {
    let item = item?;
    println!("{item:?}");
}
```

Or advance one page at a time with `get_next_page`:

```rust theme={null}
let mut page = client
    .payments()
    .list()
    .query(serde_json::json!({}))
    .await?;

loop {
    for item in &page.items {
        println!("{item:?}");
    }
    match page.get_next_page().await? {
        Some(next) => page = next,
        None => break,
    }
}
```

## Error Handling

Every method returns a `dodopayments::Result<T>`. Failures are represented by the `dodopayments::Error` enum. Match on it to handle API errors distinctly from transport errors:

```rust theme={null}
let result = client
    .checkout_sessions()
    .create()
    .body(dodopayments::models::CheckoutSessionsCreateParams {
        product_cart: Some(vec![dodopayments::models::ProductItemReq {
            product_id: "product_id".to_string(),
            quantity: 1,
            addons: None,
            amount: None,
            credit_entitlements: None,
        }]),
        ..Default::default()
    })
    .await;

match result {
    Ok(value) => println!("{value:?}"),
    Err(dodopayments::Error::Api { status, message }) => {
        eprintln!("API returned {status}: {message}");
    }
    Err(err) => eprintln!("request failed: {err}"),
}
```

## Undocumented Endpoints

To call an endpoint not yet exposed as a typed method, use the low-level `request` builder, which applies authentication and the base URL:

```rust theme={null}
let response = client
    .request(reqwest::Method::GET, "/some/path")
    .send()
    .await?;
```

## Resources

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-rust">
    View source code and contribute
  </Card>

  <Card title="Crates.io" icon="cube" href="https://crates.io/crates/dodopayments">
    View the published crate and versions
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Complete API documentation
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    Get help and connect with developers
  </Card>
</CardGroup>

## Support

Need help with the Rust SDK?

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

## Contributing

We welcome contributions! Check the [contributing guidelines](https://github.com/dodopayments/dodopayments-rust/blob/main/CONTRIBUTING.md) to get started.
