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 Laravel Package

draw/swagger

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require draw/swagger
    
  2. First Use Case: Load and Parse a Swagger File

    use Draw\Swagger\Swagger;
    
    $swagger = new Swagger('path/to/swagger.json');
    $openApi = $swagger->getOpenApi(); // Returns parsed Swagger/OpenAPI spec
    
  3. Where to Look First

    • src/Draw/Swagger/Swagger.php: Core class for loading and manipulating specs.
    • tests/: Example usage patterns for modifying paths, schemas, and responses.
    • README.md: Basic API reference and usage examples.

Implementation Patterns

Core Usage Patterns

1. Loading and Modifying Specs

$swagger = new Swagger('api-spec.json');
$openApi = $swagger->getOpenApi();

// Modify a path
$openApi->getPaths()->addPath('/users/{id}', [
    'get' => [
        'summary' => 'Get user by ID',
        'responses' => [
            '200' => [
                'description' => 'User details',
                'schema' => ['$ref' => '#/definitions/User']
            ]
        ]
    ]
]);

$swagger->save('updated-spec.json');

2. Dynamic Spec Generation from Laravel Routes

Use annotations or metadata to generate Swagger specs dynamically:

// Example: Extract route metadata to build Swagger paths
Route::get('/users/{id}', function () {
    // ...
})->middleware(function ($request, $next) {
    $swagger = new Swagger();
    $swagger->addPath('/users/{id}', [
        'get' => [
            'tags' => ['Users'],
            'summary' => 'Fetch user by ID',
            'parameters' => [
                ['name' => 'id', 'in' => 'path', 'required' => true, 'type' => 'integer']
            ]
        ]
    ]);
    return $next($request);
});

3. Schema and Response Manipulation

$definitions = $openApi->getDefinitions();
$userSchema = $definitions->getSchema('User');

// Add a new property to the User schema
$userSchema->addProperty('lastLogin', [
    'type' => 'string',
    'format' => 'date-time'
]);

// Update a response
$responses = $openApi->getPath('/users')->getGet()->getResponses();
$responses->set('404', [
    'description' => 'User not found',
    'schema' => ['$ref' => '#/definitions/Error']
]);

4. Merging Multiple Specs

Combine specs from microservices or modules:

$mainSpec = new Swagger('main-spec.json');
$moduleSpec = new Swagger('module-spec.json');

$mergedSpec = $mainSpec->getOpenApi();
$mergedSpec->merge($moduleSpec->getOpenApi());

$swagger = new Swagger();
$swagger->setOpenApi($mergedSpec);
$swagger->save('merged-spec.json');

5. Validation in CI/CD

Validate Swagger specs against expected structures in your pipeline:

$swagger = new Swagger('api-spec.json');
$openApi = $swagger->getOpenApi();

// Example: Check if a required path exists
$this->assertTrue($openApi->getPaths()->hasPath('/users'), 'Users endpoint missing');

// Example: Validate response schemas
$this->assertArrayHasKey('200', $openApi->getPath('/users')->getGet()->getResponses()->getKeys());

Laravel-Specific Patterns

1. Service Provider Integration

Register the Swagger class in Laravel’s container for easy access:

// app/Providers/AppServiceProvider.php
public function register()
{
    $this->app->singleton(Swagger::class, function () {
        return new \Draw\Swagger\Swagger(config('swagger.path'));
    });
}

2. Middleware for Spec Generation

Use middleware to dynamically generate or update Swagger specs:

// app/Http/Middleware/GenerateSwaggerSpec.php
public function handle($request, Closure $next)
{
    $swagger = app(Swagger::class);
    $swagger->addPath($request->route()->uri(), [
        'get' => [
            'tags' => [$request->route()->getName()],
            'summary' => 'Dynamic endpoint'
        ]
    ]);
    return $next($request);
}

3. Artisan Command for Spec Management

Create a command to generate or validate specs:

// app/Console/Commands/GenerateSwaggerSpec.php
public function handle()
{
    $swagger = new Swagger();
    $routes = Route::getRoutes()->getRoutes();

    foreach ($routes as $route) {
        $swagger->addPath($route->uri(), [
            'get' => [
                'tags' => [$route->getName()],
                'summary' => 'Endpoint: ' . $route->uri()
            ]
        ]);
    }

    $swagger->save(storage_path('app/swagger.json'));
    $this->info('Swagger spec generated!');
}

Gotchas and Tips

Pitfalls

1. Swagger 2.0 vs. OpenAPI 3.x

  • This package only supports Swagger 2.0, which is deprecated. OpenAPI 3.x is the modern standard.
  • Workaround: Use a converter (e.g., openapi-converter) to migrate specs to OpenAPI 3.x after manipulation.

2. Limited Documentation

  • The package has minimal documentation and no active maintenance. Expect to rely on tests and trial/error.
  • Tip: Study the tests/ directory for usage patterns.

3. No Native OpenAPI Validation

  • The library does not validate specs against OpenAPI standards. Use third-party tools like openapi-tools/validator in CI.
  • Example CI Check:
    composer require openapi-tools/validator
    vendor/bin/openapi-validator validate api-spec.json
    

4. PHP Version Compatibility

  • Last release in 2020 targets PHP 7.1–7.4. Laravel 9+ (PHP 8.0+) may require polyfills or forks.
  • Tip: Test with PHPUnit and PHPStan to catch compatibility issues early.

5. No Built-in Caching

  • Parsing and manipulating specs can be slow for large APIs. Cache the parsed OpenApi object if reused frequently.
  • Example:
    $cacheKey = 'swagger_spec';
    $openApi = Cache::remember($cacheKey, now()->addHours(1), function () {
        return (new Swagger('api-spec.json'))->getOpenApi();
    });
    

6. Annotation Overhead

  • The package relies on annotations (e.g., @SWG\Tag). Laravel’s native attributes (e.g., #[Route]) won’t work without manual mapping.
  • Tip: Use a hybrid approach (annotations for Swagger + Laravel attributes for routing).

7. No Support for OpenAPI Components

  • Features like shared schemas, responses, or security schemes require manual handling.
  • Workaround: Use getComponents() to manage shared definitions.

Debugging Tips

1. Inspect Parsed Specs

Dump the parsed OpenApi object to debug issues:

$openApi = (new Swagger('api-spec.json'))->getOpenApi();
dd($openApi->toArray()); // Convert to array for inspection

2. Validate JSON Output

Ensure the saved spec is valid JSON:

$swagger = new Swagger();
$swagger->setOpenApi($openApi);
$json = $swagger->saveToString(); // Get JSON as string
json_decode($json); // Check for JSON errors

3. Check for Deprecated Methods

Some methods may be deprecated or renamed in newer versions (though this package is unmaintained). Refer to the tests/ directory for correct usage.

4. Handle Missing Paths/Schemas

If a path or schema is missing, initialize it explicitly:

if (!$openApi->getPaths()->hasPath('/users')) {
    $openApi->getPaths()->addPath('/users', ['get' => []]);
}

Extension Points

1. Custom Annotations

Extend the library to support custom annotations (e.g

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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle