Laravel Spectrum Documentation

website·Indexed 30 days ago

https://docs.laravel-spectrum.dev

Searchable website documentation for Laravel Spectrum from https://docs.laravel-spectrum.dev.

Tokens
51.7K
Snippets
280
Records
304
Agent score
49%

What's inside Laravel Spectrum Documentation

  1. Overview of Laravel Spectrum API Documentation Generator

    Laravel Spectrum is an intelligent API documentation generator specifically designed for Laravel and Lumen. Unlike traditional tools, it eliminates the need for manual PHPDoc annotations or YAML file maintenance by analyzing the source code to automatically generate comprehensive OpenAPI documentation.
  2. Overview of Laravel Spectrum

    Laravel Spectrum is a zero-annotation API documentation generation tool for Laravel. It analyzes existing code to automatically generate OpenAPI 3.0 specification documentation without requiring the developer to write annotations or comments.
  3. Document standard HTTP error responses

    Laravel Spectrum automatically detects and documents standard HTTP error responses returned as JSON. This includes common status codes such as 400 (Bad Request), 401 (Unauthorized), 403 (Forbidden), 404 (Not Found), 422 (Unprocessable Entity), and 500 (Internal Server Error).
    // 400 Bad Request
    return response()->json([
        'message' => 'The given data was invalid.',
        'errors' => [
            'email' => ['The email field is required.'],
            'password' => ['The password field is required.']
        ]
    ], 400);
    
    // 401 Unauthorized
    return response()->json([
        'message' => 'Unauthenticated.'
    ], 401);
    
    // 403 Forbidden
    return response()->json([
        'message' => 'This action is unauthorized.'
    ], 403);
    
    // 404 Not Found
    return response()->json([
        'message' => 'Resource not found.'
    ], 404);
    
    // 422 Unprocessable Entity
    return response()->json([
        'message' => 'The given data was invalid.',
        'errors' => $validator->errors()
    ], 422);
    
    // 500 Internal Server Error
    return response()->json([
        'message' => 'Server Error'
    ], 500);
  4. Recommended Laravel Spectrum setup paths by project type

    Depending on your project's current state, follow these recommended documentation paths to implement Laravel Spectrum:

    • New Projects: Installation and Configuration $\rightarrow$ Basic Usage $\rightarrow$ Features Overview.
    • Existing Projects: Installation and Configuration $\rightarrow$ Migration Guide $\rightarrow$ Troubleshooting.
    • Large Projects: Performance Optimization $\rightarrow$ CI/CD Integration $\rightarrow$ Customization.
    • API Testing Tool Integration: Export Features $\rightarrow$ Authentication Setup $\rightarrow$ CI/CD Integration.
  5. Detect authentication middleware for OpenAPI documentation

    Laravel Spectrum automatically detects common Laravel authentication middleware applied to API routes and reflects the corresponding security requirements and 401 Unauthenticated responses in the generated OpenAPI schema. Supported middleware include Sanctum (auth:sanctum), JWT (auth:api), and multiple guard combinations.
    // Sanctum authentication
    Route::middleware('auth:sanctum')->group(function () {
        Route::get('/api/profile', [ProfileController::class, 'show']);
    });
    
    // JWT authentication
    Route::middleware('auth:api')->group(function () {
        Route::apiResource('api/posts', PostController::class);
    });
    
    // Multiple guards
    Route::middleware(['auth:sanctum,api'])->group(function () {
        Route::post('/api/admin/users', [AdminController::class, 'createUser']);
    });
  6. Laravel Spectrum Documentation Overview

    Laravel Spectrum provides a comprehensive suite of tools for API documentation. The documentation is organized into the following primary sections:

    • Getting Started: Installation, configuration, basic usage, and a 5-minute Quick Start guide.
    • Feature Guides: Details on validation detection (FormRequest), response analysis (API Resources, Fractal, pagination), authentication setup (JWT, Sanctum, OAuth2), and the Mock Server for launching API servers from OpenAPI docs.
    • Advanced Usage: Performance optimization, parallel processing, exporting to Postman/Insomnia, customization, and CI/CD integration.
    • Reference: CLI Artisan commands, config/spectrum.php settings, and programmatic API hooks.
    • Troubleshooting: Common problems, FAQ, and known issues.
    • Other Resources: Tool comparisons (vs Swagger-PHP, Scribe, L5-Swagger), migration guides, and contribution guidelines.
  7. Laravel Spectrum Artisan Command Overview

    Laravel Spectrum provides a suite of Artisan commands for managing OpenAPI documentation, including generation, validation, and export tools.
    spectrum:generate           - Generate OpenAPI documentation
    spectrum:generate:optimized  - Optimized generation (for large projects)
    spectrum:watch               - Real-time preview mode
    spectrum:mock                - Launch mock API server
    spectrum:export:postman      - Export to Postman collection
    spectrum:export:insomnia     - Export to Insomnia workspace
    spectrum:sdk                 - Generate typed SDK client code
    spectrum:validate            - Validate OpenAPI spec compliance
    spectrum:diff                - Compare two OpenAPI specs and detect breaking changes
    spectrum:version-compare     - Alias of spectrum:diff with migration-focused reporting
    spectrum:cache               - Manage cache (clear, stats, warm)
  8. Document validation using the Validator Facade

    Validation rules defined via the Validator::make() facade are also detected by Laravel Spectrum.
    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'sometimes|required|string|max:255',
            'status' => 'sometimes|required|in:active,inactive',
        ]);
    
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }
    
        // ...
    }
  9. Handle complex conditional validation with Rule::when

    Laravel Spectrum can process complex conditional logic using Illuminate sValidation sRule::when. This is useful for nested conditions or logic that cannot be expressed via simple required_if strings.
    use Illuminate	sValidation	sRule;
    
    public function rules()
    {
        return [
            'subscription_type' => 'required|in:free,basic,premium,enterprise',
            
            'payment_method' => Rule::when(
                $this->subscription_type !== 'free',
                ['required', 'in:credit_card,paypal,bank_transfer,invoice'],
                'nullable'
            ),
            
            'billing_cycle' => Rule::when(
                in_array($this->subscription_type, ['basic', 'premium']),
                ['required', 'in:monthly,yearly'],
                Rule::when(
                    $this->subscription_type === 'enterprise',
                    ['required', 'in:monthly,quarterly,yearly,custom'],
                    'nullable'
                )
            ),
        ];
    }
  10. Migrate from API Blueprint to Laravel Spectrum

    When migrating from .apib files, verify the route structure against the actual Laravel routes and convert Blueprint data structures into Laravel Resources and FormRequests.
    # Verify route structure to match Blueprint
    php artisan route:list --path=api
  11. Best practices for writing detectable conditional validation

    To ensure Laravel Spectrum can accurately detect and document your conditional rules, follow these guidelines:

    • Use Clear Conditions: Avoid overly complex boolean logic in a single line. Use intermediate variables to make conditions readable.
    • Group Conditions: Use helper methods to return arrays of rules for specific scenarios and merge them into the main rules() method.
    • Custom Messages: Provide clear validation messages in the messages() method to improve API consumer experience.
    // Grouping conditions example
    protected function personalInfoRules(): array
    {
        return [
            'first_name' => 'required|string',
            'last_name' => 'required|string',
            'date_of_birth' => 'required|date',
        ];
    }
    
    public function rules()
    {
        $rules = ['user_type' => 'required|in:personal,business'];
        
        if ($this->user_type === 'personal') {
            $rules = array_merge($rules, $this->personalInfoRules());
        } else {
            $rules = array_merge($rules, $this->businessInfoRules());
        }
        
        return $rules;
    }
  12. Migrate from L5-Swagger to Laravel Spectrum

    Since L5-Swagger is a wrapper for Swagger-PHP, follow the Swagger-PHP migration steps. Additionally, disable L5-Swagger routes and update the Swagger UI view to point to the Spectrum JSON output.
    // 1. Disable L5-Swagger routes in config/l5-swagger.php
    'routes' => [
        'api' => false,
    ],
    
    // 2. Update Swagger UI view (resources/views/api/documentation.blade.php)
    <script>
    SwaggerUIBundle({
        url: "{{ asset('storage/app/spectrum/openapi.json') }}",
    });
    </script>