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

Swagger Php Laravel Package

zircote/swagger-php

Generate OpenAPI 3.0/3.1/3.2 docs from your PHP 8.2+ code using native attributes (preferred) or optional Doctrine annotations. Includes CLI and programmatic generation, parses phpdoc, provides helpful error reporting, and powers interactive API docs.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require zircote/swagger-php

For CLI usage globally:

composer global require zircote/swagger-php
  1. Basic Attribute Usage: Add OpenAPI attributes to your controllers or DTOs. Example:

    use OpenApi\Attributes as OAT;
    
    #[OAT\Info(title: 'My API', version: '1.0')]
    class MyController {
        #[OAT\Get(path: '/users', summary: 'Get all users')]
        public function index(): array { ... }
    }
    
  2. Generate Documentation:

    • Programmatically:
      $openapi = (new \OpenApi\Generator())->generate([__DIR__ . '/src']);
      file_put_contents('api-docs.yaml', $openapi->toYaml());
      
    • CLI:
      ./vendor/bin/openapi --output api-docs.yaml src/
      

First Use Case: API Documentation

Annotate your Laravel controllers with OpenAPI attributes to auto-generate interactive API docs. Use tools like Swagger UI to visualize the docs.


Implementation Patterns

1. Controller Annotations

Annotate Laravel controllers for route-level documentation:

use OpenApi\Attributes as OAT;

#[OAT\Tag(name: 'Users')]
class UserController extends Controller {
    #[OAT\Post(
        path: '/users',
        summary: 'Create a user',
        requestBody: new OAT\RequestBody(
            content: new \OpenApi\Attributes\JsonContent(ref: '#/components/schemas/UserCreate')
        )
    )]
    public function store(Request $request) { ... }
}

2. DTO/Request Validation

Use attributes on DTOs for schema validation:

use OpenApi\Attributes as OAT;

#[OAT\Schema(description: 'User creation data')]
class UserCreate {
    #[OAT\Property(type: 'string', example: 'john@example.com')]
    public string $email;

    #[OAT\Property(type: 'string', format: 'password')]
    public string $password;
}

3. Integration with Laravel

  • Route Caching: Combine with Laravel’s route caching for static API docs:
    php artisan route:cache
    ./vendor/bin/openapi --output public/api-docs.yaml app/Http/Controllers/
    
  • Middleware: Use openapi middleware to serve docs dynamically:
    Route::get('/api-docs', function () {
        return response((new \OpenApi\Generator())->generate([__DIR__ . '/app/Http/Controllers']));
    });
    

4. Custom Components

Define reusable schemas in a central file (e.g., app/OpenApi/Components.php):

use OpenApi\Attributes as OAT;

#[OAT\Schema(schema: 'User')]
class User {
    #[OAT\Property(type: 'string')] public string $id;
    #[OAT\Property(type: 'string')] public string $name;
}

5. OpenAPI Versioning

Specify OpenAPI version globally or per-generator:

$generator = new \OpenApi\Generator();
$generator->setVersion('3.1'); // Default is 3.0

6. CLI Workflows

  • Watch Mode: Use nodemon to regenerate docs on file changes:
    nodemon --watch app --exec "vendor/bin/openapi --output public/api-docs.yaml app/Http/Controllers"
    
  • CI/CD: Generate docs in pipelines and deploy to a static host:
    # .github/workflows/docs.yml
    jobs:
      generate-docs:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - run: composer install
          - run: ./vendor/bin/openapi --output api-docs.yaml app/
          - uses: actions/upload-artifact@v3
            with:
              name: api-docs
              path: api-docs.yaml
    

Gotchas and Tips

Pitfalls

  1. Type Resolution:

    • Legacy Resolver: If migrating from v5, ensure TypeInfoTypeResolver is used (default in v6). Avoid LegacyTypeResolver (deprecated).
    • Complex Types: Use PHPDoc for generics (e.g., @var list<User>) or attribute-based definitions:
      #[OAT\Property(items: new OAT\Items(type: User::class))]
      public array $users;
      
  2. Annotation Conflicts:

    • Duplicate Annotations: Ensure no conflicting @OAT\* attributes on the same method/class. Use #[OAT\Info] once per class.
    • PHPDoc vs. Attributes: Attributes take precedence over PHPDoc. Use one or the other for clarity.
  3. CLI Quirks:

    • Path Handling: Use absolute paths in CLI commands to avoid issues with relative paths:
      ./vendor/bin/openapi --output ./public/api-docs.yaml $(pwd)/app/Http/Controllers
      
    • Version Override: The --version flag may not persist in some setups. Use Generator::setVersion() programmatically if needed.
  4. Performance:

    • Large Codebases: Exclude non-relevant directories (e.g., tests) to speed up generation:
      $generator->generate([__DIR__ . '/app/Http', __DIR__ . '/app/Models']);
      
    • Caching: Cache generated docs in Laravel’s storage/ directory and serve statically.
  5. OpenAPI 3.2:

    • New Features: Leverage 3.2 features like unevaluatedProperties or query operations, but validate compatibility with your tools (e.g., Swagger UI may lag in support).

Debugging Tips

  1. Validation Errors:

    • Enable strict validation in the generator:
      $generator->setStrictValidation(true);
      
    • Check for missing required fields (e.g., summary in #[OAT\Get]).
  2. Schema Mismatches:

    • Use #[OAT\Example] to provide concrete examples for complex schemas:
      #[OAT\Property(type: 'object', example: ['id' => 1, 'name' => 'Test'])]
      public array $data;
      
  3. CLI Debugging:

    • Run with --verbose for detailed output:
      ./vendor/bin/openapi --verbose --output api-docs.yaml app/
      

Extension Points

  1. Custom Resolvers: Override type resolution for custom logic:

    use OpenApi\Generator;
    use OpenApi\TypeInfoTypeResolver;
    
    $generator = new Generator();
    $generator->setTypeResolver(new class extends TypeInfoTypeResolver {
        protected function resolveCustomType(string $type): string {
            return match ($type) {
                'App\\Models\\User' => 'UserSchema',
                default => parent::resolveType($type),
            };
        }
    });
    
  2. Post-Processing: Modify the generated spec using OpenApi\OpenApi:

    $openapi = $generator->generate([__DIR__ . '/app']);
    $openapi->info->title = 'My Awesome API';
    $openapi->servers = [new \OpenApi\Server(url: 'https://api.example.com/v1')];
    
  3. Laravel Service Provider: Bind the generator to the container for reusable access:

    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->singleton(\OpenApi\Generator::class, function () {
            return (new \OpenApi\Generator())
                ->setTypeResolver(new \OpenApi\TypeInfoTypeResolver())
                ->setVersion('3.1');
        });
    }
    

Laravel-Specific Tips

  1. Route Model Binding: Document model binding in routes:

    #[OAT\Get(
        path: '/users/{id}',
        summary: 'Get a user',
        parameters: [new OAT\Parameter(
            name: 'id',
            in: 'path',
            required: true,
            schema: new OAT\Schema(type: 'integer')
        )]
    )]
    public function show(User $user) { ... }
    
  2. Form Requests: Annotate FormRequest classes for validation docs:

    use Illuminate\Foundation\Http\FormRequest;
    use OpenApi\Attributes as OAT;
    
    class StoreUserRequest extends FormRequest {
        #[OAT\Property(type: 'string', example: 'john@example.com')]
        public string $email;
    }
    
  3. API Resources: Document API resources (e.g., Illuminate\Http\Resources\Json\JsonResource):

    #[OAT\Schema(schema: 'UserResource')]
    class UserResource extends JsonResource {
    
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