Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

L5 Swagger Laravel Package

darkaonline/l5-swagger

Laravel package that wraps swagger-php and Swagger UI to generate and serve OpenAPI/Swagger documentation for your app. Provides Laravel-friendly installation, configuration, and routes to publish and view interactive API docs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require darkaonline/l5-swagger
    
  2. Publish the config:
    php artisan vendor:publish --provider="OpenApi\Generator\Laravel\L5SwaggerServiceProvider" --tag=l5-swagger-config
    
  3. Add annotations to a controller (e.g., app/Http/Controllers/Api/UserController.php):
    use OpenApi\Annotations as OA;
    
    /**
     * @OA\Get(
     *     path="/api/users",
     *     tags={"Users"},
     *     summary="Get all users",
     *     @OA\Response(response="200", description="List of users")
     * )
     */
    public function index()
    {
        return User::all();
    }
    
  4. Generate and serve the docs:
    php artisan l5-swagger:generate
    
  5. Access Swagger UI at /api/documentation (default route).

First Use Case: Quick API Documentation

  • Use @OA\Info in a base controller or service provider to define API metadata:
    /**
     * @OA\Info(title="My API", version="1.0")
     */
    
  • Run php artisan l5-swagger:generate to auto-scan annotated routes.
  • Visit /api/documentation to see an interactive UI with your API endpoints.

Implementation Patterns

1. Annotation-Based Documentation

  • Controllers: Annotate methods with @OA\Get, @OA\Post, etc., for route-level docs.
    /**
     * @OA\Post(
     *     path="/api/users",
     *     tags={"Users"},
     *     summary="Create a user",
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(ref="#/components/schemas/User")
     *     ),
     *     @OA\Response(response="201", description="User created")
     * )
     */
    public function store(Request $request)
    {
        // ...
    }
    
  • Models: Use @OA\Schema to define request/response schemas:
    /**
     * @OA\Schema(
     *     schema="User",
     *     type="object",
     *     required={"name", "email"},
     *     @OA\Property(property="name", type="string"),
     *     @OA\Property(property="email", type="string", format="email")
     * )
     */
    class User {}
    

2. Dynamic Documentation with Processors

  • Customize OpenAPI generation using processors (e.g., filter routes, modify schemas):
    // config/l5-swagger.php
    'processors' => [
        \OpenApi\Generator\Processor\FilterProcessor::class,
        \App\Swagger\CustomProcessor::class, // Your custom processor
    ],
    
  • Example custom processor (app/Swagger/CustomProcessor.php):
    namespace App\Swagger;
    
    use OpenApi\Generator\Processor;
    
    class CustomProcessor extends Processor
    {
        public function process($operation, $filename, $context)
        {
            $operation['security'] = [['api_key' => []]]; // Add security globally
            return $operation;
        }
    }
    

3. Authentication Integration

  • Passport/OAuth2: Configure security schemes in config/l5-swagger.php:
    'securitySchemes' => [
        'bearerAuth' => [
            'type' => 'http',
            'scheme' => 'bearer',
            'bearerFormat' => 'JWT',
        ],
    ],
    
  • Apply to routes:
    /**
     * @OA\Get(
     *     path="/api/protected",
     *     tags={"Protected"},
     *     security={{"bearerAuth": {}}},
     *     @OA\Response(response="200", description="Protected data")
     * )
     */
    

4. Multi-Environment Configs

  • Use environment variables to toggle features (e.g., dark mode, doc expansion):
    L5_SWAGGER_UI_DARK_MODE=true
    L5_SWAGGER_UI_DOC_EXPANSION=false
    
  • Override configs in .env or config/l5-swagger.php.

5. API Versioning

  • Group routes by version using @OA\Tag:
    /**
     * @OA\Tag(name="v1", description="API v1")
     */
    class V1UserController {}
    
  • Serve multiple OpenAPI specs via l5-swagger:generate with --spec flag:
    php artisan l5-swagger:generate --spec=v1
    php artisan l5-swagger:generate --spec=v2
    

6. Custom Swagger UI

  • Extend the default UI by publishing assets:
    php artisan vendor:publish --provider="OpenApi\Generator\Laravel\L5SwaggerServiceProvider" --tag=l5-swagger-assets
    
  • Override resources/views/vendor/l5-swagger/ui.blade.php to add custom JS/CSS.

Gotchas and Tips

Pitfalls

  1. Annotation Parsing Issues:

    • Ensure annotations are above the method/class they describe.
    • Avoid PHP 8.2+ attributes (use @OA\* annotations instead).
    • Fix: Run composer dump-autoload if annotations are ignored.
  2. Circular References in Schemas:

    • Complex nested schemas may cause infinite loops.
    • Fix: Use $ref to reference existing schemas:
      @OA\Property(property="address", ref="#/components/schemas/Address")
      
  3. Route Caching Conflicts:

    • Laravel’s route caching (php artisan route:cache) may break dynamic Swagger generation.
    • Fix: Exclude Swagger routes from caching or regenerate docs after caching.
  4. Swagger UI Not Updating:

    • Clear cached views (php artisan view:clear) or browser cache.
    • Fix: Use ?t= query param to bust cache: /api/documentation?t= + timestamp.
  5. Environment-Specific Configs:

    • Configs in .env override config/l5-swagger.php, but may not apply to all environments.
    • Fix: Use config('l5-swagger.*.key') in custom processors to handle environment-specific logic.

Debugging Tips

  1. Inspect Generated Spec:

    • Access raw OpenAPI JSON/YAML at /api/documentation/json or /api/documentation/yaml.
    • Validate with Swagger Editor.
  2. Enable Verbose Logging:

    // config/l5-swagger.php
    'debug' => true,
    
    • Logs will appear in storage/logs/l5-swagger.log.
  3. Check Processor Order:

    • Processors run in the order defined in config/l5-swagger.php. Reorder to prioritize custom logic.
  4. Validate Annotations:

    • Use php artisan l5-swagger:generate --debug to see parsing errors.

Extension Points

  1. Custom Generators:

    • Extend \OpenApi\Generator\Laravel\Generator to support non-annotated sources (e.g., database schemas).
  2. Webhook Triggers:

    • Hook into generated event to auto-deploy docs:
      // app/Providers/EventServiceProvider.php
      protected $listen = [
          \OpenApi\Generator\Events\Generated::class => [
              \App\Listeners\DeploySwaggerDocs::class,
          ],
      ];
      
  3. Dynamic Route Filtering:

    • Use FilterProcessor to exclude routes:
      'processors' => [
          \OpenApi\Generator\Processor\FilterProcessor::class => [
              'exclude' => ['/api/debug', '/api/webhooks'],
          ],
      ],
      
  4. Dark Mode Customization:

    • Override Swagger UI theme by extending the published assets:
      /* resources/css/swagger-ui-custom.css */
      .swagger-ui .opblock-summary {
          color: #fff !important; /* Override dark mode text */
      }
      

Performance Tips

  1. Cache Generated Specs:

    • Set generate_always: false in config to avoid regenerating on every request.
    • Manually regenerate with php artisan l5-swagger:generate.
  2. Exclude Unused Routes:

    • Use FilterProcessor to exclude admin/debug routes from docs.
  3. Optimize Schemas:

    • Reuse schemas with $ref to avoid duplication:
      @OA\Schema(ref="#/components/schemas/User")
      
  4. Lazy-Load Swagger UI:

    • Serve Swagger UI assets from a CDN or local cache:
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport