Documenting endpoints

Sampling

How resources are described by running them on sampled models, and how to help when a resource fails.

A resource is not parsed: it is run. The generator builds a sample of what the resource receives (usually a model), calls toArray() on it, and describes the result. What toArray() returns is therefore exactly what the document says, conditions included.

What a resource receives

The generator finds the model of a resource, in this order:

  1. the type of the constructor parameter of the resource;
  2. @extends JsonResource<Book>, or the model given to a base resource with its own template;
  3. @mixin Book;
  4. #[UseResource] or #[UseResourceCollection] on a model;
  5. the naming convention: App\Http\Resources\BookResource → App\Models\Book.
app/Http/Resources/BookResource.php
/**
 * @mixin Book
 */
final class BookResource extends JsonResource

A collection finds its resource by #[Collects], $collects, @extends ResourceCollection<BookResource> or Laravel's convention (BookCollection → Book, then BookResource).

How a sample is made

The model hasThe sample is
A factory (HasFactory, #[UseFactory])create() inside a transaction rolled back at the end of the generation, or make() when no transaction is open
No factorya model filled with fake values typed by its @property tags, its casts and the columns of its table
A #[ResourceFactory] on the resourcewhat that factory returns

The types of the values come from the @property tags, then the casts (which win on the type), then the nullability of the columns when a database answers. A cast whose JSON depends on the value (array, json, custom casts) declares nothing: the sampled value is read.

app/Models/Book.php
/**
 * @property int $id
 * @property string $title
 * @property \Illuminate\Support\Carbon|null $published_at
 */
final class Book extends Model
{
    protected function casts(): array
    {
        return ['published_at' => 'datetime'];
    }
}
The database is never changed. Factories run inside a transaction opened on the default connection when its driver is in sampling.connections, rolled back at the end of the generation, even when it fails. Models of another connection, or of a driver not listed, are made, never saved. Set sampling.transactions to false to never write.

Required and optional properties

toArray() runs twice: on the sample, then on the sample with its relations loaded.

  • A key returned by both runs is required.
  • A key returned by the second run only (whenLoaded()) is optional, and described.
  • A key computed with when(), mergeWhen() and the other conditional helpers is optional.
return [
    // required
    'id' => $this->id,
    // required
    'title' => $this->title,
    // optional, an Author component
    'author' => new AuthorResource($this->whenLoaded('author')),
    // optional
    'secret' => $this->when($request->user()?->isAdmin(), $this->secret),
];

A nested resource is described like a returned one and becomes its own component, referenced by $ref.

A second sample tells the values that never change from one sample to the other, such as 'type' => 'cat': they are the discriminators of a CatResource|DogResource union.

Components

Each resource is a component of components.schemas, named after its class without Resource (BookResource → Book). #[SchemaName] names it, on a resource or a backed enum:

use Ark4ne\OpenApi\Attributes\SchemaName;

#[SchemaName('PublicBook')]
final class BookResource extends JsonResource

Set use_references to false in a document to write every schema inline instead.

Resources that do not receive a model

A resource built from a DTO, an array or anything that is not a model needs #[ResourceFactory] to tell how its sample is built:

app/Http/Resources/QuoteResource.php
use Ark4ne\OpenApi\Attributes\ResourceFactory;

#[ResourceFactory(
    QuoteFactory::class,
    method: 'sample',
    parameters: ['currency' => 'EUR'],
)]
final class QuoteResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'amount' => $this->resource->amount,
            'currency' => $this->resource->currency,
        ];
    }
}

factory is a model factory class (its make() receives parameters), or any class whose method (or __invoke without method) receives parameters by name. The class is built through the container.

Settings

config/openapi.php
'sampling' => [
    'transactions' => true,
    'connections' => ['mariadb', 'mysql', 'pgsql', 'sqlite', 'sqlsrv'],
    'collection_size' => 2,
    'seed' => 1,
    'examples' => true,
],
KeyEffect
transactionscreate the factory models inside a rolled back transaction; false: only make them
connectionsthe drivers a transaction is opened for
collection_sizethe number of items of a sampled collection
seedthe seed of the fake values: two runs give the same document
exampleswrite the sampled scalars as example; false leaves them out

When a resource fails

When toArray() throws on a sample, the resource is described with what could be read, and a warning tells why:

  GET /api/books/{book}
    warning response: cannot run App\Http\Resources\BookResource::toArray(): Call to a member function format() on null

Give the model a factory, @property tags or casts, or give the resource a #[ResourceFactory]. A failing run with relations keeps the schema of the plain run.