Documenting endpoints

Requests

Document query parameters, request bodies, headers and cookies from form requests and attributes.

The parameters and the body of an operation come from the form request of its action: its rules() are read and turned into schemas. Attributes and DescribesRequest add what the rules do not say: headers, cookies, other media types.

Form requests

Type the form request in the action; its rules give the fields:

app/Http/Requests/StoreAvatarRequest.php
final class StoreAvatarRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'avatar' => ['required', File::image()->max(2048)],
            'caption' => 'nullable|string|max:120',
            'publish_at' => 'sometimes|date_format:Y-m-d',
            'company' => 'required_if:type,business|string',
        ];
    }
}
requestBody
{
  "required": true,
  "content": {
    "multipart/form-data": {
      "schema": {
        "type": "object",
        "required": ["avatar"],
        "properties": {
          "avatar": { "type": "string", "format": "binary", "description": "At most 2048 KB." },
          "caption": { "type": ["string", "null"], "maxLength": 120 },
          "publish_at": { "type": "string", "format": "date" },
          "company": { "type": "string", "description": "Required if type is business." }
        }
      },
      "encoding": {
        "avatar": { "contentType": "image/jpeg, image/png, image/bmp, image/gif, image/webp" }
      }
    }
  }
}
  • The fields go to the query for GET, HEAD and DELETE, to the body otherwise.
  • The body is application/json, or multipart/form-data as soon as a field is a file; the types of the files give the encoding.
  • required makes the field required; sometimes cancels it; required_if, required_with and the other conditions leave it optional and write the condition in its description.
  • Nested fields (address.city, tags.*) give nested objects and lists.
  • A request that redefines authorize() adds a 403; a request with rules adds a 422. See Security & errors.

Every supported rule and the schema it gives are listed in the validation rules reference. An unknown rule keeps the field and is reported as an info; a closure rule is ignored with an info.

Only form requests are read. Rules validated in the controller ($request->validate([...])) are invisible to the generator: move them to a form request.

Query parameters

In the query, every key is its own parameter. A nested key is written with brackets:

app/Http/Requests/ListPostsRequest.php
public function rules(): array
{
    return [
        'q' => 'required|string|min:2',
        'filter.status' => [Rule::enum(Status::class)],
        'filter.author' => 'integer',
        'sort' => 'in:title,-title,date,-date',
    ];
}
parameters
[
  { "name": "q", "in": "query", "required": true, "schema": { "type": "string", "minLength": 2 } },
  { "name": "filter[status]", "in": "query", "schema": { "type": "string", "enum": ["draft", "published"] } },
  { "name": "filter[author]", "in": "query", "schema": { "type": "integer" } },
  { "name": "sort", "in": "query", "schema": { "type": "string", "enum": ["title", "-title", "date", "-date"] } }
]

strategies.query.by chooses how nested fields are written:

byfilter.status, filter.author, ids.*
all (default)filter[status], filter[author], ids[]: one parameter per key, an object field included
lastfilter[status], filter[author], ids: the same, the last list kept as one array parameter
nonefilter as one deepObject parameter, ids as an array
querystringthe whole query as one querystring parameter (3.2; none before)

An object whose keys are not all known (open additionalProperties, a reference) stays a deepObject with all and last, with an info.

Headers, cookies and parameters by attribute

#[QueryParameter], #[Header] and #[Cookie] add a parameter, or complete the parameter of the same name the rules gave. Put them on the controller, the request class or the action:

use Ark4ne\OpenApi\Attributes\Header;
use Ark4ne\OpenApi\Attributes\QueryParameter;

#[QueryParameter('page', description: 'Page number, from 1')]
#[QueryParameter('sort', type: "'title'|'price'", description: 'Sort order')]
#[Header('X-Request-Id', type: 'string', description: 'Echoed in the response')]
public function index(ListPostsRequest $request): array

A parameter left null keeps its value: #[QueryParameter('page', description: '…')] keeps the schema (integer, minimum: 1) and the requirement of the page rule. type is a PHPDoc type (PHPDoc types). A header is matched whatever the case of its name.

Describing a request by hand

A form request implementing DescribesRequest completes or replaces what its rules describe:

app/Http/Requests/ListPostsRequest.php
use Ark4ne\OpenApi\Extraction\Requests\DescribesRequest;
use Ark4ne\OpenApi\Extraction\Requests\RequestDescriber;

final class ListPostsRequest extends FormRequest implements DescribesRequest
{
    public function rules(): array
    {
        return ['q' => 'required|string|min:2'];
    }

    public function describe(RequestDescriber $request): RequestDescriber
    {
        return $request
            ->header('X-Tenant', 'required|uuid', 'Tenant of the request')
            ->query(['include' => 'string']);
    }
}

RequestDescriber is immutable: chain the calls and return the result. Rules are written as in rules(); a writer Schema is used as it is.

MethodAdds
header($name, $rules, $description, $required)a header
cookie($name, $rules, $description, $required)a cookie
query(array $rules)query fields
json(array $rules), form(array $rules), multipart(array $rules)body fields of application/json, application/x-www-form-urlencoded, multipart/form-data
body(array $rules, ?string $mediaType)body fields of any media type
bodySchema(Schema $schema, string $mediaType)a body described by a schema, replacing that media type
bodyDescription(?string $description)the description of the body
parameter(ParameterDescription $parameter)any parameter, replacing the one of the same name and location

A rule that describes itself

A validation rule of your application implements DescribesRule to give its schema:

app/Rules/Isbn.php
use Ark4ne\OpenApi\Description\FieldDescription;
use Ark4ne\OpenApi\Extraction\Rules\DescribesRule;

final class Isbn implements DescribesRule, ValidationRule
{
    public function validate(
        string $attribute,
        mixed $value,
        Closure $fail,
    ): void {
        if (! is_string($value)
            || preg_match('/^[0-9-]{10,17}$/', $value) !== 1
        ) {
            $fail('The :attribute must be an ISBN.');
        }
    }

    public function describe(FieldDescription $field): FieldDescription
    {
        return $field->schema(
            $field->schema
                ->type('string')
                ->pattern('^[0-9-]{10,17}$'),
        );
    }
}
schema of the field
{ "type": "string", "pattern": "^[0-9-]{10,17}$" }

For a rule registered by name (Validator::extend('phone', …)), write a rule mapper.

A body without form request

#[RequestBody] gives the body of an action that has no form request, or describes the body the rules give:

use Ark4ne\OpenApi\Attributes\RequestBody;

#[RequestBody(
    type: 'array{name: string, tags?: list<string>}',
    description: 'The new label',
)]
public function store(Request $request): LabelResource

#[RequestBody(resource: BookResource::class)]
public function import(Request $request): BookResource

#[RequestBody(description: 'The avatar and its caption', required: false)]
public function avatar(StoreAvatarRequest $request): void
  • With type or resource, the attribute gives the body of its mediaType (application/json by default), next to the media types the rules gave.
  • Without either, it only describes the body the rules gave: description and required; mediaType is then unused.
  • required is null by default: required when the attribute gives the body, unchanged otherwise.