Documenting endpoints

Security & errors

Security requirements from the middlewares, and the error responses the generator adds to each operation.

The security of an operation and most of its error responses come from what the route already does: its middlewares, its bound models, its form request and the exceptions its action throws.

Security from the middlewares

MiddlewareSecurity schemeAlso adds
auth:sanctumsanctum (bearer token), or session + xsrf (the cookie of a SPA)401
auth:apipassport (OAuth2 authorization code on /oauth/authorize and /oauth/token)401
auth, auth:<guard>bearer, or a bearer token named after the guard401
auth.basicbasic (HTTP basic)401
abilities:, ability: (Sanctum)the scopes of the sanctum requirement from 3.1; a sentence of the description before
scopes:, scope: (Passport)the scopes of the passport requirement, declared in its flows
can:, Authorize403
signedsignature and expires query parameters, 403
throttle429 with X-RateLimit-Limit, X-RateLimit-Remaining, Retry-After, X-RateLimit-Reset
ValidateCsrfToken (the web group)X-CSRF-TOKEN header and 419, on the methods that change something

Each guard of auth:sanctum,api is an alternative requirement.

Your own schemes

security_schemes completes or replaces the schemes the middlewares give, by name. Write each scheme as an OpenAPI Security Scheme Object: its keys are the OpenAPI field names, in camelCase.

config/openapi.php
'documents' => [
    'v1' => [
        'security_schemes' => [
            'passport' => [
                'type' => 'oauth2',
                'flows' => ['authorizationCode' => [
                    'authorizationUrl' => 'https://example.com/oauth/authorize',
                    'tokenUrl' => 'https://example.com/oauth/token',
                    'scopes' => ['books:read' => 'Read the books'],
                ]],
            ],
            'oidc' => [
                'type' => 'openIdConnect',
                'openIdConnectUrl' => 'https://example.com'
                    . '/.well-known/openid-configuration',
            ],
        ],
        'security' => [],   // names of the schemes required on every operation
    ],
],

security lists the schemes required by default on every operation, on top of those of the middlewares.

Declaring the security

#[Security] replaces the requirements of the middlewares. It is repeatable: each attribute is an alternative.

use Ark4ne\OpenApi\Attributes\Security;

#[Security('oidc', scopes: ['books:write'])]
#[Security('passport', scopes: ['books:write'])]
public function store(StoreBookRequest $request): BookResource

On the controller, it applies to each action; on the action, it replaces those of the class.

To add what a middleware of your own means (a header, a scheme, an error), write a middleware mapper.

Error responses

StatusComes from
401auth, auth:<guard>, auth.basic, the default security
403can:, Authorize, signed, a form request that redefines authorize(), @throws AuthorizationException
404a bound model or backed enum in the path, @throws ModelNotFoundException
419the CSRF middleware
422a form request with rules, @throws ValidationException
429throttle
anythe @throws of the action

They are shared responses of components.responses (Unauthenticated, NotFound, ValidationFailed…), with the bodies Laravel renders: Error ({"message": …}) and ValidationError ({"message": …, "errors": {…}}).

"responses": {
  "201": { "…": "…" },
  "401": { "$ref": "#/components/responses/Unauthenticated" },
  "422": { "$ref": "#/components/responses/ValidationFailed" }
}

With the JSON:API integration and integrations.json_api.errors, the bodies are JSON:API error documents.

Exceptions of the action

Each @throws of the action becomes a response:

/**
 * Book a seat.
 *
 * @throws SeatTakenException
 * @throws \Illuminate\Auth\Access\AuthorizationException
 */
public function book(string $seat): JsonResponse

The status and the body of an exception come from, in order:

  1. #[Response] on the exception class, or on a parent class:
    use Ark4ne\OpenApi\Attributes\Response;
    
    #[Response(409, description: 'The seat is already taken')]
    final class SeatTakenException extends RuntimeException {}
    

    Without body, the response has the error body; it accepts resource, type, headers and example as on an action.
  2. exceptions.map of the configuration, for the exceptions you cannot annotate and those bootstrap/app.php renders through closures. The exception or its closest parent class wins:
    config/openapi.php
    'exceptions' => [
        'read_throws' => true,
        'map' => [
            PaymentRequiredException::class => 402,
            SeatTakenException::class => [
                'status' => 409,
                'description' => 'Seat taken',
            ],
        ],
    ],
    
  3. Laravel's rendering: AuthenticationException 401, AuthorizationException 403, ModelNotFoundException 404, TokenMismatchException 419, ValidationException 422, ThrottleRequestsException 429, subclasses included.
  4. Symfony's HTTP exceptions whose class fixes the status (NotFoundHttpException…), and an HTTP exception of the application whose constructor without arguments sets its status.

Several causes of one status become one response: a declared #[Response] wins, otherwise their descriptions are put together and different bodies become oneOf.

Set exceptions.read_throws to false to ignore the @throws tags.