# Go SDK

`github.com/Rasket-HQ/rasket-go`: a typed client for Go 1.24 and later, on the standard library 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 rasket-go module is not published yet. There is nothing to install from the Go module proxy 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:

```go
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/Rasket-HQ/rasket-go"
)

func main() {
	client, err := rasket.NewClient(os.Getenv("RASKET_API_KEY"), rasket.WithUserAgent("acme-billing/1.0"))
	if err != nil {
		log.Fatal(err)
	}
	sent, err := client.Emails.Send(context.Background(), rasket.SendEmailRequest{
		From:    rasket.String("Acme <billing@acme.example>"),
		To:      rasket.Recipients{"ronald.williams@example.com"},
		Subject: rasket.String("Your receipt"),
		HTML:    rasket.String("<p>Thanks.</p>"),
	}, rasket.WithIdempotencyKey("receipt-1042"))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(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 `rasket.WithUserAgent` is appended to it. Keys start with `rk_`, and an OAuth access token works wherever a key does. On a deployment host, set `rasket.WithBaseURL` to `https://<deployment-host>/api/v1`.

## What every call returns

The result:

```go
result, err := client.Emails.Get(ctx, emailID)

result.Body               // the parsed body, typed per route (rasket.Email here)
result.RateLimit          // &rasket.RateLimit{Limit: 10, 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. Every method takes a `context.Context` first, then path parameters, then the body or query struct, then options. Optional fields are pointers (`rasket.String` makes one), and a field the API lets you clear is a `rasket.Nullable`: `rasket.Null` sends `null`.

| Node | Go |
| --- | --- |
| `emails.send` | `client.Emails.Send(ctx, body, opts...)` |
| `webhooks.rotateSecret` | `client.Webhooks.RotateSecret(ctx, webhookID)` |
| `domains.regenerateDkim` | `client.Domains.RegenerateDkim(ctx, domainID, body)` |
| `emails.receiving.attachments.list` | `client.Emails.Receiving.Attachments.List(ctx, emailID, query)` |

## Every page of a list

Walk every page:

```go
for domain, err := range client.Domains.ListAll(ctx, &rasket.DomainsListQuery{Limit: rasket.Int(100)}) {
	if err != nil {
		return err
	}
	fmt.Println(domain.Name)
}
```

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

## Idempotency

Pass `rasket.WithIdempotencyKey` 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:

```go
var apiErr *rasket.APIError
var connErr *rasket.ConnectionError
switch {
case errors.As(err, &apiErr) && apiErr.Name == rasket.ErrValidationError:
	reject(apiErr.Errors) // []rasket.ValidationIssue{{Path: ..., Message: ...}}
case errors.As(err, &apiErr) && apiErr.Name == rasket.ErrRateLimitExceeded:
	later(apiErr.RateLimit.RetryAfterSeconds)
case errors.As(err, &connErr):
	// connErr.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:

```go
client, err := rasket.NewClient(apiKey,
	rasket.WithTimeout(30*time.Second),
	rasket.WithRetry(3, 500*time.Millisecond, 8*time.Second),
)
```

`WithRetry(1, 0, 0)` turns retrying off. The timeout applies to each attempt; cancel the `context` to stop the whole call.

## Verifying a webhook

Verify in a net/http handler:

```go
func receive(w http.ResponseWriter, r *http.Request) {
	raw, err := io.ReadAll(r.Body) // the bytes, before anything decodes them
	if err != nil {
		http.Error(w, "unreadable body", http.StatusBadRequest)
		return
	}
	event, err := rasket.Verify(raw, r.Header, os.Getenv("RASKET_WEBHOOK_SECRET"))
	if err != nil {
		http.Error(w, "invalid signature", http.StatusBadRequest)
		return
	}
	handle(event)
}
```

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

## Worth knowing

- The client is safe for concurrent use; pass your own `*http.Client` with `rasket.WithHTTPClient`.
- 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), [PHP](https://www.rasket.com/docs/sdk/php), [Ruby](https://www.rasket.com/docs/sdk/ruby), [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).
