# .NET SDK

`Rasket`: an async, typed client for .NET 8 and .NET 10, on `HttpClient` and `System.Text.Json`, trim- and AOT-safe. 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 NuGet package is not published yet. There is nothing to install from NuGet 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:

```csharp
using Rasket;

using var client = new RasketClient(
    Environment.GetEnvironmentVariable("RASKET_API_KEY")!,
    new RasketClientOptions { UserAgent = "acme-billing/1.0" });

var sent = await client.Emails.SendAsync(new SendEmailRequest
{
    From = "Acme <billing@acme.example>",
    To = "ronald.williams@example.com",
    Subject = "Your receipt",
    Html = "<p>Thanks.</p>",
}, new RequestOptions { IdempotencyKey = "receipt-1042" });

Console.WriteLine(sent.Body.Id);
```

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

## What every call returns

The result:

```csharp
var result = await client.Emails.GetAsync(emailId);

Email email = result.Body;                 // the parsed body, typed per route
RateLimit? limit = result.RateLimit;       // Limit (10), Remaining, ResetSeconds
string? requestId = result.RequestId;      // the x-request-id to quote
bool replayed = result.IdempotentReplayed; // 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. Every method is async and ends in `Async`: path parameters first, then the body or query, then `RequestOptions` and a `CancellationToken`. Optional fields are nullable, and a field the API lets you clear is an `Optional<T>`: `Optional<string>.Null` sends `null`, and a value converts to it implicitly.

| Node | .NET |
| --- | --- |
| `emails.send` | `client.Emails.SendAsync(body, options, ct)` |
| `webhooks.rotateSecret` | `client.Webhooks.RotateSecretAsync(webhookId)` |
| `domains.regenerateDkim` | `client.Domains.RegenerateDkimAsync(domainId, body)` |
| `emails.receiving.attachments.list` | `client.Emails.Receiving.Attachments.ListAsync(emailId, query)` |

## Every page of a list

Walk every page:

```csharp
await foreach (var domain in client.Domains.ListAllAsync(new DomainsListQuery { Limit = 100 }))
{
    Console.WriteLine(domain.Name);
}
```

Every list method that pages has an `AllAsync` twin, an `IAsyncEnumerable` that asks for the next page with the last item's id as `after`. The first error ends the walk.

## Idempotency

Pass `new RequestOptions { IdempotencyKey = ... }` 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:

```csharp
try
{
    await client.Emails.SendAsync(message);
}
catch (RasketApiException error) when (error.Name == ErrorNames.ValidationError)
{
    Reject(error.Errors); // [ValidationIssue { Path = ..., Message = ... }]
}
catch (RasketApiException error) when (error.Name == ErrorNames.RateLimitExceeded)
{
    Later(error.RateLimit?.RetryAfterSeconds);
}
catch (RasketConnectionException error)
{
    // error.Reason is Network or Timeout: no answer arrived
    Log(error.Reason);
}
```

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:

```csharp
using var client = new RasketClient(apiKey, new RasketClientOptions
{
    Timeout = TimeSpan.FromSeconds(30),
    MaxAttempts = 3,
    MinRetryDelay = TimeSpan.FromMilliseconds(500),
    MaxRetryDelay = TimeSpan.FromSeconds(8),
});
```

`MaxAttempts = 1` turns retrying off. The timeout applies to each attempt; cancel the `CancellationToken` to stop the whole call, which throws `OperationCanceledException` rather than a timeout.

## Verifying a webhook

Verify in an ASP.NET Core endpoint:

```csharp
app.MapPost("/webhooks/rasket", async (HttpRequest request) =>
{
    using var buffer = new MemoryStream();
    await request.Body.CopyToAsync(buffer); // the bytes, before anything decodes them
    try
    {
        var payload = Webhook.Verify(
            buffer.ToArray(),
            name => (string?)request.Headers[name],
            Environment.GetEnvironmentVariable("RASKET_WEBHOOK_SECRET")!);
        Handle(payload);
        return Results.Ok();
    }
    catch (WebhookVerificationException)
    {
        return Results.BadRequest("invalid signature");
    }
});
```

> The signature covers the raw request body. Copy `Request.Body` yourself before anything decodes it, and pass those bytes. `client.Webhooks.Verify` is the same check.

## Worth knowing

- Make one `RasketClient` and keep it: it is safe for concurrent use. Pass your own `HttpClient` in `RasketClientOptions.HttpClient` (from `IHttpClientFactory`, say); the client never disposes one it did not make.
- A refusal is a `RasketApiException`; its `Origin` is `ErrorSource.Client` when the client refused before sending, such as an idempotency key that is too long.
- Timestamps are ISO 8601 UTC with milliseconds, as strings.
- `webhooks.get` returns the signing secret masked. It is in the `CreateAsync` and `RotateSecretAsync` 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 [Rust](https://www.rasket.com/docs/sdk/rust).
