# Rust SDK

`rasket`: an async, typed client for Rust 1.88 and later, on tokio. Its types and methods are generated from the same document the API is validated against, so it has the Node client's methods and cannot drift from them.

> The rasket crate is not published yet. There is nothing to install from crates.io yet. Until there is, call the REST API with any HTTP client, as below, or connect an agent over [MCP](https://www.rasket.com/docs/mcp). The rest of this page describes the client as it will ship.

## Today: the REST API

Every endpoint in the [API reference](https://www.rasket.com/docs/api-reference/emails) has a cURL tab. This is the first send:

Send an email:

```sh
curl -X POST "https://api.rasket.com/emails" \
  -H "Authorization: Bearer $RASKET_API_KEY" \
  -H "User-Agent: acme-billing/1.0" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: order-1042" \
  -d '{
  "from": "Acme <orders@send.acme.example>",
  "to": ["ronald.williams@example.com"],
  "subject": "Your order has shipped",
  "html": "<p>Order 1042 left the warehouse this morning.</p>"
}'
```

```ts
const response = await fetch("https://api.rasket.com/emails", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.RASKET_API_KEY}`,
    "User-Agent": "acme-billing/1.0",
    "Content-Type": "application/json",
    "Idempotency-Key": "order-1042",
  },
  body: JSON.stringify({
    from: "Acme <orders@send.acme.example>",
    to: ["ronald.williams@example.com"],
    subject: "Your order has shipped",
    html: "<p>Order 1042 left the warehouse this morning.</p>"
  }),
});

const { id } = await response.json();
```

```python
import os

import requests

response = requests.post(
    "https://api.rasket.com/emails",
    headers={
        "Authorization": f"Bearer {os.environ['RASKET_API_KEY']}",
        "User-Agent": "acme-billing/1.0",
        "Idempotency-Key": "order-1042",
    },
    json={
    "from": "Acme <orders@send.acme.example>",
    "to": ["ronald.williams@example.com"],
    "subject": "Your order has shipped",
    "html": "<p>Order 1042 left the warehouse this morning.</p>"
  },
)

id = response.json()["id"]
```

## The first send

Send an email:

```rust
use rasket::{Client, RequestOptions, SendEmailRequest};

#[tokio::main]
async fn main() -> Result<(), rasket::Error> {
    let client = Client::builder(std::env::var("RASKET_API_KEY").unwrap_or_default())
        .user_agent("acme-billing/1.0")
        .build()?;
    let sent = client
        .emails
        .send(
            &SendEmailRequest {
                from: Some("Acme <billing@acme.example>".into()),
                to: "ronald.williams@example.com".into(),
                subject: Some("Your receipt".into()),
                html: Some("<p>Thanks.</p>".into()),
                ..Default::default()
            },
            Some(RequestOptions::new().idempotency_key("receipt-1042")),
        )
        .await?;
    println!("{}", sent.body.id);
    Ok(())
}
```

The client sends a `User-Agent` of its own on every request, because a request without one is refused; what you pass as `.user_agent(…)` is appended to it. Keys start with `rk_`, and an OAuth access token works wherever a key does. On a deployment host, set `.base_url(…)` to `https://<deployment-host>/api/v1`.

## What every call returns

The result:

```rust
let result = client.emails.get(&email_id, None).await?;

let body = result.body; // the parsed body, typed per route (rasket::Email here)
let rate_limit = result.rate_limit; // Some(RateLimit { limit: 10, remaining: .., reset_seconds: .. })
let request_id = result.request_id; // the x-request-id to quote
let replayed = result.idempotent_replayed; // true on a replay of an earlier keyed request
```

