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

Yaml Swagger Laravel Laravel Package

endanguyen/yaml-swagger-laravel

Laravel package that integrates Swagger/OpenAPI docs defined in YAML. Load and serve YAML-based API specifications in a Laravel app to generate interactive documentation and keep definitions versionable alongside your code.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation

    composer require endanguyen/yaml-swagger-laravel
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Endanguyen\YamlSwaggerLaravel\YamlSwaggerServiceProvider" --tag="config"
    
  2. Basic Setup

    • Ensure your Laravel project has OpenAPI/Swagger annotations in your controllers or routes.
    • Configure the package in config/yaml-swagger.php (if published):
      'output_path' => storage_path('app/swagger'),
      'filename' => 'api.yaml',
      'generate_on_demand' => false, // Set to true for manual generation
      
  3. First Use Case

    • Run the generator:
      php artisan swagger:generate
      
    • The generated YAML file will be at storage/app/swagger/api.yaml.
    • Validate the output using a tool like Swagger Editor.

Implementation Patterns

Workflow Integration

  1. Automated Generation

    • Use generate_on_demand: false in config to auto-generate YAML on every php artisan command (e.g., optimize, migrate).
    • Add a post-update hook in composer.json:
      "scripts": {
        "post-autoload-dump": "php artisan swagger:generate"
      }
      
  2. Manual Generation

    • Trigger generation via a custom Artisan command or CI/CD pipeline:
      php artisan swagger:generate --force
      
  3. Versioning

    • Use environment-specific configs (e.g., .env variables) to generate versioned YAML files:
      'filename' => env('SWAGGER_VERSION', 'api') . '.yaml',
      
  4. Route-Based Annotations

    • Decorate routes in routes/api.php with Swagger tags:
      Route::get('/users', [UserController::class, 'index'])
          ->middleware('auth:api')
          ->swagger([
              'tags' => ['Users'],
              'summary' => 'Get all users',
              'description' => 'Returns paginated user list',
          ]);
      
  5. Controller Annotations

    • Use PHPDoc-style annotations in controllers:
      /**
       * @OA\Get(
       *     path="/users/{id}",
       *     tags={"Users"},
       *     summary="Get a user by ID",
       *     @OA\Parameter(ref="#/components/parameters/UserId"),
       *     @OA\Response(response=200, ref="#/components/schemas/User")
       * )
       */
      public function show(User $user) { ... }
      
  6. Schema Reusability

    • Define shared schemas in a dedicated file (e.g., app/Http/Resources/SwaggerSchemas.php) and reference them:
      /**
       * @OA\Schema(
       *     schema="User",
       *     type="object",
       *     required={"id", "name"},
       *     @OA\Property(property="id", type="integer"),
       *     @OA\Property(property="name", type="string")
       * )
       */
      
  7. CI/CD Pipeline

    • Integrate into GitHub Actions/GitLab CI:
      - name: Generate Swagger YAML
        run: php artisan swagger:generate
      - name: Upload artifact
        uses: actions/upload-artifact@v2
        with:
          name: swagger-yaml
          path: storage/app/swagger/api.yaml
      

Gotchas and Tips

Pitfalls

  1. Annotation Parsing Issues

    • Problem: The package may miss annotations if they’re not in the expected format (e.g., incorrect PHPDoc syntax or missing @OA\ prefix).
    • Fix: Validate annotations using zircote/swagger-php or manually inspect the generated YAML.
  2. Caching Conflicts

    • Problem: If generate_on_demand: true, stale YAML files may persist after code changes.
    • Fix: Clear the output directory or use --force flag:
      php artisan swagger:generate --force
      
  3. Namespace Conflicts

    • Problem: Annotations in namespaced controllers (e.g., App\Http\Controllers\Api\V1\UserController) may not resolve correctly.
    • Fix: Ensure the swagger facade is properly bound or use fully qualified paths in annotations:
      use OpenApi\Annotations as OA;
      
  4. Missing Dependencies

    • Problem: The package relies on zircote/swagger-php for parsing. If not installed, generation fails silently.
    • Fix: Explicitly require it in composer.json:
      composer require zircote/swagger-php
      
  5. Large Projects

    • Problem: Generation may time out or fail for projects with thousands of routes.
    • Fix: Exclude specific routes/controllers via config:
      'exclude' => [
          'App\Http\Controllers\Admin*',
          'routes/admin.php',
      ],
      

Debugging Tips

  1. Enable Verbose Output

    • Run with -v flag to debug parsing:
      php artisan swagger:generate -v
      
  2. Inspect Intermediate Files

    • Check storage/logs/laravel.log for parsing errors or missing annotations.
  3. Validate YAML

    • Use yamllint to validate syntax:
      yamllint storage/app/swagger/api.yaml
      
  4. Test Incrementally

    • Start with a single controller/route to isolate issues:
      php artisan swagger:generate --controller=UserController
      

Extension Points

  1. Custom Generators

    • Extend the generator by publishing and modifying the service provider:
      // app/Providers/YamlSwaggerServiceProvider.php
      public function register()
      {
          $this->app->bind(YamlSwaggerGenerator::class, function ($app) {
              return new CustomYamlSwaggerGenerator($app['config']);
          });
      }
      
  2. Post-Processing

    • Hook into the swagger.generated event to modify the YAML (e.g., add server URLs):
      // app/Providers/EventServiceProvider.php
      protected $listen = [
          'swagger.generated' => [
              \App\Listeners\AddServerUrl::class,
          ],
      ];
      
  3. Dynamic Filenames

    • Override the filename dynamically based on environment or branch:
      // config/yaml-swagger.php
      'filename' => function () {
          return 'api-' . strtolower(app()->environment()) . '.yaml';
      },
      
  4. Integration with API Docs

    • Serve the YAML file via a route:
      Route::get('/swagger.yaml', function () {
          return response()->file(storage_path('app/swagger/api.yaml'));
      });
      
    • Use with tools like Redoc or Swagger UI.
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai