nhattuanbl/lara-swagger

Swagger ui doc for laravel 6,7 or 8

1.6.1 2024-05-23 15:55 UTC

This package is not auto-updated.

Last update: 2024-05-23 08:56:03 UTC


README

Latest Version on Packagist Software License Total Downloads

Swagger ui doc for laravel 6,7 or 8

Requires

  • PHP: >=8.0
  • Laravel: latest version 6, 7, or 8

    Installation

    composer require nhattuanbl/lara-swagger
    
    php artisan vendor:publish --provider="LaraSwagger\LaraSwaggerServiceProvider" --tag="views"
    

    Edit: config/app.php

    'providers' => [
    ...
    \LaraSwagger\LaraSwaggerServiceProvider::class,
    ];
    

    Usage

  • Example route:
    Route::get('/', function () {
     return view('vendor/lara_swagger/lara_swagger');
    });
    

Route::get('/swagger.json', function (\LaraSwagger\LaraSwagger $laraSwagger) {

return response($laraSwagger->getDocs())->header('Content-Type', 'application/json');

});

Edit: `resources/views/vendor/lara_swagger/lara_swagger.blade.php`

window.onload = function() {

// Begin Swagger UI call region
const ui = SwaggerUIBundle({
    url: "{{ url('swagger.json') }}", // <=== change to your route
    dom_id: '#swagger-ui',
    deepLinking: true,
 - Create model and controller:

php artisan make:model Product --controller --resource


namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use LaraSwagger\Attributes\LaraSwagger;

[LaraSwagger]

class Product extends Model {

use HasFactory;

}

![img](https://i.imgur.com/b1dwopy.jpg)

<details>
<summary>Parameters</summary>

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use LaraSwagger\Attributes\Parameter; use LaraSwagger\Attributes\LaraSwagger;

/**

  • @property string name
  • @property int quantity */

    [

    LaraSwagger( // controller: CustomController::class, // tag: 'Product', // description: string|['get' => 'markdown support']

     hidden: ['isInStock'],
     readOnly: ['id'],
    

    ), Parameter(name: 'page', type: 'integer', required: true, default: 1, description: 'Pagination', minimum: 1), Parameter(name: 'soldOut', type: 'boolean'), Parameter(name: 'status', type: 'string', enum: ['pending', 'delivered']), ] class Product extends Model { use HasFactory;

    protected $fillable = [

     'email'
    

    ];

    protected $casts = [

     'quantity' => 'int'
    

    ];

    protected $hidden = [

     'hasCategory'
    

    ];

    protected $dates = [

     'created_at'
    

    ];

    public function isInStock(): bool {

     return false;
    

    }

    public function hasCategory(): bool {

     return true;
    

    } }

    ![img](https://i.imgur.com/JfWYz1G.png)
    </details>
    
Add auth ```php Route::get('/swagger.json', function (\LaraSwagger\LaraSwagger $laraSwagger) { $laraSwagger->info = [ 'title' => 'some title', 'description' => 'some desc', 'version' => '2.0', 'termsOfService' => 'https://google.com', 'contact' => [ 'name' => 'nhattuanbl', 'email' => 'nhattuanbl@gmail.com' ] ]; $laraSwagger->security = [ 'apiKey' => [ 'type' => 'apiKey', 'in' => 'header', 'name' => 'X-API-Key' ], 'appId' => [ 'type' => 'apiKey', 'in' => 'header', 'name' => 'X-APP-ID' ], 'OAuth2' => [ 'type' => 'oauth2', 'flows' => [ 'authorizationCode' => [ 'authorizationUrl' => 'https://example.com/oauth/authorize', 'tokenUrl' => 'https://example.com/oauth/token', 'scopes' => [ 'read' => 'Grants read access', 'write' => 'Grants write access', 'admin' => 'Grants access to admin operations' ] ] ] ] ]; $laraSwagger->callbackOperation = function(string $method, string $endpoint, array $swagger) { //hide all get method if ($method == 'get') { return null; } if ($endpoint == '/users/{id}' && $method == 'put') { $swagger['security'] = [ ['apiKey' => []], ['appId' => []], ['OAuth2' => ['read', 'write']], ]; } return $swagger; }; $servers = [ ['url' => 'v1', 'description' => 'api v1'], ['url' => 'v2'] ]; return response($laraSwagger->getDocs($servers))->header('Content-Type', 'application/json'); }); ```
Add parameter ```php <?php namespace App\Http\Controllers; use App\Models\Product; use Illuminate\Http\Request; use LaraSwagger\Attributes\Parameter; use LaraSwagger\Attributes\Response; class ProductController extends Controller { ... #[Parameter(name: 'hasAvatar', type: 'boolean', default: true)] public function update(Request $request, $id) { // } } ``` ![img](https://i.imgur.com/b3BIkhk.jpg)
Add response ```php #[Response(code: 404, ref: '#/components/responses/NotFound')] public function destroy($id) { // } ``` ![img](https://i.imgur.com/oI6ME9S.jpg)
Add custom endpoint ```php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use LaraSwagger\Attributes\Operation; use LaraSwagger\Attributes\RequestBody; use LaraSwagger\Attributes\Response; class AuthController extends Controller { #[Operation(endpoint: '/login', method: 'post', tag: 'Auth')] #[RequestBody(name: 'email', type: 'string')] #[RequestBody(name: 'remember', type: 'boolean', example: true)] #[RequestBody(name: 'avatar', type: 'binary')] #[RequestBody(name: 'username', type: 'string', contentType: 'application/json')] #[RequestBody(name: 'password', type: 'string', contentType: 'application/json')] #[Response(code: 401, ref: '#/components/responses/Unauthorized')] public function login() { // } } ``` ![img](https://i.imgur.com/TTTnexL.jpg)
Override ```php class ProductController extends Controller { ... #[ Operation(endpoint: '/products', method: 'post', tag: 'Product'), Parameter(name: 'var1', type: 'integer', enum: [1,2,3,4]), Parameter(name: 'var2', type: 'integer', in: 'query', minimum: 10, maximum: 100), Response(code: 201, description: 'Created', content: [ 'application/json' => [ 'schema' => [ 'type' => 'object', 'properties' => [ 'message' => ['type' => 'string'], 'success' => ['type' => 'boolean'] ] ] ] ]), ] public function store(Request $request) { // } ... } ``` ![img](https://i.imgur.com/rgNrG95.png)