How to write Swagger documentation for Laravel API. Tips & examples
API documentation becomes very necessary when you split the team into Backend and Frontend. And even more when you divide your monorepo into parts or even microservices.
I will show you how easily create API documentation for your Laravel API using swagger.
composer require "darkaonline/l5-swagger"
Then publish config and all view files:
php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider"
Next, open a config/l5-swagger.php file. Let’s walk through essential keys:
- routes.api — This is an URL for accessing documentation UI. Your frontend team will be using it to access documentation. By default, it is api/documentation . I prefer changing it to something smaller like api/docs
- generate_always — I prefer disabling it as it will generate docs on the fly. Not useful with big API. You can always manually run php artisan l5-swagger:generate
Those are the most important to start. Now if you try to create docs using this command
php artisan l5-swagger:generate
It will return an error
Required @OA\Info() not found
That means that you have to create that notation first. So let’s add it. I prefer creating Abstract controller for an API, but you can add this to app/Http/Controllers/Controller.php
* title="Your super ApplicationAPI",
*/class Controller extends BaseController
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
Next, we need to add docs for at least one route. Let’s add it for app/Http/Controllers/Auth/LoginController.php:
* summary="Sign in",
* description="Login by email, password",
* description="Pass user credentials",
* @OA\Property(property="email", type="string", format="email", example="firstname.lastname@example.org"),