Weave 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

Swagger Bundle Laravel Package

dokapi/swagger-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require dokapi/swagger-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Dokapi\SwaggerBundle\DokapiSwaggerBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration Publish the default config:

    php artisan vendor:publish --provider="Dokapi\SwaggerBundle\DokapiSwaggerBundle" --tag="config"
    

    Update config/swagger.php with your API details (e.g., host, base_path).

  3. First Use Case: Documenting a Controller Annotate a controller method with Swagger tags:

    use Dokapi\SwaggerBundle\Annotation\Swagger;
    
    class UserController extends Controller
    {
        /**
         * @Swagger\Get(
         *     path="/users",
         *     summary="Get all users",
         *     tags={"Users"}
         * )
         */
        public function index()
        {
            return User::all();
        }
    }
    
  4. Generate Documentation Run the generator:

    php artisan swagger:generate
    

    Output will be saved to public/swagger.json (configurable).


Implementation Patterns

Workflows

  1. Incremental Documentation

    • Document controllers/methods as you build using annotations.
    • Regenerate docs only for changed routes:
      php artisan swagger:generate --only-changed
      
  2. Reusing Annotations

    • Base Classes: Extend a base controller with common Swagger tags:
      abstract class ApiController extends Controller
      {
          /**
           * @Swagger\Tag(name="API", description="Base API endpoints")
           */
      }
      
    • Traits: Share reusable annotations across controllers.
  3. Integration with API Platform If using API Platform, merge annotations:

    use ApiPlatform\Metadata\ApiResource;
    use Dokapi\SwaggerBundle\Annotation\Swagger;
    
    #[ApiResource]
    class User
    {
        /**
         * @Swagger\Get(
         *     path="/users/{id}",
         *     summary="Get a user by ID"
         * )
         */
    }
    
  4. Dynamic Paths/Parameters Use placeholders for dynamic routes:

    /**
     * @Swagger\Get(
     *     path="/users/{id}",
     *     summary="Get user by ID",
     *     @Swagger\Parameter(
     *         name="id",
     *         in="path",
     *         type="integer",
     *         required=true
     *     )
     * )
     */
    
  5. Security Schemes Define OAuth2/JWT auth in config/swagger.php:

    'securityDefinitions' => [
        'Bearer' => [
            'type' => 'apiKey',
            'name' => 'Authorization',
            'in' => 'header',
        ],
    ],
    

    Apply to endpoints:

    /**
     * @Swagger\Get(
     *     path="/admin/users",
     *     security={{"Bearer": {}}}
     * )
     */
    

Gotchas and Tips

Pitfalls

  1. Annotation Parsing Issues

    • Symfony < 5.3: Use dokapi/swagger-bundle:^1.0 (older syntax).
    • PHP 8.0+: Ensure returnTypeWillChange is enabled in php.ini for proper docblock parsing.
    • Caching: Clear cache after adding new annotations:
      php artisan cache:clear
      
  2. Route Conflicts

    • Swagger generates docs for all annotated routes, even if they’re disabled in routes/api.php.
    • Exclude routes with:
      /**
       * @Swagger\Ignore()
       */
      
  3. Complex Types

    • Nested Objects: Define schemas in config/swagger.php under definitions:
      'definitions' => [
          'User' => [
              'type' => 'object',
              'properties' => [
                  'name' => ['type' => 'string'],
                  'roles' => ['type' => 'array', 'items' => ['type' => 'string']],
              ],
          ],
      ],
      
    • Arrays of Objects: Use $ref to avoid duplication:
      'properties' => [
          'users' => ['type' => 'array', 'items' => ['$ref' => '#/definitions/User']],
      ],
      
  4. Performance

    • Large APIs: Exclude unused controllers from generation:
      php artisan swagger:generate --exclude="App\Http\Controllers\Tests*"
      
    • CI/CD: Cache generated docs to avoid regenerating on every push.

Tips

  1. Validation Rules ↔ Swagger Sync Laravel validation rules to Swagger schemas:

    /**
     * @Swagger\Post(
     *     path="/users",
     *     @Swagger\Parameter(
     *         name="body",
     *         in="body",
     *         required=true,
     *         schema={
     *             "type": "object",
     *             "properties": {
     *                 "name": {"type": "string", "minLength": 3},
     *                 "email": {"type": "string", "format": "email"}
     *             }
     *         }
     *     )
     * )
     */
    
  2. Custom Templates Override the default OpenAPI template in resources/views/vendor/swagger/. Example: Add a custom info section:

    {# resources/views/vendor/swagger/info.twig #}
    {
        "info": {
            "title": "{{ config('swagger.title') }}",
            "version": "{{ config('swagger.version') }}",
            "description": "{{ config('swagger.description') }}",
            "contact": {
                "email": "{{ config('swagger.contact_email') }}"
            }
        }
    }
    
  3. Testing Docs Validate generated docs against a schema:

    composer require --dev zircote/swagger-php
    php artisan swagger:validate
    
  4. Environment-Specific Docs Use different configs for dev/prod:

    php artisan swagger:generate --env=production
    

    Configure in config/swagger.php:

    'env_config' => [
        'production' => 'config/swagger_prod.php',
    ],
    
  5. IDE Integration

    • PHPStorm: Enable "OpenAPI/Swagger" support in Settings > Languages & Frameworks > REST Client.
    • VSCode: Use the Swagger Viewer extension to preview public/swagger.json.
  6. Deprecation Warnings

    • Monitor @Swagger\Deprecated() annotations for future API changes:
      /**
       * @Swagger\Get(
       *     path="/legacy/users",
       *     @Swagger\Deprecated(
       *         description="Use /users instead"
       *     )
       * )
       */
      
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.
steadrun/laravel-monitor
labyrinthe/connect-laravel
elmogy/layan
drewdan/sentinel-client
dskripchenko/laravel-llm
fatryst/nuonuo
stevenay/myanfont
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc
animalyoung/laravel-influxdb
onix-solutions/sms-telera
lonely-lights/prosetta
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin