PHPackages                             kr0lik/laravel-dto-to-swagger - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. kr0lik/laravel-dto-to-swagger

ActiveLibrary[API Development](/categories/api)

kr0lik/laravel-dto-to-swagger
=============================

Generate swagger from dto and return type from action.

2.2.0(7mo ago)718.4k↓35.5%5[1 PRs](https://github.com/kr0lik/laravel-dto-to-swagger/pulls)MITPHPPHP ^8.2CI passing

Since Feb 24Pushed 7mo ago1 watchersCompare

[ Source](https://github.com/kr0lik/laravel-dto-to-swagger)[ Packagist](https://packagist.org/packages/kr0lik/laravel-dto-to-swagger)[ RSS](/packages/kr0lik-laravel-dto-to-swagger/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (7)Versions (34)Used By (0)

laravel-dto-to-swagger
======================

[](#laravel-dto-to-swagger)

Overview
--------

[](#overview)

**laravel-dto-to-swagger** is an automatic Swagger documentation generator based on Laravel routing and strongly typed DTOs for request and response data.

💡 **No need to manually define schemas, tags, or routes!** The documentation is generated entirely based on your route definitions and DTOs. Just rely on your type annotations, and let the package handle the rest.

💡 Integrates with [`spatie/laravel-data`](https://github.com/spatie/laravel-data), making Swagger generation seamless and fully automated.

💡 The schema fully reflects your type definitions without manual intervention.

💡 Based on `zircote/swagger-php` for powerful OpenAPI support.

---

Installation &amp; Setup
------------------------

[](#installation--setup)

```
composer require kr0lik/laravel-dto-to-swagger
```

Register the service provider in `config/app.php` (if needed):

```
Kr0lik\DtoToSwagger\DtoToSwaggerServiceProvider::class,
```

Publish the configuration file (swagger.php):

```
$ php artisan vendor:publish --tag=swagger-config
```

---

Configuration
-------------

[](#configuration)

The config file is located at `config/swagger.php`. You can define multiple configurations using keys (e.g., `default`, `custom-config`).

**Configuration Options:**

- `savePath`: Path for the generated Swagger YAML file.
- `includeMiddlewares`, `excludeMiddlewares`: Define which middlewares to include/exclude.
- `includePatterns`, `excludePatterns`: Control route inclusion/exclusion patterns.
- `middlewaresToAuth`: Define authentication middlewares (e.g., `auth:sanctum`).
- `tagFromControllerName`, `tagFromControllerFolder`, `tagFromActionFolder`, `tagFromMiddlewares`: Control Swagger tags generation.
- `fileUploadType`: Define the class used for file upload with `multipart/form-data` schema.
- `defaultErrorResponseSchemas`, `requestErrorResponseSchemas`: Configure default error response schemas.
- `openApi`: Base OpenAPI configuration, including:
    - `info`: API metadata (title, version, description, etc.).
    - `servers`: List of API servers.
    - `components`: Reusable elements like security schemes and schemas.
    - etc...

---

Usage
-----

[](#usage)

Ensure that your controllers and DTOs are properly typed.

To ensure correct schema generation, DTOs must implement one of the following interfaces depending on the type of data being described:

```
`Kr0lik\DtoToSwagger\Contract\JsonRequestInterface` – for JSON request bodies.
`Kr0lik\DtoToSwagger\Contract\QueryRequestInterface` – for query parameters.
`Kr0lik\DtoToSwagger\Contract\HeaderRequestInterface` – for request headers.
`Kr0lik\DtoToSwagger\Contract\JsonResponseInterface` – for JSON responses.

```

This approach allows you to consolidate all request-related data into a single DTO while maintaining complete Swagger documentation coverage.

#### Defining Additional Parameters in JsonRequestInterface

[](#defining-additional-parameters-in-jsonrequestinterface)

Even if a DTO implements JsonRequestInterface (which primarily describes the request body), you can still define query parameters, path parameters, or headers within the same DTO. To do this, use OpenAPI attributes such as:

```
#[OpenApi\Attributes\Parameter(in: 'query')] – for query parameters.
#[OpenApi\Attributes\Parameter(in: 'path')] – for path parameters.
#[OpenApi\Attributes\Parameter(in: 'header')] – for header parameters.

```

By implementing the appropriate interface, you enable automatic documentation generation without the need for manual schema definitions.

Update the config/swagger.php file according to your needs.

You can configure multiple configurations (e.g., default, else-one).

```
//swagger.php
return [
    'default' => [
        'savePath' => base_path('swagger.yaml'),
        'includeMiddlewares' => ['api'], // string[]
        'includePatterns' => [], // string[]
        'excludeMiddlewares' => [], // string[]
        'excludePatterns' => [], // string[]
        'middlewaresToAuth' => ['auth:sanctum' => ['bearerAuth' => []]], // array
        'tagFromControllerName' => true, // bool
        'tagFromControllerFolder' => false, // bool
        'tagFromActionFolder' => true, // bool
        'tagFromMiddlewares' => ['api', 'admin', 'web'], // string[]
        'fileUploadType' => SymfonyUploadedFile::class,
        'defaultErrorResponseSchemas' => [
            500 => [
                'description' => 'Error.',
                'content' => [
                    'application/json' => [
                        'schema' => [
                            '$ref' => '#/components/schemas/ErrorResponse',
                        ],
                    ],
                ],
            ],
        ], // array

        'openApi' => [
            'info' => [
                'version' => '1.0.0',
                'title' => config('app.name'),
            ],
            'servers' => [['description' => 'dev', 'url' => config('app.url')]],
            'components' => [
                'securitySchemes' => [
                    'bearerAuth' => [
                        'type' => 'http',
                        'scheme' => 'bearer',
                        'bearerFormat' => 'api_token',
                    ],
                ],
                'schemas' => [
                    'JsonResponse' => [
                        'type' => 'object',
                        'properties' => [
                            'success' => ['type' => 'boolean'],
                            'message' => ['type' => 'string'],
                            'data' => ['nullable' => true],
                            'errors' => ['nullable' => true],
                        ],
                    ],
                ],
            ],
        ],
    ],
    'else-one' => [
        'savePath' => base_path('swagger-else-one.yaml'),
        'includeMiddlewares' => [],
        'excludeMiddlewares' => ['api'],
        'openApi' => [
            'info' => [
                'version' => '1.0.0',
                'title' => 'Else One Swagger',
            ],
        ],
        'servers' => [['description' => 'else-one', 'url' => config('app.url')]],
    ]
];
```

If the default config is specified, subsequent configs will be based on it. The default config is optional. The keys can be anything.

Ensure your controllers and actions are properly typed and utilize DTOs (Data Transfer Objects) for request and response data.

Run Swagger generation for default configuration:

```
php artisan swagger:generate
```

This generates a `swagger.yaml` file with fully automated API documentation.

If you want to generate using a specific configuration (for example, else-one), you can specify it like this:

```
php artisan swagger:generate else-one
```

This generates a `swagger-else-one.yaml` file from config above.

---

Example
-------

[](#example)

Automatically handle path parameters, query parameters, and request bodies with DTOs.

```