One shape for every method. For a list route, the body is the `{ object, has_more, data }` envelope described under [pagination](https://www.rasket.com/docs/pagination).

## The same methods as the Node SDK

This client covers emails (sent and received), batch sends, domains, contacts, segments, broadcasts, webhooks and suppressions: every method the [Node SDK](https://www.rasket.com/docs/sdk/node) has for them. Methods are in snake_case on namespace fields (`client.emails.receiving`). Each takes path parameters as `&str`, then the body (`&T`) or query (`Option<&T>`), then `Option<RequestOptions>`, and is `async`. Optional fields are `Option`s, and a field the API lets you clear is a `rasket::Nullable`: `Nullable::Null` sends `null`.

| Node | Rust |
| --- | --- |
| `emails.send` | `client.emails.send(&body, options).await` |
| `webhooks.rotateSecret` | `client.webhooks.rotate_secret(webhook_id, options).await` |
| `domains.regenerateDkim` | `client.domains.regenerate_dkim(domain_id, &body, options).await` |
| `emails.receiving.attachments.list` | `client.emails.receiving.attachments.list(email_id, query, options).await` |

## Every page of a list

Walk every page:

```rust
let query = rasket::DomainsListQuery {
    limit: Some(100),
    ..Default::default()
};
let mut domains = client.domains.list_all(Some(&query), None);
while let Some(domain) = domains.next().await {
    println!("{}", domain?.name);
}
```

Every list method that pages has an `_all` twin returning a `rasket::Paginator`, which asks for the next page with the last item's id as `after`. The first error ends the walk.

## Idempotency

Pass `RequestOptions::new().idempotency_key(…)` to `emails.send`, `batch.send`, `broadcasts.sendTest` or `contacts.verifications.create`, the routes that take one. The client sends it as it is and never makes one up: a key it invented would make a retry look safe when you never asked for that.

- 1–256 characters, counted as the API counts them. A key outside that range is refused before any request is sent, with the same `400 invalid_idempotency_key` the API would answer.
- Scoped to your team, remembered for 24 hours.

## Errors

Handle an error by name:

```rust
use rasket::error_names::{RATE_LIMIT_EXCEEDED, VALIDATION_ERROR};

match client.emails.send(&email, None).await {
    Ok(sent) => println!("{}", sent.body.id),
    Err(rasket::Error::Api(error)) if error.name == VALIDATION_ERROR => {
        reject(error.errors.unwrap_or_default()); // Vec<rasket::ValidationIssue>
    }
    Err(rasket::Error::Api(error)) if error.name == RATE_LIMIT_EXCEEDED => {
        later(error.rate_limit.and_then(|limit| limit.retry_after_seconds));
    }
    // error.reason is Network or Timeout: no answer arrived
    Err(rasket::Error::Connection(error)) => unreachable_api(error.reason),
    Err(other) => return Err(other),
}
```

The error's name is the API's stable vocabulary, the names the [errors](https://www.rasket.com/docs/errors) page lists, and the client carries each as a constant. The one value outside it is `unknown_error`: the response had no error body of ours.

## Retries

Only what is safe to repeat is retried: a `GET`, or a request with an idempotency key. Those are retried when no answer came, on a `429` that is not a quota, on a `5xx` other than `501`, and on `409 concurrent_idempotent_requests`. `retry-after` is obeyed, and a value above the longest wait is not waited for: the error comes back at once.

The retry settings:

```rust
let client = rasket::Client::builder(api_key)
    .timeout(Duration::from_secs(30))
    .retry(3, Duration::from_millis(500), Duration::from_secs(8))
    .build()?;
```

`.retry(1, Duration::ZERO, Duration::ZERO)` turns retrying off. The timeout applies to each attempt, answer body included; drop the future to stop the whole call.

## Verifying a webhook

Verify in an axum or hyper handler:

```rust
// headers: the request's http::HeaderMap; body: its raw bytes, before anything decodes them.
let secret = std::env::var("RASKET_WEBHOOK_SECRET").unwrap_or_default();
match rasket::webhook::verify(&body, &headers, &secret) {
    Ok(event) => handle(event),
    Err(error) => refuse(error.reason.as_str()),
}
```

> The signature covers the raw request body. Take the body as bytes before anything decodes it, and pass those. `client.webhooks.verify` is the same check; `rasket::webhook::verify_at` takes the time to measure the window against.

## Worth knowing

- `Client` is cheap to clone and safe to share across tasks; pass your own `reqwest::Client` with `.http_client(…)`.
- `rasket::Error` is `#[non_exhaustive]`: match the variants you handle and keep a catch-all arm.
- Timestamps are ISO 8601 UTC with milliseconds, as strings.
- `webhooks.get` returns the signing secret masked. It is in the `create` and `rotate_secret` responses and nowhere else.

## Other languages

The same client, generated from the same document, in [Node.js](https://www.rasket.com/docs/sdk/node), [Python](https://www.rasket.com/docs/sdk/python), [Go](https://www.rasket.com/docs/sdk/go), [PHP](https://www.rasket.com/docs/sdk/php), [Ruby](https://www.rasket.com/docs/sdk/ruby), [Java](https://www.rasket.com/docs/sdk/java) and [.NET](https://www.rasket.com/docs/sdk/dotnet).
