Laravel · OpenAPI 3.x

Swagger Laravel Autogenerate

Automatically generate OpenAPI (Swagger) documentation from your Laravel routes, validation rules, and optional controller inference—less manual spec maintenance, faster iteration.

I Stand with IRAN

Overview

Composer package g4t/swagger registers a service provider that exposes a Swagger UI page and a JSON OpenAPI endpoint. The spec is built from registered application routes (URI, HTTP methods, middleware, tags) and can incorporate FormRequest rules for request schemas and parameters.

Optional features include inferred response examples from controllers, error/validation examples, per-route documentation helpers, basic auth for the UI, cached static JSON for faster responses, and an experimental mock-server workflow.

Package statistics

Live numbers from the Packagist package JSON for g4t/swagger (installs, GitHub signals, and favorites).

Total installs
Monthly
Daily
GitHub stars
Forks
Open issues
Watchers
Packagist favorites
Dependents
Suggesters

Source: packagist.org/packages/g4t/swagger · Updates when you refresh the page.

Features

  • OpenAPI 3.x JSON from registered routes
  • FormRequest rules drive request schemas and query/path parameters where applicable
  • Optional inferred success responses (infer_response_examples): literals, JsonResource, response()->json(...), and more
  • Optional inferred errors (infer_error_response_examples): JSON with status, abort(), validation-style 422 when rules warrant it
  • storage/swagger/… JSON overrides for per-route response examples when enabled
  • Faster JSON: when not in static-only mode, serve public/{cached_spec_path} if present (use_cached_spec_when_present)
  • Route macros: ->description(), ->summary(), ->hiddenDoc()
  • Controller attribute: #[SwaggerSection('…')]
  • Optional basic authentication for the documentation UI
  • Commands: swagger:cache, make:swagger, experimental swagger:mock-server

Installation

Require the package with Composer:

composer require g4t/swagger

Laravel will auto-discover G4T\Swagger\SwaggerServiceProvider via composer.json extra configuration.

Publish configuration

php artisan vendor:publish --provider "G4T\Swagger\SwaggerServiceProvider"

Edit config/swagger.php for titles, URL prefix, versions, inference flags, cache path, auth, and servers.

Usage

Video walkthrough

Watch on YouTube — how to use the package in a Laravel app.

  1. Publish config/swagger.php (see Installation).
  2. Adjust title, URL prefix, versions, inference flags, cached_spec_path / use_cached_spec_when_present, etc.
  3. Open the UI at /{swagger.url} (default: /swagger/documentation), e.g. https://your-app.test/swagger/documentation.
  4. The issues page is at swagger.issues_url (default: /swagger/issues).

Route description

Route::get('user', [UserController::class, 'index'])
    ->description('Get list of users with pagination.');

Short summary

Route::get('user', [UserController::class, 'index'])
    ->summary('get users.');

Hide from docs

Route::get('user', [UserController::class, 'index'])->hiddenDoc();

Controller section (OpenAPI tag grouping)

<?php

namespace App\Http\Controllers;

use G4T\Swagger\Attributes\SwaggerSection;

#[SwaggerSection('everything about your users')]
class UserController extends Controller
{
    // ...
}

Documentation basic auth

In config/swagger.php:

"enable_auth" => false,
"username" => "admin",
"password" => "pass",
"sesson_ttl" => 100000,

Set enable_auth to true in production if you need to protect the UI.

Documentation routes

Routes are registered under the configured paths (defaults shown):

Path Purpose
GET /{swagger.url} Swagger UI (default: /swagger/documentation)
GET /{swagger.url}/json OpenAPI JSON; optional ?version= filter per config('swagger.versions')
GET /{swagger.issues_url} Issues helper page (default: /swagger/issues)

All of the above run behind BasicAuthentication middleware when auth is enabled in config.

Artisan commands

Command Description
make:swagger Writes OpenAPI JSON to public/{cached_spec_path} (default doc.json). Legacy alias; same destination as swagger:cache.
swagger:cache Regenerates cached spec to public/{cached_spec_path}. swagger:cache --clear removes the file. Generation skipped when swagger.enable is false (clear still works).
swagger:mock-server Optional G4T-hosted mock workflow (experimental).
php artisan make:swagger
php artisan swagger:cache
php artisan swagger:cache --clear
php artisan swagger:mock-server

OpenAPI export & caching

After make:swagger or swagger:cache, the file is written to:

  • Path: public_path(config('swagger.cached_spec_path', 'doc.json'))
  • Encoding: JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE

Regenerate after changing routes, controllers, FormRequests, or resources when you rely on a cached file for the JSON endpoint.

JSON endpoint resolution

The /{swagger.url}/json response is resolved by DocumentationController::resolveSwaggerSpecification():

load_from_json Behavior
true Only the file at public/{cached_spec_path} is used; missing or invalid file yields an empty array [].
false If use_cached_spec_when_present is true and the file exists with valid JSON, that file is served; otherwise the spec is built live from routes.

Environment keys: SWAGGER_CACHED_SPEC_PATH, SWAGGER_USE_CACHED_SPEC (set to false to force live generation without deleting the file).

Mock server (experimental)

Experimental: The mock feature is under testing. It may change without much notice. Do not rely on it for critical production paths.

G4T provides an optional command that connects your auto-generated API documentation to a hosted mock experience so you can explore or demo your API surface more easily.

php artisan swagger:mock-server

Configure mock_server_url (default https://mock.g4t.io), and optionally MOCK_SERVER_APP_ID in .env to target a specific app without prompts.

Configuration reference

All keys live in config/swagger.php after publishing. Common environment variables are noted.

Key Description
titleAPI documentation title. Env: SWAGGER_TITLE.
descriptionAPI description. SWAGGER_DESCRIPTION.
emailContact email in spec. SWAGGER_EMAIL.
versionDocument version string. SWAGGER_VERSION.
enable_auth, username, password, sesson_ttlBasic auth for Swagger UI and JSON/issue routes.
enable_response_schemaToggle response schema generation.
infer_response_examplesInfer success examples from controllers.
infer_error_response_examplesInfer error/validation examples.
unwrap_resource_collection_examplesNon-paginated Resource::collection as top-level JSON array.
omit_default_404_for_showHide default 404 on show GET unless a real example exists.
suggestions_select_inputUI-related suggestions control.
load_from_jsonStatic-file-only OpenAPI mode when true.
cached_spec_pathFile under public/. SWAGGER_CACHED_SPEC_PATH.
use_cached_spec_when_presentServe cache when load_from_json is false. SWAGGER_USE_CACHED_SPEC.
mock_server_url, mock_server_app_idMock upload endpoint and app id. MOCK_SERVER_URL, MOCK_SERVER_APP_ID.
auth_middlewaresMiddleware names treated as auth (e.g. auth, auth:api).
urlDocumentation UI path. SWAGGER_URL.
issues_urlIssues page path. SWAGGER_ISSUE_URL.
enableMaster switch. SWAGGER_ENABLED.
show_prefixOnly document routes whose URI starts with these prefixes (empty = all allowed by other rules).
include_web_routesInclude web.php routes. SWAGGER_INCLUDE_WEB_ROUTES.
versions, defaultVersion dropdown in UI; JSON filtered via ?version=.
serversOpenAPI servers array (uses APP_URL by default).
security_schemesDeclared security schemes (e.g. header API keys).
spatie_query_builderEnable Spatie Query Builder filter hints on GET routes.
statusOptional per-method default status map; combine with inferred examples and storage/swagger JSON.

Resources