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 wrapper for swagger-php and Swagger UI. Generate and serve OpenAPI/Swagger docs from annotations, with configurable routes, assets, and security (e.g., Passport). Includes config publishing, scanning paths, and an interactive docs UI.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require darkaonline/l5-swagger
    

    Publish the configuration file:

    php artisan vendor:publish --provider="DarkaOnLine\L5Swagger\L5SwaggerServiceProvider" --tag=l5-swagger-config
    
  2. Basic Configuration: Edit config/l5-swagger.php to define your API paths and security schemes. Example:

    'paths' => [
        'api' => 'routes/api.php',
    ],
    'securitySchemes' => [
        'bearerAuth' => [
            'type' => 'http',
            'scheme' => 'bearer',
            'bearerFormat' => 'JWT',
        ],
    ],
    
  3. First Use Case: Add Swagger annotations to a controller method:

    use DarkaOnLine\L5Swagger\Annotations as Swg;
    
    /**
     * @Swg\Get(
     *     path="/users",
     *     summary="Get a list of users",
     *     @Swg\Response(response=200, description="List of users")
     * )
     */
    public function index()
    {
        return User::all();
    }
    
  4. Access Swagger UI: Visit /api/documentation (or your configured path) to see the interactive API documentation.


Implementation Patterns

Core Workflows

1. Annotation-Based Documentation

  • Controllers: Use PHP attributes (or annotations) to document endpoints:
    /**
     * @Swg\Post(
     *     path="/users",
     *     summary="Create a new user",
     *     @Swg\Parameter(
     *         in="body",
     *         name="user",
     *         required=true,
     *         @Swg\Schema(ref="#/definitions/User")
     *     ),
     *     @Swg\Response(response=201, description="User created")
     * )
     */
    public function store(Request $request)
    {
        // ...
    }
    
  • Models: Document models in app/Models/ using @Swg\Schema:
    /**
     * @Swg\Schema(
     *     schema="User",
     *     @Swg\Property(property="name", type="string"),
     *     @Swg\Property(property="email", type="string", format="email")
     * )
     */
    class User extends Model {}
    

2. Dynamic API Documentation

  • Route Scanning: Configure scan in l5-swagger.php to auto-discover routes:
    'scan' => [
        'app/Http/Controllers',
        'app/Http/Api/Controllers',
    ],
    
  • Generator Factory: Customize the OpenAPI generator (v11.1.0+):
    'generator_factory' => function () {
        return \OpenApi\Generator::create()
            ->withNamingConvention('underscore')
            ->withDefaultResponse();
    },
    

3. Security Schemes

  • Passport/OAuth2: Configure in l5-swagger.php:
    'securitySchemes' => [
        'oauth2' => [
            'type' => 'oauth2',
            'flows' => [
                'password' => [
                    'tokenUrl' => 'oauth/token',
                    'scopes' => [
                        'read' => 'Read access',
                        'write' => 'Write access',
                    ],
                ],
            ],
        ],
    ],
    
  • Sanctum: Use the built-in Sanctum example or extend:
    'securitySchemes' => [
        'sanctum' => [
            'type' => 'http',
            'scheme' => 'bearer',
            'bearerFormat' => 'token',
        ],
    ],
    

4. Swagger UI Customization

  • Environment Variables: Override UI settings via .env:
    L5_SWAGGER_UI_DOC_EXPANSION=none
    L5_SWAGGER_UI_FILTERS=true
    L5_SWAGGER_UI_DARK_MODE=true
    
  • Custom Templates: Extend the default Swagger UI template in resources/views/vendor/l5-swagger/ui.blade.php.

5. Multi-API Support

  • Define multiple APIs in l5-swagger.php:
    'apis' => [
        'v1' => [
            'paths' => ['routes/api.php'],
            'title' => 'API v1',
            'version' => '1.0.0',
        ],
        'v2' => [
            'paths' => ['routes/api-v2.php'],
            'title' => 'API v2',
            'version' => '2.0.0',
        ],
    ],
    
  • Access via /api/v1/documentation and /api/v2/documentation.

Integration Tips

Laravel Features

  • Middleware: Apply Swagger-specific middleware to exclude routes:
    Route::middleware(['api', 'swagger.exclude'])->group(function () {
        // Routes not documented in Swagger
    });
    
  • Service Providers: Boot Swagger in AppServiceProvider:
    public function boot()
    {
        if ($this->app->environment('local')) {
            $this->loadL5Swagger();
        }
    }
    

Testing

  • Unit Tests: Mock the OpenAPI generator:
    $generator = Mockery::mock(\OpenApi\Generator::class);
    $this->app->instance(\OpenApi\Generator::class, $generator);
    
  • Feature Tests: Assert Swagger UI responses:
    $response = $this->get('/api/documentation');
    $response->assertSee('Swagger UI');
    

Performance

  • Caching: Enable caching in l5-swagger.php:
    'cache' => [
        'enabled' => true,
        'time' => 60, // Cache for 60 minutes
    ],
    
  • Exclude Routes: Skip documentation for non-API routes:
    'scan' => [
        'app/Http/Controllers/Api',
        // Exclude non-API controllers
    ],
    

Gotchas and Tips

Pitfalls

  1. Annotation Parsing Issues:

    • Problem: Annotations are ignored or cause errors.
    • Fix: Ensure doctrine/annotations is installed (v10+ includes it by default). For PHP 8.2+, use attributes:
      #[Swg\Get(path: "/users", summary: "Get users")]
      public function index() {}
      
    • Debug: Check storage/logs/l5-swagger.log for parsing errors.
  2. Route Conflicts:

    • Problem: Swagger UI routes conflict with existing routes (e.g., /api/documentation).
    • Fix: Customize the route in l5-swagger.php:
      'routes' => [
          'api' => [
              'prefix' => 'docs',
              'middleware' => ['web'],
          ],
      ],
      
      Now accessible at /docs/documentation.
  3. Security Scheme Mismatches:

    • Problem: Authenticated endpoints fail in Swagger UI.
    • Fix: Ensure securitySchemes matches your auth setup (e.g., Passport/Sanctum). Example for Sanctum:
      'security' => [
          [
              'sanctum' => [],
          ],
      ],
      
  4. Model Documentation Not Reflecting:

    • Problem: @Swg\Schema annotations on models are ignored.
    • Fix: Explicitly include model paths in scan:
      'scan' => [
          'app/Models',
          'app/Http/Controllers',
      ],
      
  5. Swagger UI Assets Not Loading:

    • Problem: CSS/JS fails to load in Swagger UI.
    • Fix: Verify L5_SWAGGER_UI_ASSETS_PATH in .env or clear cached views:
      php artisan view:clear
      

Debugging Tips

  1. Log Generation: Enable debug logs in l5-swagger.php:

    'debug' => true,
    

    Logs are stored in storage/logs/l5-swagger.log.

  2. Validate OpenAPI Spec: Use the Swagger Validator to validate the generated spec at /api/documentation/json.

  3. Check Generated Spec: Access the raw OpenAPI spec at /api/documentation/json to inspect the output.

  4. Processor Debugging: For custom processors, enable verbose output:

    'processors' => [
        'MyProcessor' => [
            'class' => \App\Swagger\MyProcessor::class,
            'config' => [
                'verbose' => true,
            ],
        ],
    ],
    

Extension Points

  1. Custom Processors: Extend
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony