Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions .claude/skills/api-toolbox-development/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
---
name: api-toolbox-development
description: Build Laravel APIs with juststeveking/api-toolbox. Use when returning API errors (RFC 9457 problem details, make:api-problem), adding ETags, preconditions or caching, cursor pagination, idempotency keys, Prefer or async 202 operations, JSON Merge Patch, Content-Digest, signing or verifying webhooks (HTTP Message Signatures), deprecating endpoints, the API catalog, 406/415 negotiation, request IDs, or testing any of these.
---

# API Toolbox Development

## When to use this skill

Use this skill when you write or change an API endpoint in an application that requires `juststeveking/api-toolbox`, or when you test one. Each feature implements a published HTTP standard. Use the feature rather than inventing a header, query parameter or JSON shape for something a standard already covers.

## First: which features are on

Read `config/api-toolbox.php`. Features are listed in `features` with options passed inline:

```php
use JustSteveKing\Toolbox\Features;

'features' => [
Features::problemDetails(['type_base_uri' => 'https://docs.example.com/problems']),
Features::conditionalRequests(),
Features::idempotency(['ttl' => 86400]),
// ...
],
```

- If the file does not exist, every stable feature is on with its defaults. `Features::rateLimitHeaders()` is experimental and is off unless listed.
- A disabled feature registers nothing: no middleware alias, route, container binding, Artisan command or test assertion. Using one of those for a disabled feature fails. To enable a feature, add it to the list; do not register its pieces by hand.
- Check at runtime with `JustSteveKing\Toolbox\Facades\ApiToolbox::enabled(Features::idempotency())`, or inject `JustSteveKing\Toolbox\Contracts\EnabledFeatures`.
- Features built on an IETF draft that is still changing are experimental and may break in a minor release. Today that is RateLimit headers only.

## Choose the reference for the task

| Task | Read |
|---|---|
| Returning an error, a custom error type, validation errors, `make:api-problem` | [references/problem-details.md](references/problem-details.md) |
| ETags, 304, 412, 428, `Cache-Control`, cursor pagination | [references/caching-and-pagination.md](references/caching-and-pagination.md) |
| PATCH, `Prefer`, idempotent POST, 202 Accepted and background jobs | [references/writes.md](references/writes.md) |
| Signing or verifying webhooks and requests, `Content-Digest` | [references/signatures-and-digests.md](references/signatures-and-digests.md) |
| Deprecating or sunsetting endpoints, the API catalog, 406/415, request IDs, tracing, rate limits | [references/api-lifecycle.md](references/api-lifecycle.md) |
| Writing tests for any of the above | [references/testing.md](references/testing.md) |

## Middleware aliases

| Alias | Feature | Does |
|---|---|---|
| `conditional` | Conditional Requests | `preconditions` then `validators` |
| `preconditions` | Conditional Requests | Evaluates `If-*` headers: 412 or 304 |
| `validators` | Conditional Requests | Adds `ETag` and `Last-Modified`; `validators:weak` for a weak hash |
| `preconditions.required` | Conditional Requests | 428 without a precondition; `preconditions.required:PUT,POST` |
| `idempotent` | Idempotency | Honours `Idempotency-Key`; `idempotent:required` for 400 without one |
| `prefer` | Preferences | `return=minimal` and `Preference-Applied`, with `Vary: Prefer` |
| `merge-patch` | Merge Patch | 415 with `Accept-Patch` for any other PATCH format |
| `digest.verify` | Digest Fields | Checks `Content-Digest`/`Repr-Digest`; `digest.verify:required` |
| `digest.respond` | Digest Fields | Adds digests a client asks for; `digest.respond:always` |
| `signature.verify` | Message Signatures | 401 without a valid signature |
| `signature.sign` | Message Signatures | Signs the response; `signature.sign:key-id` |
| `deprecation` | Deprecation | Only needed when the feature's `global` option is off |
| `api-catalog.link` | API Catalog | Adds `Link: <...>; rel="api-catalog"` |
| `produces` | Negotiation | 406; `produces:application/json` |
| `consumes` | Negotiation | 415; `consumes:application/json,application/merge-patch+json` |

Request IDs and trace context run globally, and RateLimit headers replace Laravel's `throttle` middleware. None of them needs adding to routes.

## Rules that apply everywhere

