# OpenAPI Documentation

> Document every endpoint of your resources in OpenAPI with Scramble, with typed bodies, responses and examples, and keep the document under test.

The package documents its endpoints through [Scramble](https://scramble.dedoc.co). It builds the document from the declarations of your resources: fields, relations, scopes, instructions, actions, metrics, limits and gates.

## Installation

```bash
composer require dedoc/scramble:^0.13.48
```

The package registers its documentation in the `boot()` method of its service provider: `config/scramble.php` needs no change. Visit `/docs/api` to read the document, or export it:

```bash
php artisan scramble:export
```

An API that your application registers with `Scramble::registerApi()` after the package boots gets the package documentation too. For an API registered before, add the transformers:

```php
Scramble::registerApi('v2', ['api_path' => 'api/v2'])
    ->withOperationTransformers(\Lomkit\Rest\Scramble\RestOperations::class)
    ->withDocumentTransformers(\Lomkit\Rest\Scramble\RestDocument::class);
```

## What the document holds

The document is the same for every reader. The package reads the declarations of each resource as a guest: a field, an action or a metric declared for some users only is documented as a guest sees it.

<table>
<thead>
  <tr>
    <th>
      Operation
    </th>
    
    <th>
      Summary
    </th>
    
    <th>
      Body
    </th>
    
    <th>
      Response
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        GET /{resource}
      </code>
    </td>
    
    <td>
      <code>
        Get {Resource} details
      </code>
    </td>
    
    <td>
      the <code>
        with
      </code>
      
       parameter
    </td>
    
    <td>
      <code>
        {Resource}Details
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        POST /{resource}/search
      </code>
    </td>
    
    <td>
      <code>
        Search {Resource}
      </code>
    </td>
    
    <td>
      <code>
        {Resource}Search
      </code>
    </td>
    
    <td>
      <code>
        {Resource}Paginated
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        POST /{resource}/mutate
      </code>
    </td>
    
    <td>
      <code>
        Mutate {Resource}
      </code>
    </td>
    
    <td>
      <code>
        {Resource}Mutation
      </code>
      
       entries
    </td>
    
    <td>
      <code>
        {Resource}MutateResult
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        POST /{resource}/actions/{uriKey}
      </code>
    </td>
    
    <td>
      the name of the action
    </td>
    
    <td>
      <code>
        search
      </code>
      
       or <code>
        resources
      </code>
      
      , as the target requires, and <code>
        fields
      </code>
    </td>
    
    <td>
      <code>
        RestActionResponse
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        POST /{resource}/metrics/{uriKey}
      </code>
    </td>
    
    <td>
      the name of the metric
    </td>
    
    <td>
      <code>
        search
      </code>
      
      , <code>
        range
      </code>
      
      , <code>
        timezone
      </code>
    </td>
    
    <td>
      <code>
        data
      </code>
      
       with the result of the metric
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        DELETE /{resource}
      </code>
      
      , <code>
        POST /{resource}/restore
      </code>
      
      , <code>
        DELETE /{resource}/force
      </code>
    </td>
    
    <td>
      <code>
        Delete {Resource}
      </code>
      
      , <code>
        Restore {Resource}
      </code>
      
      , <code>
        Force delete {Resource}
      </code>
    </td>
    
    <td>
      <code>
        resources
      </code>
    </td>
    
    <td>
      <code>
        {Resource}Rows
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        GET /{resource}/actions/{action}/batches/{batch}
      </code>
    </td>
    
    <td>
      <code>
        Batch progress of {Resource} actions
      </code>
    </td>
    
    <td>
      
    </td>
    
    <td>
      <code>
        RestBatchProgress
      </code>
    </td>
  </tr>
</tbody>
</table>

`{Resource}` is the class name of the resource without its `Resource` suffix, also used as the tag.

- **Records.** Each resource has a record, named like its tag (`Post`): its selectable fields with their type, the gates of a row, and each relation under its key. The morph type column of a `MorphTo` relation lists its morph types as an enum. A `MorphTo` relation is `oneOf` the record of each target, with a `discriminator` on `@type`.
- **Search.** Filters list one condition per filterable field, with the operators of the field and the value that each one takes, plus the fields of each related resource one level deep and the pivot fields. Includes, aggregates, scopes and instructions have one schema per relation or name. Lists hold at most their `rest.limits.sizes` entries. `sorts` lists the key of each aggregate that sorts: an aggregate over a relation to many, with no field or on a field that is not a key, see [Sorts and selects](/search/sorts-and-selects).
- **Mutations.** `attributes` lists the fields that the operation writes, with their rules in the description. An `Enum` field lists the cases that writes accept. Each relation lists the operations that it accepts, after [`onlyOperations()` and `withoutOperations()`](/resources/relations#limiting-the-operations): a read-only relation is left out of `relations`, a relation without `update` leaves `attributes` out of its `sync` and `toggle` entries and `relations` out of its link entries, and the `sync` of a many-to-many relation without `detach` requires `without_detaching` with `const: true`. The `sync` of a `syncable()` relation takes `key` alone.
- **Actions.** The body follows the target of the action: `search` is required on the `Search` target, `resources` on the `Resources` target. A key that the target refuses is documented as `false`. `fields` lists typed `{name, value}` entries. The result is `oneOf` the types of `ActionResponse`, with a `discriminator` on `type`. A batched action answers `RestBatchableActionResponse`, with `batch`. See [Actions and writes](#actions-and-writes).
- **Metrics.** The built-in types share `RestValueResult`, `RestTrendResult`, `RestPartitionResult` (with `previous` on each part and on `other` when the partition compares two periods), `RestTableResult` (with `percentile` on a percentile column) and `RestProgressResult`. `parts` and `splits` hold at most `rest.limits.sizes.groups` entries; a partition or a trend with its own `limit()` has its schema, with that maximum, in its operation. A metric of your own documents its `type` alone until it declares `schema()`, see [Metrics](/actions-and-metrics/metrics#your-own-metric).
- **Details.** `{Resource}Details` lists the names of the resource as enums. The base keys are required, the sections and parts optional. `meta` accepts any key when the resource overrides `detailsMeta()`.

### Search engines

The page of a resource whose text runs on a [search engine](/search/search-engines) documents `dropped` and `total_capped` as optional.

On a resource that [serves its lists](/search/search-engines#engine-lists), the search and the action search are a `oneOf` of two named branches:

<table>
<thead>
  <tr>
    <th>
      Branch
    </th>
    
    <th>
      Takes
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        {Resource}DatabaseSearch
      </code>
      
      , <code>
        {Resource}DatabaseActionSearch
      </code>
    </td>
    
    <td>
      The default: <code>
        source
      </code>
      
       absent or <code>
        database
      </code>
      
      , the SQL filters, scopes, instructions and sorts, without <code>
        @relevance
      </code>
      
      , the SQL <code>
        trashed
      </code>
      
      , and a <code>
        text
      </code>
      
       whose <code>
        value
      </code>
      
       must be blank (<code>
        pattern
      </code>
      
       <code>
        ^\s*$
      </code>
      
      , or <code>
        null
      </code>
      
      )
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        {Resource}EngineSearch
      </code>
      
      , <code>
        {Resource}EngineActionSearch
      </code>
    </td>
    
    <td>
      <code>
        "source": "engine"
      </code>
      
      , required, a text, and the grammar of the engine: <code>
        {Resource}EngineFilter
      </code>
      
      , <code>
        {Resource}EngineSort
      </code>
      
       (with <code>
        @relevance
      </code>
      
       for a text), <code>
        {Resource}EngineInstruction
      </code>
      
      , and <code>
        scopes
      </code>
      
       set to <code>
        false
      </code>
    </td>
  </tr>
</tbody>
</table>

On an engine that accepts [groups of filters](/search/search-engines#groups-of-filters), `{Resource}EngineFilter` is a `oneOf` of `{Resource}EngineFieldFilter`, the conditions on the attributes with `type` (`and` or `or`), and `{Resource}EngineFilterGroup`, a group with `nested`. The schemas of the other resources do not change.

### Totals

A resource that declares [totals](/search/totals) adds `search.totals` to its search, as `{Resource}SearchTotals`, with the enums of its fields and measure types, and the sizes as `maxItems`. Its page has an optional root `totals`, `{Resource}Totals` with `{Resource}TotalsGroup`, whose bucket `value` takes the types of the grouped fields. On a search engine, the `{Resource}EngineSearch` branch adds `search.totals` as `{Resource}EngineSearchTotals`, with the attributes and the measure types of the engine.

### Extensions

- An [extension](/extensions/responses-and-checks#documenting-an-extension) that implements `DocumentsExtension` adds its responses to the operations, as shared responses named `{name}.{Name}`, such as `quota.Exceeded`, and gives the schema of its search and details meta.
- Each extension that adds meta is one required property of the `meta` schema, since its key always renders, `{}` when empty.
- The document is built without a user: it lists the declared fields and the declared limits, also when an extension hides a field or narrows the limits for some users. `total_capped` is optional on the pages of a resource that an extension may cap.
- An `auth` middleware that an extension adds to the routes makes the document list the `401` of the operation.

### Actions and writes

```json
{
  "/shows/actions/cancel-shows": {
    "post": {
      "description": "The action is destructive: a hint for clients, the endpoint runs it the same way.\n\nThe text that a client shows before it runs the action: Cancel the selected shows?\n\nThe action can answer 428: send the same body again with the token of the answer in `confirmation`.",
      "summary": "Cancel Shows",
      "x-lomkit-destructive": true,
      "x-lomkit-confirm": "Cancel the selected shows?"
    }
  }
}
```

- The operation of a `destructive()` action carries `"x-lomkit-destructive": true`, and the operation of an action with `confirm()` carries its text under `x-lomkit-confirm`. Its description says both.
- An action that declares `confirmation()` documents `confirmation` in its body and the `428` response. So do the `mutate`, `destroy`, `restore` and `forceDestroy` operations of a resource that declares the matching hook, see [Confirmation](/actions-and-metrics/confirmation#confirming-writes).
- A key that an operation refuses is written `"<key>": false` in its `properties`, such as `"search": false` on the `Resources` target, `"range": false` on a metric without ranges, or `"text": false` on a search of a resource without a text search: the endpoint answers `422` when the request sends it.

### Errors

`components.responses` holds the shared error responses, listed on the operations of the package:

<table>
<thead>
  <tr>
    <th>
      Response
    </th>
    
    <th>
      Status
    </th>
    
    <th>
      Listed on
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        RestUnauthenticated
      </code>
    </td>
    
    <td>
      <code>
        401
      </code>
    </td>
    
    <td>
      the operations whose route runs <code>
        auth
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        RestForbidden
      </code>
    </td>
    
    <td>
      <code>
        403
      </code>
    </td>
    
    <td>
      every operation; with <code>
        denials
      </code>
      
       when the application registers <code>
        DenialsRenderer
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        RestNotFound
      </code>
    </td>
    
    <td>
      <code>
        404
      </code>
    </td>
    
    <td>
      every operation
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        RestConflict
      </code>
    </td>
    
    <td>
      <code>
        409
      </code>
    </td>
    
    <td>
      the mutate operations that write a <a href="/writing/versioned-rows">
        versioned
      </a>
      
       resource, at the root or under a relation, through any operation that takes <code>
        relations
      </code>
      
      , and those that reach a <a href="/writing/relations#syncing-child-rows">
        <code>
          syncable()
        </code>
      </a>
      
       relation. Each item of <code>
        conflicts
      </code>
      
       is <code>
        oneOf
      </code>
      
       two shapes by <code>
        reason
      </code>
      
      : <code>
        version
      </code>
      
       with <code>
        path
      </code>
      
      , <code>
        key
      </code>
      
       and <code>
        version
      </code>
      
      , <code>
        unlisted
      </code>
      
       with <code>
        path
      </code>
      
       and <code>
        key
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        RestValidationFailed
      </code>
    </td>
    
    <td>
      <code>
        422
      </code>
    </td>
    
    <td>
      every operation but batch progress
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        RestConfirmationRequired
      </code>
    </td>
    
    <td>
      <code>
        428
      </code>
    </td>
    
    <td>
      the actions that declare <code>
        confirmation()
      </code>
      
      , and the writes of a resource that declares the matching confirmation hook
    </td>
  </tr>
</tbody>
</table>

An operation whose route does not run `auth` has `"security": []`. The package declares no authentication scheme: declare yours in a document transformer.

```php
use Dedoc\Scramble\Scramble;
use Dedoc\Scramble\Support\Generator\OpenApi;
use Dedoc\Scramble\Support\Generator\SecurityScheme;

Scramble::configure()->withDocumentTransformers(function (OpenApi $openApi): void {
    $openApi->secure(SecurityScheme::http('bearer'));
});
```

## Types and examples

Each field documents its type:

<table>
<thead>
  <tr>
    <th>
      Field
    </th>
    
    <th>
      Schema
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        ID
      </code>
    </td>
    
    <td>
      an integer or a string, from the key type
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        Text
      </code>
    </td>
    
    <td>
      <code>
        string
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        Number
      </code>
      
      , <code>
        Integer
      </code>
    </td>
    
    <td>
      <code>
        number
      </code>
      
      , <code>
        integer
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        Boolean
      </code>
    </td>
    
    <td>
      <code>
        boolean
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        Date
      </code>
      
      , <code>
        DateTime
      </code>
    </td>
    
    <td>
      <code>
        string
      </code>
      
       with <code>
        format: date
      </code>
      
       or <code>
        format: date-time
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        Enum
      </code>
    </td>
    
    <td>
      an enum of its backing values
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        Json
      </code>
    </td>
    
    <td>
      <code>
        object
      </code>
    </td>
  </tr>
</tbody>
</table>

`nullable()` adds `null`, and `meta()` goes under `x-lomkit-meta`. A field type of your own overrides `toSchema()`, and `toWriteSchema()` when writes accept fewer values, as an `Enum` with [`offered()`](/resources/fields#offered-cases) does.

- The responses follow these types: a `Number` field answers a number, even from a `decimal` cast, and an empty `Json` field answers `{}`. See [Fields](/resources/fields#value-types-in-rows).
- The rules of a field go in its description, such as `Rules: string, max:80, required`, on the fields of `mutate`, of actions, of instructions and of scopes.
- An action field, an instruction field, a scope parameter or a metric `range` with a default gives it under `default`, such as `"default": true` or `"default": 30`.

`examples()` lists example values on a field. The request examples of each operation use the first value:

```php
Text::make('title')->examples('Weekly report', 'Daily report'),
```

Without `examples()`, an example takes a value of the field's type that passes its simple rules: the length of `min`, `max`, `size` and `between` on a string (`aaaaaaaa` for `min:8`), their bounds and those of `gt`, `gte`, `lt` and `lte` on a number, the first value of `in`, and a value for `email`, `url`, `uuid`, `ulid`, `ip`, `date`, `numeric`, `digits`, `accepted` and `declined`.

- A request example never sends a default: a field with a default is left out of an action example, and a metric example is `{}`.
- The mutate example adds each relation declared `requiredOnCreation()`, with an `attach` of a key.

<tip>

Declare `examples()` on the fields whose other rules the generated value does not pass, so that the request examples pass your rules.

</tip>

<note>

The `date` cast of Laravel renders a date and a time. Cast a `Date` attribute with `date:Y-m-d` so that the response matches the documented `format: date`.

</note>

## Keeping the document under test

The package tests its own document in two ways, and you can do the same in your application.

- **Contract tests.** The package sends real requests to each documented operation and validates each response against the schema of the document: a response that does not match fails the test.
- **A snapshot.** The package generates the document of a fixture application and compares it with a committed JSON file. A change of a declaration shows as a diff of that file.

A snapshot test in your application can compare the generated document with a committed file:

```php
use Dedoc\Scramble\Generator;

public function test_the_api_document_matches_the_snapshot(): void
{
    $document = app(Generator::class)();
    unset($document['info'], $document['servers']);

    $json = json_encode($document, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)."\n";

    $this->assertSame(file_get_contents(base_path('tests/api.json')), $json);
}
```

Write the file once from the same code, and commit it. When a change to a resource changes the API, the test fails and the diff of `tests/api.json` shows what clients see.
