turkeryildirim / laravel-api-specs
Auto-generate OpenAPI 3.1, AsyncAPI 3.1 and Postman specs from Laravel projects
Package info
github.com/turkeryildirim/laravel-api-specs
pkg:composer/turkeryildirim/laravel-api-specs
Requires
- php: ^8.2
- ext-json: *
- laravel/framework: ^11.0|^12.0|^13.0
- nikic/php-parser: ^5.0
- symfony/yaml: ^7.0|^8.0
Requires (Dev)
- larastan/larastan: ^3.15
- orchestra/testbench: ^9.0|^10.0|^11.0
- phpstan/phpstan: ^2.3
- phpunit/phpunit: ^11.0|^12.0
- squizlabs/php_codesniffer: ^4.0
- turkeryildirim/phpunit-json-coverage-report: ^1.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
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
- What It Does NOT Do / When Not to Use It
- Requirements & Installation
- Usage & Artisan Commands
- Auto-Discovery vs Explicit Mode
- PHP 8 Attributes Reference
- Configuration Reference & Gotchas
- Development & Quality Checks
- License
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,FormRequestrules,JsonResource/ResourceCollectionreturn types, Eloquent models, and route middleware. - AsyncAPI
3.1.0(JSON or YAML) from Laravel events,ShouldBroadcastevents, Eloquent observers, and#[AsyncApiChannel]attributes. - Postman Collection
v2.1(JSON) grouped by controller tag with path variables, query parameters,{{base_url}},request.authsecurity 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 directreturn [...]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 renderedDiscoveryReportis 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,FormRequestrequest bodies,JsonResourceresponse 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.methodoperationIdgeneration,FormRequestbody inference,JsonResourcereturn-type inference, middleware security mapping, model scanning, and resource directory scanning are disabled. Explicit attributes, PHPDoc summary/description/@deprecated, path parameters, named routeoperationIds, andJsonResourceschemas 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 bothauto_discovery = trueandauto_discovery = falsemodes.
- OpenAPI / Postman: Only routes whose controller method has explicit metadata—a PHPDoc block or at least one of
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?}marksrequired: false). Parameter types are resolved from matching controller method parameter type hints (int->integer,float->number,bool->boolean, otherwisestring), and any$route->wheresregex constraints are attached asschema.pattern. - Tags &
operationId: In auto-discovery mode, the default tag is the controller short name withoutController(e.g.,ProductController->Product). The baseoperationIduses$route->getName()if named, orTag.methodotherwise. Invokable controllers (__invoke) map toTag.invoke. - Multi-method & duplicate
operationIddisambiguation: When a single route responds to multiple HTTP methods (excludingHEAD),DiscoveryEngineappends 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 becomedescription, and@deprecatedmarksdeprecated: true. - CRUD status codes: When no explicit
#[Response]attribute is present,indexdefaults to200,storeto201,destroyto204(No contentwith no response body), and other methods to200.
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:
- Base type resolution:
string,digits:*->stringinteger->integernumeric->numberboolean->booleanarray->array(withitems: {})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->objectRule::enum(...)->integerforint-backedBackedEnum,stringforstring-backedBackedEnumandUnitEnum- Unmatched rules default to
string.
- Constraint application &
required:min:N,max:N,between:N,M->minLength/maxLengthonstring,minItems/maxItemsonarray,minimum/maximumoninteger/numberin:a,b,candRule::in(...)(scalars,BackedEnumvalues, andUnitEnumnames) ->enumRule::enum(...)->enumfromBackedEnumvalues orUnitEnumcase names, honoringonly()andexcept()regex:pattern->patterndigits:N->type: stringwithpattern: ^\d{N}$confirmed->x-confirmed: truerequiredadds the field to the schema'srequiredlist unlessnullableis also present.
Nested dot-notation keys compile into nested OpenAPI object and array schemas (including nested required arrays):
address.citycompilesaddressastype: objectwithproperties.city(and adds'city'toaddress.requiredwhenrequiredis present withoutnullable).items.*compilesitemsastype: arraywith the element schema underitems(preserving array constraints such asminormaxdefined onitems).items.*.namecompilesitemsas anarrayofobjectitems with nestedproperties.nameand a nestedrequiredarray insideitems.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):
ResourceCollectionsubclasses wrap the item schema in{ type: "object", properties: { data: { type: "array", items: ... } } }and are inlined per endpoint rather than registered incomponents.schemas.JsonResourcesubclasses are registered incomponents.schemasunder their short class name.- Nested resource expressions (
SomeResource::make(...),SomeResource::resolve(...),new SomeResource(...),SomeResource::collection(...)) pass through ASTNameResolver, resolving aliaseduseimports before normalizing$reftargets 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. Passingnullas 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 returningnull,nullliterals, and 3-argwhen(..., ..., null)convert scalar types into OpenAPI 3.1 type arrays (e.g.,['string', 'null']) and$refschemas intoanyOfwith['type' => 'null'].
- Null-coalescing (
- Key-name heuristics (
ResourceParser::guessTypeFromKey()) when an expression cannot be statically typed:id,*_id->integercount,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:
- Attempts
Schema::getColumnListing($model->getTable())(wrapped safely viarescue()). - If no database connection or table columns are available, falls back to
$model->getFillable(), prependingidif missing and appendingcreated_at/updated_atwhen$model->usesTimestamps()is true. (Models with empty$fillableand no database columns yield an emptypropertiesobject.) - Applies
$hiddenexclusions and$visibleallowlists. - Maps
$castsfirst (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:sanctumorauth.basicmatches the exact key. - Prefix fallback: Parameterized middleware such as
auth:api-tokenmatches the firstmiddleware_mapentry sharing the same prefix before:(e.g.,auth:*). - OAuth2 flows: Entries with
'type' => 'oauth2'inmiddleware_mapautomatically receive aclientCredentialsflow using the entry's optional'tokenUrl'value, falling back tourl('/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 implementingIlluminate\Contracts\Broadcasting\ShouldBroadcast, classes in directories whose path containsevent(case-insensitive, excluding observers), or classes whose short name ends withEvent(excluding*Observer). Constructor parameter types (int,float,bool,array, fallbackstring) build the message payload.ShouldBroadcastevents prefix the channel address withbroadcast.. - Observers (
auto_discovery = true): Discovers classes with anObserversuffix or in anobserverdirectory that implement any ofcreated,updated,deleted,restored, orforceDeleted. StripsObserverfrom the class name and derives the channel address prefix withStr::plural(Str::snake($modelName))(e.g.,OrderItemObserver::created-> channel addressorder_items.created), linking the payload$refto#/components/schemas/{Model}. #[AsyncApiChannel](auto_discovery = trueorfalse): 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 validactionvalues; any other value triggers a warning inDiscoveryReportand 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
schemaOverrideis provided, it is used directly as the response schema. - When
resourceis aJsonResourceclass,ResourceParserparses it for the response and registers the resource incomponents.schemas(if not aResourceCollection). - When
schemais 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].urlorpostman.variable[0].value(base_url) asnullresolvesconfig('app.url', 'http://localhost')at generation time. Default titles ('Laravel API','Laravel Async API','Laravel API Collection') resolve dynamically fromconfig('app.name', 'Laravel API'). - Recursive config merging: The service provider recursively merges associative arrays while replacing list arrays wholesale. Overriding
openapi.info.titlepreserves siblingopenapi.infokeys; overridingroute_blocklistoropenapi.serversreplaces that list. scanbehavior (nullvs[]):nullscans[app_path('Models')],[app_path('Events')], and[app_path('Observers')]respectively (resourcesdefaults to[]whennull, 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.
FormRequestconstructor/container side effects:FormRequestDiscoveryresolvesFormRequestclasses via the container before falling back tonewInstanceWithoutConstructor()onValidationExceptionor other throwables. Avoid side effects inFormRequestconstructors orprepareForValidation()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 viarescue()and falls back to$fillable+ timestamps. Ensure$fillableis 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 inscan.eventsandscan.observers. If you place annotated classes elsewhere (such asapp/Listeners), add that directory toscan.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.