wadakatu/laravel-spectrum

Zero-annotation API documentation generator for Laravel and Lumen

v0.0.1-alpha 2025-07-07 13:52 UTC

This package is auto-updated.

Last update: 2025-07-08 04:21:09 UTC


README

Laravel Spectrum Banner

Latest Version

Tests Code Coverage Latest Stable Version Total Downloads License PHP Version Require

🎯 Zero-annotation API documentation generator for Laravel & Lumen

Transform your existing Laravel/Lumen APIs into comprehensive OpenAPI documentation without writing a single annotation or modifying your code.

✨ Key Features

🚀 Zero Configuration

Automatically detects and documents your API routes without any annotations or comments

📝 Smart Request Analysis

  • Laravel FormRequest automatic parsing
  • Lumen inline validation support
  • Type inference from validation rules
  • Custom messages & attributes

📦 Flexible Response Handling

  • Laravel API Resources analysis
  • Fractal Transformer support
  • Automatic includes detection
  • Multiple format compatibility

🛡️ Complete Error Documentation

  • 422 validation errors auto-generation
  • Authentication errors (401/403) detection
  • Custom error response mapping

🔐 Security & Authentication

  • Bearer Token auto-detection
  • API Key authentication support
  • Sanctum/Passport compatibility
  • Security scheme generation

🔥 Developer Experience

  • Real-time preview with hot-reload
  • File change auto-detection
  • WebSocket live updates
  • Intelligent caching system

📸 Demo

# Generate your API documentation instantly
php artisan spectrum:generate

# Watch mode for real-time updates
php artisan spectrum:watch

Laravel Spectrum Demo

🔧 Requirements

  • PHP 8.1 or higher
  • Laravel 10.x, 11.x, or 12.x / Lumen 10.x, 11.x, 12.x
  • Composer 2.0 or higher

📦 Installation

composer require wadakatu/laravel-spectrum

That's it! No configuration needed to get started.

🚀 Quick Start

1. Generate Documentation

# Generate OpenAPI documentation
php artisan spectrum:generate

# Generate in YAML format
php artisan spectrum:generate --format=yaml

# Custom output path
php artisan spectrum:generate --output=public/api-docs.json

2. Real-time Preview (Development)

# Start the watcher with live reload
php artisan spectrum:watch

# Visit http://localhost:8080 to see your documentation

3. View with Swagger UI

<!-- Add to your blade template -->
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js"></script>
<script>
SwaggerUIBundle({
    url: "/api-documentation.json",
    dom_id: '#swagger-ui',
})
</script>

📖 Usage Examples

Laravel FormRequest Example

// app/Http/Requests/StoreUserRequest.php
class StoreUserRequest extends FormRequest
{
    public function rules()
    {
        return [
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users',
            'password' => 'required|string|min:8|confirmed',
            'age' => 'nullable|integer|min:18|max:120',
            'roles' => 'array',
            'roles.*' => 'exists:roles,id',
        ];
    }

    public function messages()
    {
        return [
            'email.unique' => 'This email is already registered.',
        ];
    }
}

// Controller - automatically documented!
public function store(StoreUserRequest $request)
{
    $user = User::create($request->validated());
    return new UserResource($user);
}

Laravel API Resource Example

// app/Http/Resources/UserResource.php
class UserResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'email_verified' => $this->email_verified_at !== null,
            'roles' => RoleResource::collection($this->whenLoaded('roles')),
            'created_at' => $this->created_at->toDateTimeString(),
            'profile' => new ProfileResource($this->whenLoaded('profile')),
        ];
    }
}

Fractal Transformer Example

// app/Transformers/UserTransformer.php
class UserTransformer extends TransformerAbstract
{
    protected $availableIncludes = ['posts', 'profile', 'followers'];
    protected $defaultIncludes = ['profile'];
    
    public function transform(User $user)
    {
        return [
            'id' => (int) $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'member_since' => $user->created_at->toDateString(),
            'is_active' => (bool) $user->is_active,
        ];
    }
    
    public function includePosts(User $user)
    {
        return $this->collection($user->posts, new PostTransformer());
    }
}

Lumen Inline Validation Example