- Never build error JSON by hand in an API route. Throw; the package renders `application/problem+json`.
- Every problem the package raises is typed from the apiguide.dev catalogue. Reuse `JustSteveKing\Toolbox\Support\ApiGuide` constants for your own problems where an entry fits, rather than inventing a type that means the same thing.
- Do not add `X-` headers for things these standards cover: `Idempotency-Key`, `Prefer`/`Preference-Applied`, `Deprecation`/`Sunset`, `RateLimit`/`RateLimit-Policy`, `Content-Digest`, `Signature`/`Signature-Input`, `traceparent`.
- Order of route middleware does not matter for this package's middleware: it registers its own priority, so `preconditions.required` runs before `preconditions`, and `idempotent` runs after authentication.
79 changes: 79 additions & 0 deletions .claude/skills/api-toolbox-development/references/api-lifecycle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# API lifecycle: deprecation, catalog, negotiation, request IDs and rate limits

## Deprecation and Sunset (RFC 9745, RFC 8594)

Feature: `Features::deprecation()`. Mark a controller or a single action with attributes:

```php
use JustSteveKing\Toolbox\Deprecation\Attributes\Deprecation;
use JustSteveKing\Toolbox\Deprecation\Attributes\Sunset;

#[Deprecation(at: '2026-06-30T23:59:59Z', link: 'https://docs.example.com/deprecations/orders-v1')]
#[Sunset(at: '2027-01-01T00:00:00Z', link: 'https://docs.example.com/sunset-policy')]
final class OrderController
{
#[Deprecation(at: '2026-03-01')]
public function export() { /* ... */ }
}
```

- These are not PHP's `#[\Deprecated]`, which would raise a PHP deprecation on every request. Import them from `JustSteveKing\Toolbox\Deprecation\Attributes`.
- Only controller routes are read. Closure routes are not, because `route:cache` breaks their attributes. Move a closure route to a controller to deprecate it.
- A date without an offset is UTC. A deprecation date can be in the future. A sunset earlier than the deprecation throws.
- `#[Deprecation(link: ...)]` with no date publishes a deprecation policy only.
- With the `global` option on (the default), nothing is added to routes. With it off, add the `deprecation` middleware.
- Reading deprecations from elsewhere, such as a manifest: bind `JustSteveKing\Toolbox\Deprecation\Contracts\DeprecationSource`, which returns a `JustSteveKing\Toolbox\Deprecation\Notice` for a route.

## API catalog (RFC 9727)

Feature: `Features::apiCatalog([...])`. It serves `/.well-known/api-catalog`, listing the APIs and where their OpenAPI descriptions and documentation live.

```php
Features::apiCatalog([
'apis' => [
[
'href' => '/api/v1',
'service-desc' => ['href' => '/openapi.json', 'type' => 'application/vnd.oai.openapi+json'],
'service-doc' => ['href' => 'https://docs.example.com', 'type' => 'text/html'],
'status' => '/api/v1/health',
],
],
'middleware' => ['throttle:60,1'],
]),
```

- `href` is the API itself. `service-desc` is a machine-readable description, `service-doc` documentation for people, `service-meta` policies and other metadata, and `status` a health endpoint.
- The catalog is public. List only APIs meant to be found, never internal ones.
- Point to it from an API root with the `api-catalog.link` middleware.
- To build it from a database or gateway, bind `JustSteveKing\Toolbox\ApiCatalog\Contracts\CatalogSource`.

## Negotiation: 406 and 415

Feature: `Features::negotiation()`.

```php
Route::post('leads', CreateLead::class)->middleware(['produces:application/json', 'consumes:application/json']);
Route::patch('leads/{lead}', UpdateLead::class)->middleware('consumes:application/merge-patch+json');
```

- `produces` returns 406 when `Accept` rules out every listed type. A missing `Accept` accepts anything.
- `consumes` returns 415 when the request has content of another type, or content with no `Content-Type`. A request with no content always passes.
- `consumes:application/json` does not accept `application/merge-patch+json`. List each type a route takes.

## Request IDs and tracing

These are on with Negotiation and need no code.

- Every response carries `X-Request-Id`, which can be renamed with the `request_id_header` option. A well-formed incoming ID is kept; otherwise a UUIDv7 is assigned.
- The ID is in the log context as `request_id`, and problem `instance` is `urn:uuid:<id>`. To find the logs for a reported error, search for that ID.
- W3C `traceparent` is continued from the caller, added to the log context and to queued jobs, and sent on with Laravel HTTP client requests. Do not add these headers to outgoing requests by hand.
- Read the current ID by injecting `JustSteveKing\Toolbox\Contracts\RequestIdentifier` and calling `current()`. It returns null when request IDs are off.

## RateLimit headers (experimental)

Feature: `Features::rateLimitHeaders()`. It is off unless listed, and can change in a minor release.

- Keep using Laravel's `throttle` middleware and `RateLimiter::for()`. Responses gain `RateLimit-Policy` and `RateLimit`, and a 429 becomes a `rate-limit-exceeded` problem with `Retry-After` and `Cache-Control: no-store`.
- The policy name is the limiter name. `throttle:60,1` is `"default"`.
- Applications that use `throttleWithRedis()` get no RateLimit headers. This is a known gap.
- For a billing-period allowance rather than a short window, throw a problem typed `ApiGuide::QUOTA_EXCEEDED` instead.
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Conditional requests, caching and pagination

## Conditional requests (RFC 9110 section 13, RFC 6585)

Feature: `Features::conditionalRequests()`. It is opt-in per route.

Use it to prevent lost updates, where two clients edit the same resource and the second write silently overwrites the first, and to answer re-fetches with 304.

### 1. Give the model validators

```php
use JustSteveKing\Toolbox\ConditionalRequests\Concerns\HasModelValidators;
use JustSteveKing\Toolbox\ConditionalRequests\Contracts\HasValidators;

final class Document extends Model implements HasValidators
{
use HasModelValidators;
}
```

The strong ETag comes from the model's class, key and `updated_at`, and `Last-Modified` comes from `updated_at`. Two writes in the same second share a timestamp, so for real optimistic concurrency add an integer `version` column that every write increments, and return it:

```php
protected function entityTagVersion(): ?string
{
return (string) $this->version;
}
```

The model is found through route model binding, so the route parameter must be bound to it.

### 2. Add the middleware

```php
Route::middleware('conditional')->group(function () {
Route::get('documents/{document}', ShowDocument::class);
Route::put('documents/{document}', ReplaceDocument::class)->middleware('preconditions.required');
Route::patch('documents/{document}', UpdateDocument::class)->middleware('preconditions.required');
Route::delete('documents/{document}', DeleteDocument::class)->middleware('preconditions.required');
});
```

- `conditional` = `preconditions` + `validators`.
- `preconditions.required` returns 428 when a PUT, PATCH or DELETE has no `If-Match` or `If-Unmodified-Since`. Name other methods with `preconditions.required:PUT,POST`.
- Laravel 13's `#[Middleware('conditional')]` controller attribute also works.

### What clients see

- `GET` returns `ETag` and `Last-Modified`. A repeat with `If-None-Match` returns 304 with no body.
- `PATCH` with a stale `If-Match` returns 412 `precondition-failed`, carrying the current `ETag` to re-fetch.
- A write without a precondition on a `preconditions.required` route returns 428 `precondition-required`.
- `PUT` with `If-None-Match: *` creates without overwriting.
- Without a bound model, a GET's ETag is a hash of the response content. Use `validators:weak` for a weak one.

Do not add a `version` field to request bodies for locking, and do not compare timestamps in controllers. Preconditions are checked before the controller runs.

## Caching directives

Use Laravel's own `cache.headers` middleware beside `conditional`, and leave its `etag` option off, because `conditional` already sends the ETag:

```php
Route::get('documents/{document}', ShowDocument::class)->middleware([
'conditional',
'cache.headers:public;max_age=60;stale_while_revalidate=30;stale_if_error=86400',
]);
```

## Cursor pagination with Link headers (RFC 8288)

Feature: `Features::pagination()`.

```php
use JustSteveKing\Toolbox\Pagination\CursorPage;

public function index(Request $request)
{
return CursorPage::of(
Post::query()->where('published', true)->orderBy('id')->cursorPaginate(20)->withQueryString(),
PostResource::class,
);
}
```

- The body is a plain JSON array of the items. Navigation is in `Link` headers: `next` and `prev` when they exist, and `first` always. There is no `last`.
- Call `withQueryString()` so filters survive into the links.
- The resource class is optional.
- Use `cursorPaginate()`, not `paginate()`. `CursorPage` takes a `CursorPaginator`.
- A cursor that cannot be decoded is a 400 `invalid-pagination-cursor` for every cursor paginator in the app, not a silent first page.

Clients read `Link: <...>; rel="next"` rather than `links.next` in the body. Do not also add `links` or `meta` to the body.
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# Problem Details (RFC 9457)

Feature: `Features::problemDetails()`. Errors are rendered as `application/problem+json` when the request expects JSON, or when its path matches the `paths` option (default `['api/*']`). Requests using `application/vnd.api+json` are left alone, because JSON:API has its own error format.

