# PHP SDK

`rasket/rasket-php`: a client for PHP 8.2 and later, over ext-curl. 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/rasket-php Composer package is not published yet. There is nothing to install from Packagist 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:

```php
<?php

require __DIR__ . '/vendor/autoload.php';

$rasket = new Rasket\Client(getenv('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']);

echo $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:

```php
$result = $rasket->emails->get($emailId);

$result->body;               // the decoded body, an array
$result->rateLimit;          // 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. The method names are the Node client's. Path parameters come first, then the body or query as an array, then an options array. Bodies and responses are arrays with string keys, and a `null` in a body is sent as `null`.

| Node | PHP |
| --- | --- |
| `emails.send` | `$rasket->emails->send($body, $options)` |
| `webhooks.rotateSecret` | `$rasket->webhooks->rotateSecret($webhookId)` |
| `domains.regenerateDkim` | `$rasket->domains->regenerateDkim($domainId, $body)` |
| `emails.receiving.attachments.list` | `$rasket->emails->receiving->attachments->list($emailId, $query)` |

## Every page of a list

Walk every page:

```php
foreach ($rasket->domains->listAll(['limit' => 100]) as $domain) {
    echo $domain['name'], "\n";
}
```

Every list method that pages has an `All` twin, a generator 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:

```php
use Rasket\ErrorName;
use Rasket\Exception\ApiException;
use Rasket\Exception\ConnectionException;

try {
    $rasket->emails->send($message);
} catch (ApiException $error) {
    if ($error->name === ErrorName::VALIDATION_ERROR) {
        reject($error->errors); // list of ValidationIssue, each with ->path and ->message
    } elseif ($error->name === ErrorName::RATE_LIMIT_EXCEEDED) {
        later($error->rateLimit?->retryAfterSeconds);
    } else {
        throw $error; // ->statusCode, ->getMessage(), ->requestId
    }
} catch (ConnectionException $error) {
    // $error->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:

```php
$rasket = new Rasket\Client($apiKey, [
    'timeout' => 30,
    'retry' => ['attempts' => 3, 'min_delay' => 0.5, 'max_delay' => 8],
]);
```

`'attempts' => 1` turns retrying off. The timeout and both delays are in seconds, and the timeout applies to each attempt.

## Verifying a webhook

Verify a delivery:

```php
use Rasket\Exception\WebhookVerificationException;
use Rasket\Webhooks;

$raw = file_get_contents('php://input'); // the raw body, never a decoded copy

try {
    $event = Webhooks::verify($raw, getallheaders(), getenv('RASKET_WEBHOOK_SECRET'));
} catch (WebhookVerificationException $error) {
    http_response_code(400);
    exit;
}

handle($event);
```

> The signature covers the raw request body. Read `php://input`, or `$request->getContent()` in Laravel and Symfony, never a decoded copy. `$rasket->webhooks->verify` is the same check.

## Worth knowing

- Pass a `Rasket\Transport` 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 `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), [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).
