# Ruby SDK

`rasket`: a client for Ruby 3.3 and later, over Net::HTTP, with RBS signatures. 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 gem is not published yet. There is nothing to install from RubyGems 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:

```ruby
require "rasket"

rasket = Rasket::Client.new(api_key: ENV.fetch("RASKET_API_KEY"), user_agent: "acme-billing/1.0")

sent = rasket.emails.send(
  {
    from: "Acme <billing@acme.example>",
    to: ["ronald.williams@example.com"],
    subject: "Your receipt",
    html: "<p>Thanks.</p>"
  },
  idempotency_key: "receipt-1042"
)

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

```ruby
result = rasket.emails.get(email_id)

result.body                # the parsed body, symbol keys
result.rate_limit          # RateLimit(limit: 10, remaining: ..., reset_seconds: ...)
result.request_id          # the x-request-id to quote
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. Each segment is in snake_case. Path parameters come first, then the body as a Hash with symbol or string keys; a query is `query:`, and every method takes `timeout:`. Responses are parsed with symbol keys, and a `nil` in a body is sent as `null`.

| Node | Ruby |
| --- | --- |
| `emails.send` | `rasket.emails.send(body, idempotency_key: ...)` |
| `webhooks.rotateSecret` | `rasket.webhooks.rotate_secret(webhook_id)` |
| `domains.regenerateDkim` | `rasket.domains.regenerate_dkim(domain_id, body)` |
| `emails.receiving.attachments.list` | `rasket.emails.receiving.attachments.list(email_id, query: ...)` |

## Every page of a list

Walk every page:

```ruby
rasket.domains.list_all(query: { limit: 100 }).each do |domain|
  puts domain[:name]
end
```

Every list method that pages has an `_all` twin, an Enumerator that asks for the next page with the last item's id as `after`, only as you read.

## Idempotency

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

```ruby
begin
  rasket.emails.send(message)
rescue Rasket::ApiError => e
  case e.name
  when Rasket::ErrorNames::VALIDATION_ERROR then reject(e.errors) # [ValidationIssue(path:, message:)]
  when Rasket::ErrorNames::RATE_LIMIT_EXCEEDED then later(e.rate_limit&.retry_after_seconds)
  else raise # e.status_code, e.message, e.request_id
  end
rescue Rasket::ConnectionError => e
  e.reason # :network or :timeout: no answer arrived
end
```

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:

```ruby
rasket = Rasket::Client.new(
  api_key: api_key,
  timeout: 30,
  retry_attempts: 3, retry_min_delay: 0.5, retry_max_delay: 8
)
```

`retry_attempts: 1` turns retrying off. The timeout and both delays are in seconds, and the timeout applies to each attempt.

## Verifying a webhook

Verify in a Rails controller:

```ruby
class RasketWebhooksController < ApplicationController
  skip_forgery_protection

  def create
    event = Rasket::Webhooks.verify(request.raw_post, request.headers, ENV.fetch("RASKET_WEBHOOK_SECRET"))
    handle(event)
    head :ok
  rescue Rasket::WebhookVerificationError
    head :bad_request
  end
end
```

> The signature covers the raw request body: `request.raw_post` in Rails, `request.body.read` in Rack or Sinatra, never `params`. A Rack env works as the headers. `rasket.webhooks.verify` is the same check.

## Worth knowing

- Pass any object with a `call` method as `transport:` to send through your own HTTP stack.
- 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), [Java](https://www.rasket.com/docs/sdk/java), [.NET](https://www.rasket.com/docs/sdk/dotnet) and [Rust](https://www.rasket.com/docs/sdk/rust).
