# Java SDK

`com.rasket:rasket-java`: a typed, thread-safe client for Java 11 and later, on the JDK alone. 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 com.rasket:rasket-java Maven package is not published yet. There is nothing to install from Maven Central 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:

```java
import com.rasket.RasketClient;
import com.rasket.RequestOptions;
import com.rasket.Response;
import com.rasket.models.SendEmailRequest;
import com.rasket.models.SendEmailResponse;

RasketClient client = RasketClient.builder(System.getenv("RASKET_API_KEY"))
    .userAgent("acme-billing/1.0")
    .build();

Response<SendEmailResponse> sent = client.emails().send(
    new SendEmailRequest()
        .from("Acme <billing@acme.example>")
        .to("ronald.williams@example.com")
        .subject("Your receipt")
        .html("<p>Thanks.</p>"),
    RequestOptions.idempotencyKey("receipt-1042"));
System.out.println(sent.body().getId());
```

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

## What every call returns

The result:

```java
Response<Email> result = client.emails().get(emailId);

result.body();               // the parsed body, typed per route (an Email here)
result.rateLimit();          // RateLimit{limit=..., remaining=..., resetSeconds=...}
result.requestId();          // the x-request-id to quote
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. Each namespace is a method (`client.emails().receiving()`), and each call takes its path parameters, then the body or query model, then an optional `RequestOptions`. Models are built with fluent setters; a setter given `null` leaves an ordinary field out and sends `null` for a field the API lets you clear.

| Node | Java |
| --- | --- |
| `emails.send` | `client.emails().send(body, options)` |
| `webhooks.rotateSecret` | `client.webhooks().rotateSecret(webhookId)` |
| `domains.regenerateDkim` | `client.domains().regenerateDkim(domainId, body)` |
| `emails.receiving.attachments.list` | `client.emails().receiving().attachments().list(emailId, query)` |

## Every page of a list

Walk every page:

```java
for (ListDomainsItem domain : client.domains().listAll(new DomainsListQuery().limit(100))) {
  System.out.println(domain.getName());
}
```

Every list method that pages has a `listAll` twin, a lazy `Iterable` that asks for the next page with the last item's id as `after`. The first error is thrown from the loop and ends the walk.

## Idempotency

Pass `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:

```java
try {
  client.emails().send(email, RequestOptions.idempotencyKey("receipt-1042"));
} catch (RasketApiException e) {
  if (ErrorNames.VALIDATION_ERROR.equals(e.name())) {
    reject(e.errors()); // List<ValidationIssue>: path(), message()
  } else if (ErrorNames.RATE_LIMIT_EXCEEDED.equals(e.name())) {
    later(e.rateLimit().retryAfterSeconds());
  }
} catch (RasketConnectionException e) {
  // e.reason() is NETWORK or TIMEOUT: no answer arrived
}
```

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:

```java
RasketClient client = RasketClient.builder(apiKey)
    .timeout(Duration.ofSeconds(30))
    .retry(3, Duration.ofMillis(500), Duration.ofSeconds(8))
    .build();
```

`.retry(1, Duration.ZERO, Duration.ZERO)` turns retrying off. The timeout covers each attempt's headers and body together.

## Verifying a webhook

Verify in a JDK HttpServer handler:

```java
server.createContext("/webhooks/rasket", exchange -> {
  byte[] raw = exchange.getRequestBody().readAllBytes(); // the bytes, before anything decodes them
  try {
    Object event = Webhook.verify(
        raw,
        name -> exchange.getRequestHeaders().getFirst(name),
        System.getenv("RASKET_WEBHOOK_SECRET"));
    handle(event);
    exchange.sendResponseHeaders(204, -1);
  } catch (WebhookVerificationException e) {
    exchange.sendResponseHeaders(400, -1);
  }
  exchange.close();
});
```

> The signature covers the raw request body. Read the bytes yourself before anything decodes them, and pass those. A servlet passes `request::getHeader`; a `Map` of headers works too. `client.webhooks().verify` is the same check.

## Worth knowing

- Every exception is unchecked and extends `RasketException`. Pass your own `java.net.http.HttpClient` with `.httpClient(…)`.
- An idempotency key must be printable ASCII here: the JDK's HTTP client cannot send other characters in a header, so the client refuses such a key before sending.
- Timestamps are ISO 8601 UTC with milliseconds, as strings.
- `webhooks.get` returns the signing secret masked. It is in the `create` and `rotateSecret` 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), [.NET](https://www.rasket.com/docs/sdk/dotnet) and [Rust](https://www.rasket.com/docs/sdk/rust).
