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

Laravel Swaggerdoc Laravel Package

cirlmcesc/laravel-swaggerdoc

Generate OpenAPI 3.0 (Swagger) docs from your Laravel tests/commands. Write tests and produce an interface document automatically, inspired by swagger-php, to keep API documentation in sync with your code.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require cirlmcesc/laravel-swaggerdoc
    

    Publish the config file:

    php artisan vendor:publish --provider="Cirlmcesc\LaravelSwaggerdoc\SwaggerdocServiceProvider" --tag="config"
    
  2. Configuration Edit config/swaggerdoc.php to define:

    • api_title (e.g., "My API")
    • api_version (e.g., "1.0.0")
    • base_path (e.g., "/api")
    • security_definitions (if using auth like JWT/OAuth2)
    • output_path (default: storage/app/swagger.json)
  3. First Use Case Run the test command to generate the OpenAPI spec:

    php artisan swaggerdoc:generate
    

    Verify the output at storage/app/swagger.json or your configured path.


Implementation Patterns

Workflows

  1. Test-Driven API Documentation

    • Write API tests (e.g., phpunit) with annotations like @swagger to define endpoints, parameters, and responses.
    • Example:
      /** @swagger
       * @OA\Get(
       *     path="/users",
       *     tags={"Users"},
       *     summary="Get all users",
       *     @OA\Response(response="200", description="List of users")
       * )
       */
      public function index() { ... }
      
    • Run php artisan swaggerdoc:generate to auto-generate swagger.json.
  2. Integration with Laravel Routes

    • Use the SwaggerdocRouteServiceProvider to auto-discover and document routes:
      // In AppServiceProvider@boot()
      if ($this->app->environment('local')) {
          $this->app->make(\Cirlmcesc\LaravelSwaggerdoc\SwaggerdocRouteServiceProvider::class);
      }
      
    • Routes are scanned and documented in the OpenAPI spec.
  3. Customizing the Spec

    • Override the default spec template by publishing the views:
      php artisan vendor:publish --provider="Cirlmcesc\LaravelSwaggerdoc\SwaggerdocServiceProvider" --tag="views"
      
    • Modify resources/views/vendor/swaggerdoc/spec.blade.php to add/remove fields.
  4. Scheduled Generation

    • Add a cron job or Laravel scheduler task to regenerate the spec after deployments:
      // app/Console/Kernel.php
      protected function schedule(Schedule $schedule) {
          $schedule->command('swaggerdoc:generate')->daily();
      }
      

Integration Tips

  • Laravel Sanctum/Passport: Define security schemes in config/swaggerdoc.php:
    'security_definitions' => [
        'bearerAuth' => [
            'type' => 'http',
            'scheme' => 'bearer',
            'bearerFormat' => 'JWT',
        ],
    ],
    
  • Validation Rules: Document request/response schemas using OpenAPI annotations in controllers or DTOs.
  • Swagger UI: Serve the generated swagger.json via a route and use Swagger UI for visualization:
    Route::get('/docs', function () {
        return response()->file(storage_path('app/swagger.json'));
    });
    

Gotchas and Tips

Pitfalls

  1. Annotation Parsing

    • The package relies on docblock annotations (e.g., @OA\Get). Ensure:
      • PHPDoc blocks are correctly formatted (no typos in @OA tags).
      • Annotations are placed above the method/class they document.
    • Debug Tip: Use php artisan swaggerdoc:generate --verbose to see parsing errors.
  2. Route Caching

    • Laravel’s route caching (php artisan route:cache) may interfere with dynamic route discovery. Regenerate the spec after caching:
      php artisan route:cache && php artisan swaggerdoc:generate
      
  3. Namespace Conflicts

    • If using custom OpenAPI annotations (e.g., from darkaonline/l5-swagger), ensure the package’s namespace (Cirlmcesc\LaravelSwaggerdoc) doesn’t clash. Override the provider binding if needed:
      $this->app->bind(\Cirlmcesc\LaravelSwaggerdoc\SwaggerdocGenerator::class, function () {
          return new \Custom\SwaggerdocGenerator();
      });
      
  4. Deprecated OpenAPI 2.0

    • The package generates OpenAPI 3.0, but some tools/annotations may default to 2.0. Explicitly use 3.0.0 in your spec:
      'api_version' => '3.0.0',
      

Debugging

  • Empty Spec Output:

    • Check if routes/controllers are being scanned. Add --verbose to the generate command.
    • Ensure base_path in config matches your API routes (e.g., /api vs. /v1).
  • Missing Endpoints:

    • Verify annotations are on public methods (not private/protected).
    • For API resources, document index(), store(), etc., explicitly.
  • Schema Validation Errors:

Extension Points

  1. Custom Generators

    • Extend Cirlmcesc\LaravelSwaggerdoc\Generators\SwaggerdocGenerator to add logic (e.g., auto-documenting Eloquent models):
      namespace App\Generators;
      use Cirlmcesc\LaravelSwaggerdoc\Generators\SwaggerdocGenerator as BaseGenerator;
      
      class CustomSwaggerdocGenerator extends BaseGenerator {
          public function generate() {
              parent::generate();
              $this->documentModels();
          }
      }
      
  2. Dynamic Annotations

    • Use Laravel’s getAnnotations() helper or libraries like rubix/ml-extra to parse annotations dynamically:
      $reflection = new \ReflectionMethod(UserController::class, 'index');
      $annotations = \Rubix\ML\Extra\Annotation::get($reflection);
      
  3. Post-Processing

    • Hook into the swaggerdoc.generated event to modify the spec:
      // In AppServiceProvider@boot()
      event(new \Cirlmcesc\LaravelSwaggerdoc\Events\SwaggerdocGenerated($spec));
      
    • Listen to the event in an event handler:
      public function handle(SwaggerdocGenerated $event) {
          $event->spec['info']['x-custom'] = 'value';
      }
      
  4. Multi-Environment Configs

    • Use Laravel’s environment configs to switch specs (e.g., swaggerdoc.dev.php vs. swaggerdoc.prod.php):
      'output_path' => env('SWAGGER_OUTPUT', storage_path('app/swagger.json')),
      
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony