Laravel Swagger

repository·master·Indexed 41 days ago

https://github.com/ronasit/laravel-swagger

A plugin for Laravel that generates OpenAPI 3.1.0 documentation for REST APIs by analyzing PHPUnit tests and FormRequest validation rules. It ensures documentation stays in sync with code by extracting information during test execution, supporting DocBlock annotations for customization, and providing integration with Postman.

Tokens
3.4K
Snippets
12
Records
18
Agent score
52%

What's inside Laravel Swagger

  1. How Laravel Swagger generates documentation

    master

    Laravel Swagger generates REST API documentation by observing your PHPUnit tests. It extracts information from your Request classes and Controller methods during test execution.

    To ensure documentation is captured correctly:

    1. Use FormRequests: Define validation rules in the rules() method of a FormRequest class. The plugin uses these rules to describe input parameters.
    2. Use Dependency Injection: Inject the Request class into your controller methods. If you don't use dependency injection, the "Parameters" block in the documentation will be empty.
    3. Write Feature Tests: Create tests that hit your API endpoints (e.g., using $this->json(...)). The plugin intercepts these requests to build the spec.
    4. Run Tests: The documentation is built during the test run.
    // 1. Request with rules
    class UpdateUserDataRequest extends FormRequest {
        public function rules() {
            return ['name' => 'string', 'age' => 'integer'];
        }
    }
    
    // 2. Controller using DI
    class UserController extends Controller {
        public function update(UpdateUserDataRequest $request) {
            return response('', 204);
        }
    }
    
    // 3. Test to trigger documentation generation
    public function testUpdate() {
        $this->json('put', '/users/1', ['name' => 'New Name']);
    }
  2. Install Laravel Swagger

    master

    Follow these steps to integrate Laravel Swagger into your project:

    1. Install via Composer:

      composer require ronasit/laravel-swagger
    2. Publish the configuration:

      php artisan vendor:publish --provider=RonasIT\AutoDoc\AutoDocServiceProvider
    3. Register the Middleware: Add \RonasIT\AutoDoc\Http\Middleware\AutoDocMiddleware::class to your global HTTP middleware list in bootstrap/app.php.

    4. Update your Test Case: Add the \RonasIT\AutoDoc\Traits\AutoDocTestCaseTrait trait to your tests/TestCase.php file.

    5. Configure documentation saving: Choose one of two methods:

      • PHPUnit Extension (Legacy): Add RonasIT\AutoDoc\Support\PHPUnit\Extensions\SwaggerExtension to the <extensions> block in phpunit.xml. Note: This method will be removed in PHPUnit 10+.
      • CI/CD Command: Call php artisan swagger:push-documentation after the tests stage in your CI/CD pipeline.
    composer require ronasit/laravel-swagger
    php artisan vendor:publish --provider=RonasIT\AutoDoc\AutoDocServiceProvider
  3. Integrate with Postman

    master

    You can import your generated API documentation directly into Postman. The package provides a dedicated endpoint that outputs the OpenAPI spec in a Postman-compatible format.

    Endpoint: {your-app-url}/auto-doc/documentation/postman

    Use this URL within the Postman Import tool.

  4. Validation rules for Path Parameters

    master

    The validator enforces strict rules for parameters defined with in: 'path':

    1. Placeholder Matching: Every path parameter defined in the parameters array must have a corresponding {placeholder} in the URL path.
    2. No Missing Placeholders: If a {placeholder} exists in the path, a parameter with a matching name must be defined.
    3. Required Status: Path parameters cannot be optional. If a parameter is part of the path, it must have required: true set in its definition.
    4. Uniqueness: Path placeholders within a single path must be unique.
  5. Validation rules for Body and FormData parameters

    master

    To prevent ambiguous request definitions, the validator enforces the following constraints on operation parameters:

    • Single Body Parameter: An operation can have at most one parameter where in: 'body'.
    • Mutual Exclusivity: An operation cannot contain both a body parameter and formData parameters.
    • Consumes Requirement: If formData parameters are used, the operation must explicitly define a consumes value of either application/x-www-form-urlencoded or multipart/form-data.
  6. Configure Laravel Swagger settings

    master

    The following configuration keys are available to customize the plugin's behavior:

    • auto-doc.route: The URL path where the generated documentation can be viewed.
    • auto-doc.basePath: The root URL prefix for your API.
    • documentation_viewer: Allows you to switch between different OpenAPI documentation viewers (changes take effect immediately without rebuilding).
    • additional_paths: An array of paths to other valid OpenAPI files that should be merged with the primary documentation.
  7. How the SwaggerService orchestrates documentation generation

    master

    The SwaggerService is the central engine of the package. It works by intercepting HTTP requests and responses to automatically build an OpenAPI 3.1.0 specification.

    The Lifecycle:

    1. Initialization: It loads configuration from auto-doc.php and initializes a SwaggerDriverContract implementation (defined in your config) to manage temporary data storage.
    2. Data Collection: During a request/response cycle, the addData(Request $request, $response) method is called. This method:
      • Parses the URI and HTTP method.
      • Extracts parameters from the Request (including FormRequests, validation rules, and attributes).
      • Extracts schema information and examples from the Response.
      • Reads DocBlock annotations from the controller/request classes to enrich descriptions, summaries, and deprecation status.
    3. Persistence: The collected data is saved via the configured driver.
    4. Generation: When requested, the service merges all collected path and component data, validates it against the OpenAPI spec, and provides the final JSON/array content.
  8. Run the development environment with Docker Compose

    master

    The project provides a docker-compose.yml file to set up a development environment using an Nginx and PHP 8.4 container. This environment maps the current directory to /app inside the container and exposes standard web ports.

    services:
      nginx:
        image: ghcr.io/ronasit/php-nginx-dev:8.4
        working_dir: /app
        ports:
          - 80:80
          - 443:443
        volumes:
          - ./:/app
  9. Configure the LocalDriver production path

    master

    The LocalDriver requires a specific configuration key to know where to save the generated OpenAPI documentation on your local filesystem. You must set the production_path within the auto-doc.drivers.local configuration group. If this path is not provided, the driver will throw a MissedProductionFilePathException during instantiation.

    // Example configuration in config/auto-doc.php
    'drivers' => [
        'local' => [
            'production_path' => public_path('swagger/api-docs.json'),
        ],
    ],
  10. Configure security schemes and drivers

    master

    The SwaggerService supports documenting security requirements (like API Keys or Bearer tokens) by mapping a configured security driver to the OpenAPI securitySchemes component.

    To use this, you must define a security driver in your auto-doc configuration and specify which one to use in the security key.

    Example Configuration:

    // config/auto-doc.php
    return [
        'security' => 'api_key_auth', // The key to use from security_drivers
    
        'security_drivers' => [
            'api_key_auth' => [
                'type' => 'apiKey', // e.g., 'apiKey' or 'mutualTLS'
                'name' => 'X-API-KEY', // The header/query/cookie name
                'in' => 'header', // 'header', 'query', or 'cookie'
            ],
        ],
        // ...
    ];

    When a request is processed, the service checks if the request satisfies the security requirement (e.g., presence of the header) before adding the security requirement to the specific operation in the OpenAPI spec.

    'security' => 'api_key_auth',
    
    'security_drivers' => [
        'api_key_auth' => [
            'type' => 'apiKey',
            'name' => 'X-API-KEY',
            'in' => 'header',
        ],
    ],
  11. Merge additional OpenAPI documentation files

    master

    You can instruct the service to include external OpenAPI files into your generated documentation by using the additional_paths configuration key. This is useful for merging manually written specs or documentation from other services.

    In your config/auto-doc.php:

    'additional_paths' => [
        base_path('docs/external-api.json'),
        base_path('docs/other-module.yaml'),
    ],

    The service will attempt to load these files, validate them, and merge their paths and components.schemas into the main documentation. If a path or schema already exists in the generated documentation, the existing one is preserved (it does not overwrite).

    'additional_paths' => [
        base_path('docs/external-api.json'),
    ],