## What is rendered without any code

| Exception | Status | `type` |
|---|---|---|
| `ValidationException` | 422 | `https://apiguide.dev/errors/validation-failed`, with `errors` keyed by field |
| `AuthenticationException` | 401 | `https://apiguide.dev/errors/unauthorized`, plus a `WWW-Authenticate` challenge (`Bearer` by default) |
| `abort()`, `ModelNotFoundException`, authorization and any HTTP exception | its own | the apiguide.dev entry for the status (404 is `resource-not-found`), or `about:blank` |
| Anything else | 500 | `https://apiguide.dev/errors/internal-server-error`, with no message unless `app.debug` is on |

So `abort(404)`, `$request->validate()`, `Gate::authorize()` and `findOrFail()` need no extra work. Do not catch them to build a JSON error.

## Your own problem types

Generate the class. Do not write it by hand:

```bash
php artisan make:api-problem OutOfCredit --title="You do not have enough credit." --status=403 --no-interaction
php artisan make:api-problem Billing/CardDeclined --title="The card was declined." --status=402 --no-interaction
php artisan make:api-problem AccountFrozen --apiguide=account-frozen --no-interaction
```

- The class goes in `app/Problems`. `Billing/CardDeclined` makes `App\Problems\Billing\CardDeclined`.
- `--type` takes a slug or an absolute URI. It defaults to the class name in kebab case, resolved against the `type_base_uri` option.
- `--apiguide` sets the type, title and status from an apiguide.dev entry. It cannot be combined with `--title`, `--status` or `--type`.
- Under `--no-interaction` the command fails if the title or status is missing, because RFC 9457 section 4 requires both.

The result:

```php
use JustSteveKing\Toolbox\ProblemDetails\Attributes\ProblemType;
use JustSteveKing\Toolbox\ProblemDetails\ProblemException;

#[ProblemType('out-of-credit', title: 'You do not have enough credit.', status: 403)]
final class OutOfCredit extends ProblemException {}
```

Throw it with the details of this occurrence:

```php
throw new OutOfCredit(
detail: 'Your current balance is 30, but that costs 50.',
extensions: ['balance' => 30, 'accounts' => ['/account/12345']],
instance: '/account/12345/msgs/abc',
);
```

- Type, title and status are fixed on the class; detail, extensions and instance vary per occurrence. Do not put changing text in the title.
- An extension key named `type`, `title`, `status`, `detail` or `instance` throws, because it would replace a standard member.
- `#[ProblemType]` can sit on an abstract parent and be inherited.
- With Negotiation on, `instance` defaults to the request ID as `urn:uuid:...`. A value you pass is kept.

## Using the apiguide.dev catalogue

`JustSteveKing\Toolbox\Support\ApiGuide` has a constant per catalogue entry, such as `ApiGuide::ACCOUNT_FROZEN`, `ApiGuide::QUOTA_EXCEEDED` and `ApiGuide::RESOURCE_NOT_FOUND`. `ApiGuide::types()` lists every type, and `ApiGuide::title($type)` and `ApiGuide::status($type)` give the documented title and status.

```php
use JustSteveKing\Toolbox\Support\ApiGuide;

#[ProblemType(ApiGuide::QUOTA_EXCEEDED, title: 'Quota Exceeded', status: 429)]
final class MonthlyQuotaExceeded extends ProblemException {}
```

Use a catalogue entry when it means what your error means. Otherwise give your own type a slug and point `type_base_uri` at your documentation.

## Mapping exceptions you do not own

Map them in `bootstrap/app.php` rather than catching them in controllers:

```php
// bootstrap/app.php
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->map(PaymentGatewayTimeout::class, fn (PaymentGatewayTimeout $e) => new UpstreamUnavailable(detail: 'The payment provider did not answer.'));
})
```

Your own `render` callbacks run before the package's, so the application can always override a response.

## Options

| Option | Default | Meaning |
|---|---|---|
| `type_base_uri` | `/problems` | Base for slug types |
| `paths` | `['api/*']` | Paths that always get problem details, whatever `Accept` says |
| `apiguide` | `true` | Type plain HTTP errors and validation from the catalogue; `false` uses `about:blank` |
| `www_authenticate` | `Bearer` | The challenge sent with a 401; `false` for none |
| `instance_from_request_id` | `true` | `instance` from the request ID |

To resolve types another way, bind `JustSteveKing\Toolbox\ProblemDetails\Contracts\TypeResolver`.
Loading
Loading