Looking to hire Laravel developers? Try LaraJobs

laravel-api-specs maintained by turkeryildirim

Description
Auto-generate OpenAPI 3.1, AsyncAPI 3.1 and Postman specs from Laravel projects
Last update
2026/11/30 21:42 (dev-main)
License
Downloads
0

Comments
comments powered by Disqus

Laravel API Specs

License: MIT CI

Generate OpenAPI 3.1.0, AsyncAPI 3.1.0, and Postman Collection v2.1 specifications directly from your Laravel codebase.

turkeryildirim/laravel-api-specs inspects your registered routes, controller signatures, FormRequest validation rules, JsonResource classes, Eloquent models, middleware, events, and observers using PHP reflection and nikic/php-parser AST analysis—with PHP 8 attributes available whenever you want explicit control.


Table of Contents


What It Is & Why Use It

turkeryildirim/laravel-api-specs produces machine-readable API specifications from your existing Laravel application without requiring you to maintain separate YAML/JSON documentation files by hand:

  • OpenAPI 3.1.0 (JSON or YAML) from Laravel routes, controllers, FormRequest rules, JsonResource / ResourceCollection return types, Eloquent models, and route middleware.
  • AsyncAPI 3.1.0 (JSON or YAML) from Laravel events, ShouldBroadcast events, Eloquent observers, and #[AsyncApiChannel] attributes.
  • Postman Collection v2.1 (JSON) grouped by controller tag with path variables, query parameters, {{base_url}}, request.auth security mapping, and generated JSON request body examples.

It is a good fit when your Laravel API follows standard conventions—controller classes or invokable controllers, FormRequest validation, JsonResource responses, and Eloquent models—and you want to generate specs in CI or locally via Artisan commands.


What It Does NOT Do / When Not to Use It

Before adopting this package, be aware of its boundaries:

  • No web UI routes: It does not serve Swagger UI, Redoc, or AsyncAPI Studio endpoints. It only writes generated specifications to a file or stdout.
  • No runtime request execution: It never executes controller actions, sends HTTP requests, or runs database queries beyond Schema::getColumnListing() for model column discovery.
  • Limited JsonResource::toArray() AST support: It parses direct return [...] array literals, return array_merge([...], ...), and supported helpers ($this->when(...), $this->whenLoaded(...), $this->whenCounted(...), $this->count(...), resource ::make/::resolve/::collection, new Resource(...), ternaries, and ??). Dynamically constructed arrays (such as building $data = [] across statements or wrapping returns in helper methods) are not parsed.
  • No closure route support: Routes backed by closures instead of controller actions are skipped with a warning in the discovery report.

If your endpoints rely heavily on dynamic runtime response builders or closure routes, consider maintaining specs with explicit #[Response(schemaOverride: ...)] definitions or using a contract-first OpenAPI workflow.


Requirements & Installation

  • PHP: ^8.2 (ext-json; Laravel 13 requires PHP ^8.3)
  • Laravel: ^11.0 | ^12.0 | ^13.0

Install via Composer:

composer require turkeryildirim/laravel-api-specs

The package uses Laravel package auto-discovery to register Turker\LaravelApiSpecs\LaravelApiSpecsServiceProvider.

Publish the configuration file if you want to customize defaults:

php artisan vendor:publish --tag=api-spec-config

This publishes config/api-spec.php.


Usage & Artisan Commands

Generate specifications using the dedicated Artisan commands or the generic spec:generate command:

# OpenAPI 3.1.0 (JSON to stdout, or YAML to file)
php artisan spec:openapi
php artisan spec:openapi --format=yaml --output=docs/openapi.yaml

# AsyncAPI 3.1.0
php artisan spec:asyncapi
php artisan spec:asyncapi --format=yaml --output=docs/asyncapi.yaml

# Postman Collection v2.1 (JSON)
php artisan spec:postman --output=docs/postman-collection.json

# Generic generator (--type: openapi | asyncapi | postman, --format: json | yaml)
php artisan spec:generate --type=openapi --format=json
php artisan spec:generate --type=asyncapi --format=yaml --output=docs/asyncapi.yaml
php artisan spec:generate --type=postman --output=docs/collection.json

Stdout vs --output= and DiscoveryReport Behavior

