Documenting endpoints

Responses

Document the responses of an action from its return type, and declare what the return type cannot tell.

The responses of an operation come from the return type of its action, completed by its PHPDoc @return. Type the return of every action: without it, the operation gets no response, and a diagnostic. #[Response] declares what a return type cannot say: a status, a paginator, headers.

From the return type

The action returnsThe response
UserResource200 (201 for POST) with {"data": User}, User being a component
AnonymousResourceCollection with @return AnonymousResourceCollection<UserResource>, or a ResourceCollection200 with {"data": [User]}
UserResource|AdminResourceoneOf the two components, with a discriminator when a property tells them apart
A model, a collection of modelsits attributes, from its casts, @property and columns
array with @return array{id: int, tags: list<string>}that shape
int, string, bool…that scalar
JsonResponsean object without properties, and an info: declare the body with #[Response]
Response returned by a DELETE, noContent()204
voidan empty 200
RedirectResponse302 with a Location header
BinaryFileResponse, StreamedResponseapplication/octet-stream, binary; Content-Disposition for a file
A Responsablewhat its toResponse() returns, run on a sample
A viewnot documented

The resources are described by running them on sampled models; see Sampling for how, and for which keys are required.

app/Http/Controllers/PetController.php
public function show(int $id): CatResource|DogResource
{
    // …
}

// CatResource::toArray(): ['type' => 'cat', 'id' => …, 'name' => …]
// DogResource::toArray(): ['type' => 'dog', 'id' => …, 'name' => …]
responses.200
{
  "description": "OK",
  "content": {
    "application/json": {
      "schema": {
        "type": "object",
        "required": ["data"],
        "properties": {
          "data": {
            "oneOf": [
              { "$ref": "#/components/schemas/Cat" },
              { "$ref": "#/components/schemas/Dog" }
            ],
            "discriminator": {
              "propertyName": "type",
              "mapping": {
                "cat": "#/components/schemas/Cat",
                "dog": "#/components/schemas/Dog"
              }
            }
          }
        }
      }
    }
  }
}

Declaring a response

#[Response] is repeatable. On the action, it replaces the response inferred for its status:

app/Http/Controllers/SearchIndexController.php
use Ark4ne\OpenApi\Attributes\Response;

#[Response(
    202,
    description: 'Queued',
    type: 'array{job: string}',
    headers: ['Retry-After' => 'positive-int'],
)]
public function rebuild(): JsonResponse
{
    return new JsonResponse(['job' => $job->id], 202);
}
responses
{
  "202": {
    "description": "Queued",
    "headers": {
      "Retry-After": { "schema": { "type": "integer", "minimum": 1 } }
    },
    "content": {
      "application/json": {
        "schema": {
          "type": "object",
          "required": ["job"],
          "properties": { "job": { "type": "string" } },
          "additionalProperties": false
        }
      }
    }
  }
}

A JsonResponse is inferred as a 200 whatever status it is built with. A declared success (2xx) leaves out the successes inferred for other statuses: here the 202 replaces the 200.

ParameterGives
statusthe status, 200 by default, or 'default'
descriptionthe description, the HTTP phrase of the status by default
resourcethe body from a resource or a resource collection
typethe body from a PHPDoc type: array{id: int}, list<string>
mediaTypeapplication/json by default; with text/event-stream, type is one event
headersheader name → PHPDoc type of its value
paginatorthe paginator of resource
examplean example of the body
summarya short summary (3.2)

Without resource nor type, the attribute keeps the body inferred for its status, or given by the exceptions of that status: #[Response(404, description: 'No such book')] renames the 404 only.

Paginated collections

The return type of Book::paginate() wrapped in a collection does not tell the paginator. Declare it:

app/Http/Controllers/BookController.php
use Illuminate\Pagination\CursorPaginator;

#[Response(
    200,
    resource: BookResource::class,
    paginator: CursorPaginator::class,
)]
public function index(): AnonymousResourceCollection
{
    return BookResource::collection(Book::query()->cursorPaginate());
}
responses.200.content.application/json.schema
{
  "type": "object",
  "required": ["data", "links", "meta"],
  "properties": {
    "data": { "type": "array", "items": { "$ref": "#/components/schemas/Book" } },
    "links": {
      "type": "object",
      "required": ["first", "last", "prev", "next"],
      "properties": {
        "first": { "type": ["string", "null"] },
        "last": { "type": ["string", "null"] },
        "prev": { "type": ["string", "null"] },
        "next": { "type": ["string", "null"] }
      }
    },
    "meta": {
      "type": "object",
      "required": ["path", "per_page", "next_cursor", "prev_cursor"],
      "properties": {
        "path": { "type": ["string", "null"] },
        "per_page": { "type": "integer" },
        "next_cursor": { "type": ["string", "null"] },
        "prev_cursor": { "type": ["string", "null"] }
      }
    }
  }
}

LengthAwarePaginator adds current_page, from, last_page, links, to and total to meta; Paginator the meta of a simple pagination. A paginator returned as it is (Book::query()->paginate(), not wrapped in a resource) has the shape Laravel renders.

Responses shared by a controller

On the controller class, #[Response] is a response of each of its actions, listed after theirs:

#[Response(401, description: 'Unauthenticated')]
final class SeatController
{
    #[Response(
        201,
        description: 'Seat booked',
        type: 'array{seat: string, expires_at: string}',
    )]
    public function book(string $seat): JsonResponse
    {
        // …
    }
}

The action replaces a response of the controller for the same status, and a success of the action, declared or inferred, leaves out the successes of the controller for other statuses: the 401 of the controller stays, a 200 of the controller would give way to the 201 of the action.

Server-sent events

With mediaType: 'text/event-stream', type describes one event, written as itemSchema. It needs OpenAPI 3.2: an earlier strict document fails on it, a lenient one (strict: false) drops it with a warning.

#[Response(
    200,
    mediaType: 'text/event-stream',
    type: 'array{event: string, data: string}',
)]
public function stream(): StreamedResponse

Error responses

The error responses (401, 403, 404, 422, 429 and those of the @throws) are added by the generator. See Security & errors.