// Lumen Controller with inline validation
public function store(Request $request)
{
    // Automatically detected and documented!
    $this->validate($request, [
        'title' => 'required|string|max:255',
        'content' => 'required|string',
        'status' => 'required|in:draft,published',
        'tags' => 'array',
        'tags.*' => 'string|max:50',
    ]);

    $post = Post::create($request->all());
    
    return $this->fractal->item($post, new PostTransformer());
}

Authentication Configuration

// Automatically detects authentication methods
Route::middleware('auth:sanctum')->group(function () {
    Route::apiResource('users', UserController::class);
});

// API Key authentication
Route::middleware('auth.apikey')->group(function () {
    Route::get('/stats', StatsController::class);
});

⚙️ Configuration

Publish the configuration file for advanced customization:

php artisan vendor:publish --tag=spectrum-config

Configuration Options

// config/spectrum.php
return [
    // API Information
    'title' => env('APP_NAME', 'Laravel API'),
    'version' => '1.0.0',
    'description' => 'API Documentation',
    
    // Server Configuration
    'servers' => [
        [
            'url' => env('APP_URL'),
            'description' => 'Production server',
        ],
    ],
    
    // Route Detection
    'route_patterns' => [
        'api/*',        // Include all /api routes
        'api/v1/*',     // Version-specific routes
        'api/v2/*',
    ],
    
    'excluded_routes' => [
        'api/health',   // Exclude health checks
        'api/debug/*',  // Exclude debug endpoints
    ],
    
    // Response Formats
    'response_formats' => [
        'resource' => true,     // Laravel Resources
        'fractal' => true,      // Fractal Transformers
        'json' => true,         // Plain JSON responses
    ],
    
    // Security Schemes
    'security_schemes' => [
        'bearer' => [
            'type' => 'http',
            'scheme' => 'bearer',
            'bearerFormat' => 'JWT',
        ],
        'apiKey' => [
            'type' => 'apiKey',
            'in' => 'header',
            'name' => 'X-API-Key',
        ],
    ],
    
    // Cache Configuration
    'cache' => [
        'enabled' => env('SPECTRUM_CACHE_ENABLED', true),
        'ttl' => 3600, // 1 hour
    ],
    
    // Watch Mode Settings
    'watch' => [
        'port' => 8080,
        'host' => '127.0.0.1',
        'open_browser' => true,
    ],
];

🎯 Advanced Features

Custom Type Mappings

// config/spectrum.php
'type_mappings' => [
    'json' => ['type' => 'object'],
    'uuid' => ['type' => 'string', 'format' => 'uuid'],
    'decimal' => ['type' => 'number', 'format' => 'float'],
],

Response Examples

// Automatically generates examples from your Resources
class ProductResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'price' => $this->price,
            'currency' => 'USD',
            'in_stock' => $this->quantity > 0,
            'meta' => [
                'sku' => $this->sku,
                'weight' => $this->weight,
            ],
        ];
    }
}

Error Response Customization

// Automatic 422 validation error format
{
    "message": "The given data was invalid.",
    "errors": {
        "email": [
            "The email field is required.",
            "The email must be a valid email address."
        ]
    }
}

// Custom error responses
class Handler extends ExceptionHandler
{
    public function render($request, Throwable $exception)
    {
        if ($exception instanceof ModelNotFoundException) {
            return response()->json([
                'error' => 'Resource not found',
                'code' => 'RESOURCE_NOT_FOUND'
            ], 404);
        }
        
        return parent::render($request, $exception);
    }
}

🔧 Troubleshooting

Common Issues

Q: Documentation is not generating for some routes

# Check registered routes
php artisan route:list --path=api

# Clear cache
php artisan spectrum:clear-cache

Q: FormRequest validation rules not detected

# Ensure FormRequest is properly type-hinted
public function store(StoreUserRequest $request) // ✅ Correct
public function store(Request $request) // ❌ Won't detect custom rules

Q: Fractal includes not appearing

# Define available includes in transformer
protected $availableIncludes = ['posts', 'profile']; // ✅ Will be documented

🤝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

# Setup development environment
git clone https://github.com/wadakatu/laravel-spectrum.git
cd laravel-spectrum
composer install

# Run tests
composer test

# Run static analysis
composer analyze

# Fix code style
composer format:fix

📄 License

The MIT License (MIT). Please see License File for more information.

Made with ❤️ by Wadakatu
Star ⭐ this repo if you find it helpful!