All spec commands inspect the discovery report after building the specification:

  • Without --output=: The generated specification is printed to stdout. If the discovery report contains any warnings or errors, the rendered DiscoveryReport is written to stderr, keeping stdout clean for shell redirection:

    php artisan spec:openapi > openapi.json
    
  • With --output=: The specification is written to the target path (creating missing parent directories automatically). If the discovery report contains warnings or errors, it is printed to standard console output after the confirmation message.

Example report output when gaps or skipped routes are detected:

═══ Discovery Report ═══

⚠ [routes] Skipping closure/invalid route: debug/ping
⚠ [request_body] No FormRequest for POST /api/items (ItemController::store)
⚠ [response] No JsonResource return type for GET /api/stats (StatsController::index)

Tip: Add FormRequests, JsonResource return types, or use attributes to fill gaps.

php artisan about Integration

The service provider registers a Laravel API Specs section in php artisan about displaying the configured OpenAPI version, AsyncAPI version, and whether Auto Discovery is ENABLED or DISABLED.


Auto-Discovery vs Explicit Mode

The auto_discovery flag in config/api-spec.php controls how aggressively the engine infers schema metadata:

  • auto_discovery = true (default): Discovers all non-fallback, non-blocklisted controller routes and infers tags, operationId, FormRequest request bodies, JsonResource response schemas, Eloquent model schemas, middleware security schemes, and convention-based events/observers.
  • auto_discovery = false (explicit mode):
    • OpenAPI / Postman: Only routes whose controller method has explicit metadata—a PHPDoc block or at least one of #[Operation], #[QueryParameter], or #[Response]—are included. Automatic tag extraction, Tag.method operationId generation, FormRequest body inference, JsonResource return-type inference, middleware security mapping, model scanning, and resource directory scanning are disabled. Explicit attributes, PHPDoc summary/description/@deprecated, path parameters, named route operationIds, and JsonResource schemas referenced via #[Response(resource: ...)] or method return types on included routes still appear.
    • AsyncAPI: Convention-based event and observer discovery is disabled, while #[AsyncApiChannel] attribute discovery remains active in both auto_discovery = true and auto_discovery = false modes.

Routes, Path Parameters, Operation IDs & CRUD Semantics

RouteDiscovery iterates over registered Laravel routes (skipping fallback routes, route_blocklist matches, closure/invalid actions, and methods/classes marked with #[ExcludeRoute]):

  • Path parameters: Extracted from route URI placeholders ({id}, {slug?} marks required: false). Parameter types are resolved from matching controller method parameter type hints (int -> integer, float -> number, bool -> boolean, otherwise string), and any $route->wheres regex constraints are attached as schema.pattern.
  • Tags & operationId: In auto-discovery mode, the default tag is the controller short name without Controller (e.g., ProductController -> Product). The base operationId uses $route->getName() if named, or Tag.method otherwise. Invokable controllers (__invoke) map to Tag.invoke.
  • Multi-method & duplicate operationId disambiguation: When a single route responds to multiple HTTP methods (excluding HEAD), DiscoveryEngine appends the lowercase HTTP method (e.g., Product.update.put, Product.update.patch). Any remaining collisions across routes receive numeric suffixes (.2, .3, ...).
  • PHPDoc metadata: The first line of a controller method docblock becomes summary, subsequent non-tag lines become description, and @deprecated marks deprecated: true.
  • CRUD status codes: When no explicit #[Response] attribute is present, index defaults to 200, store to 201, destroy to 204 (No content with no response body), and other methods to 200.

FormRequest Two-Pass Rule Mapping

When a POST, PUT, or PATCH action type-hints a FormRequest subclass in auto-discovery mode, FormRequestDiscovery resolves the FormRequest through the service container—falling back to ReflectionClass::newInstanceWithoutConstructor() if container resolution throws ValidationException (from ValidatesWhenResolved) or any other Throwable—and compiles rules() into a schema tree where each field's rules are parsed in two passes:

  1. Base type resolution:
    • string, digits:* -> string
    • integer -> integer
    • numeric -> number
    • boolean -> boolean
    • array -> array (with items: {})
    • file, image -> string (format: binary)
    • date -> string (format: date)
    • email -> string (format: email)
    • url -> string (format: uri)
    • uuid -> string (format: uuid)
    • ip -> string (format: ipv4)
    • json -> object
    • Rule::enum(...) -> integer for int-backed BackedEnum, string for string-backed BackedEnum and UnitEnum
    • Unmatched rules default to string.
  2. Constraint application & required:
    • min:N, max:N, between:N,M -> minLength/maxLength on string, minItems/maxItems on array, minimum/maximum on integer/number
    • in:a,b,c and Rule::in(...) (scalars, BackedEnum values, and UnitEnum names) -> enum
    • Rule::enum(...) -> enum from BackedEnum values or UnitEnum case names, honoring only() and except()
    • regex:pattern -> pattern
    • digits:N -> type: string with pattern: ^\d{N}$
    • confirmed -> x-confirmed: true
    • required adds the field to the schema's required list unless nullable is also present.

Nested dot-notation keys compile into nested OpenAPI object and array schemas (including nested required arrays):

  • address.city compiles address as type: object with properties.city (and adds 'city' to address.required when required is present without nullable).
  • items.* compiles items as type: array with the element schema under items (preserving array constraints such as min or max defined on items).
  • items.*.name compiles items as an array of object items with nested properties.name and a nested required array inside items.items.

JsonResource AST Parsing

Controller return types (including union return types containing a JsonResource or ResourceCollection subclass) and #[Response(resource: ...)] references are analyzed via ResourceParser (nikic/php-parser):

  • ResourceCollection subclasses wrap the item schema in { type: "object", properties: { data: { type: "array", items: ... } } } and are inlined per endpoint rather than registered in components.schemas.
  • JsonResource subclasses are registered in components.schemas under their short class name.
  • Nested resource expressions (SomeResource::make(...), SomeResource::resolve(...), new SomeResource(...), SomeResource::collection(...)) pass through AST NameResolver, resolving aliased use imports before normalizing $ref targets to short class names (#/components/schemas/{ShortName}).
  • Conditional helpers:
    • $this->when(...) and $this->whenLoaded(...) inspect the second argument expression; single-argument $this->whenLoaded('rel') falls back to key-name heuristics. Passing null as the third argument produces a nullable schema.
    • $this->whenCounted(...) and $this->count(...) produce { type: "integer" }.
  • OpenAPI 3.1 nullable schemas:
    • Null-coalescing ($expr ?? null), ternaries returning null, null literals, and 3-arg when(..., ..., null) convert scalar types into OpenAPI 3.1 type arrays (e.g., ['string', 'null']) and $ref schemas into anyOf with ['type' => 'null'].
  • Key-name heuristics (ResourceParser::guessTypeFromKey()) when an expression cannot be statically typed:
    • id, *_id -> integer
    • count, count_*, *_count -> integer
    • *_at, *date* -> string (format: date-time)
    • is_*, has_* -> boolean
    • *price*, *amount*, *total* -> number (format: double)
    • Fallback -> string

Eloquent Models

In auto-discovery mode, ModelDiscovery scans configured model directories (app/Models by default) for non-abstract Model subclasses and registers schemas under components.schemas:

  1. Attempts Schema::getColumnListing($model->getTable()) (wrapped safely via rescue()).
  2. If no database connection or table columns are available, falls back to $model->getFillable(), prepending id if missing and appending created_at / updated_at when $model->usesTimestamps() is true. (Models with empty $fillable and no database columns yield an empty properties object.)
  3. Applies $hidden exclusions and $visible allowlists.
  4. Maps $casts first (int/integer/timestamp, real/float/double, decimal, bool/boolean, array, json/object/collection, date, datetime/immutable_datetime/custom variants), then falls back to column-name heuristics (id/*_id, *_at, date/date_*/*_date, is_*/has_*, *price*/*amount*/*total*, count*/*_count, email, uuid/*_uuid).

Middleware Security Mapping

MiddlewareDiscovery inspects route middleware against api-spec.middleware_map:

  • Exact match: e.g. auth:sanctum or auth.basic matches the exact key.
  • Prefix fallback: Parameterized middleware such as auth:api-token matches the first middleware_map entry sharing the same prefix before : (e.g., auth:*).
  • OAuth2 flows: Entries with 'type' => 'oauth2' in middleware_map automatically receive a clientCredentials flow using the entry's optional 'tokenUrl' value, falling back to url('/oauth/token') when omitted or empty.

Matched schemes are added to components.securitySchemes and attached to each operation's security array. When generating a Postman collection, PostmanCollection also maps operation security (bearer, basic, apiKey, and oauth2) from components.securitySchemes into each request's request.auth.

Events & Observers (AsyncAPI)

EventDiscovery scans the directories configured under scan.events and scan.observers:

  • Events (auto_discovery = true): Discovers classes implementing Illuminate\Contracts\Broadcasting\ShouldBroadcast, classes in directories whose path contains event (case-insensitive, excluding observers), or classes whose short name ends with Event (excluding *Observer). Constructor parameter types (int, float, bool, array, fallback string) build the message payload. ShouldBroadcast events prefix the channel address with broadcast..
  • Observers (auto_discovery = true): Discovers classes with an Observer suffix or in an observer directory that implement any of created, updated, deleted, restored, or forceDeleted. Strips Observer from the class name and derives the channel address prefix with Str::plural(Str::snake($modelName)) (e.g., OrderItemObserver::created -> channel address order_items.created), linking the payload $ref to #/components/schemas/{Model}.
  • #[AsyncApiChannel] (auto_discovery = true or false): Scans classes and methods in the configured event/observer directories for explicit channel attributes and merges them into the discovered channels. Only 'send' and 'receive' are valid action values; any other value triggers a warning in DiscoveryReport and defaults to 'send'.

PHP 8 Attributes Reference

All attributes live in Turker\LaravelApiSpecs\Attributes.

#[Operation]

Target: controller method. Overrides generated operation metadata.

use Turker\LaravelApiSpecs\Attributes\Operation;

#[Operation(id: 'catalog.listProducts', tags: ['Catalog', 'Products'], deprecated: true)]
public function index(): ProductCollection
{
    // ...
}

Parameters: id (?string), tags (?list<string>), deprecated (bool = false).

#[QueryParameter]

Target: controller method (repeatable). Declares OpenAPI query parameters (and Postman query params).

use Turker\LaravelApiSpecs\Attributes\QueryParameter;

#[QueryParameter(name: 'page', type: 'integer', minimum: 1, description: 'Page number')]
#[QueryParameter(name: 'status', type: 'string', enum: ['active', 'archived'], required: true)]
#[QueryParameter(name: 'search', type: 'string', minLength: 2, maxLength: 100, pattern: '^[a-zA-Z0-9 ]+$')]
public function index(): ProductCollection
{
    // ...
}

Parameters: name, type = 'string', format = null, description = null, required = false, enum = null, minimum = null, maximum = null, minLength = null, maxLength = null, pattern = null, example = null.

#[Response]

Target: controller method (repeatable). Replaces inferred responses for the operation with explicit definitions.

use Turker\LaravelApiSpecs\Attributes\Response;

#[Response(status: 200, description: 'Authenticated user', resource: UserResource::class)]
#[Response(status: 404, description: 'User not found', schema: 'ErrorResponse')]
#[Response(status: 422, description: 'Validation failed', schemaOverride: [
    'type' => 'object',
    'properties' => [
        'message' => ['type' => 'string'],
    ],
])]
public function show(int $id): JsonResponse
{
    // ...
}

Parameters: status = 200, description = null, resource = null, schema = null, schemaOverride = null.

  • When schemaOverride is provided, it is used directly as the response schema.
  • When resource is a JsonResource class, ResourceParser parses it for the response and registers the resource in components.schemas (if not a ResourceCollection).
  • When schema is provided, it emits ['$ref' => '#/components/schemas/' . $schema].

#[ExcludeRoute]

Target: controller class or controller method. Excludes an entire controller or an individual action from route discovery in both auto_discovery modes.

use Turker\LaravelApiSpecs\Attributes\ExcludeRoute;

#[ExcludeRoute]
class InternalHealthController
{
    // All methods excluded
}

class UserController
{
    #[ExcludeRoute]
    public function debug(): void
    {
        // Excluded from generated specs
    }
}

#[AsyncApiChannel]

Target: class or method (repeatable). Declares an explicit AsyncAPI channel. Works in both auto_discovery = true and auto_discovery = false modes for classes located in the configured scan.events / scan.observers directories.

use Turker\LaravelApiSpecs\Attributes\AsyncApiChannel;

#[AsyncApiChannel(
    address: 'orders.created',
    action: 'send',
    description: 'Emitted when a new order is placed',
    messageSchema: 'Order',
)]
class OrderCreated
{
    // ...
}

Parameters: address (string), action ('send'|'receive', default 'send'), description (?string = null), messageSchema (?string = null, resolves to #/components/schemas/{messageSchema}).


Configuration Reference & Gotchas

config/api-spec.php:

return [
    'auto_discovery' => true,
    'route_blocklist' => [
        '_debug*',
    ],

    'openapi' => [
        'version' => '3.1.0',
        'info' => [
            'title' => 'Laravel API',
            'version' => '1.0.0',
            'description' => null,
            'termsOfService' => null,
            'contact' => null,
            'license' => null,
        ],
        'servers' => [
            // A null url falls back to config('app.url', 'http://localhost') at runtime.
            ['url' => null, 'description' => 'Default'],
        ],
        'tags' => [],
        'security' => [],
    ],

    'asyncapi' => [
        'version' => '3.1.0',
        'id' => null,
        'info' => [
            'title' => 'Laravel Async API',
            'version' => '1.0.0',
            'description' => null,
        ],
        'servers' => [],
        'default_content_type' => 'application/json',
    ],

    'postman' => [
        'info' => [
            'name' => 'Laravel API Collection',
            'schema' => 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json',
        ],
        'variable' => [
            // A null value falls back to config('app.url', 'http://localhost') at runtime.
            ['key' => 'base_url', 'value' => null],
        ],
    ],

    // null scans the default app/* directory; [] disables scanning that category.
    'scan' => [
        'models' => null,
        'events' => null,
        'observers' => null,
        'resources' => null,
    ],

    // Keys also match parameterized variants by prefix before ':' (e.g., auth:sanctum matches auth:api-token).
    'middleware_map' => [
        'auth:sanctum' => ['type' => 'http', 'scheme' => 'bearer', 'bearerFormat' => 'JWT'],
        'auth:api' => ['type' => 'oauth2'],
        'auth.basic' => ['type' => 'http', 'scheme' => 'basic'],
        'auth.session' => ['type' => 'apiKey', 'in' => 'cookie', 'name' => 'laravel_session'],
    ],
];

Runtime Defaults & Config Merging

  • Runtime URL and title resolution: Leaving openapi.servers[0].url or postman.variable[0].value (base_url) as null resolves config('app.url', 'http://localhost') at generation time. Default titles ('Laravel API', 'Laravel Async API', 'Laravel API Collection') resolve dynamically from config('app.name', 'Laravel API').
  • Recursive config merging: The service provider recursively merges associative arrays while replacing list arrays wholesale. Overriding openapi.info.title preserves sibling openapi.info keys; overriding route_blocklist or openapi.servers replaces that list.
  • scan behavior (null vs []):
    • null scans [app_path('Models')], [app_path('Events')], and [app_path('Observers')] respectively (resources defaults to [] when null, since resources referenced by routes or #[Response] are already parsed automatically).
    • [] explicitly disables directory scanning for that category.

Practical Gotchas

  • Closure routes are skipped: Only controller class methods and invokable controllers are included.
  • FormRequest constructor/container side effects: FormRequestDiscovery resolves FormRequest classes via the container before falling back to newInstanceWithoutConstructor() on ValidationException or other throwables. Avoid side effects in FormRequest constructors or prepareForValidation() that shouldn't run during CLI generation.
  • Database connection fallback in ModelDiscovery: If the CLI environment cannot connect to the database (for example, in CI without a live DB), Schema::getColumnListing() fails silently via rescue() and falls back to $fillable + timestamps. Ensure $fillable is defined or run generation with access to the schema if you want full model property coverage.
  • #[AsyncApiChannel] scan scope: Explicit #[AsyncApiChannel] attributes are discovered inside the directories configured in scan.events and scan.observers. If you place annotated classes elsewhere (such as app/Listeners), add that directory to scan.events.

Development & Quality Checks

Run the project checks locally with Composer:

# Run code style, static analysis, and tests together
composer check

# Individual checks
composer test
composer phpstan
composer phpcs

For contributors and AI agents working on this repository, see docs/INDEX.md. Source repository and issue tracker: https://github.com/turkeryildirim/laravel-api-specs.


License

The MIT License (MIT). Please see LICENSE.md for more information.