Laravel API Docs: A Guide to L5 Swagger

API documentation is essential to ensure that other developers can understand and use your endpoint efficiently. In Laravel, one of the simplest ways to document your APIs is by using the L5 Swagger package, which generates interactive docs based on OpenAPI. Installing L5 Swagger To get started, install the package via Composer: composer require darkaonline/l5-swagger After Installation, publish the package configuration: php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider" This will create a configuration file in config/l5-swagger.php Now, generate the documentation for the first time by running: php artisan l5-swagger:generate The documentation will be available at: http://your-app-name.test/api/documentation Documenting Endpoint

Feb 20, 2025 - 00:51
 0
Laravel API Docs: A Guide to L5 Swagger

API documentation is essential to ensure that other developers can understand and use your endpoint efficiently. In Laravel, one of the simplest ways to document your APIs is by using the L5 Swagger package, which generates interactive docs based on OpenAPI.

Installing L5 Swagger

To get started, install the package via Composer:

composer require darkaonline/l5-swagger

After Installation, publish the package configuration:

php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider"

This will create a configuration file in config/l5-swagger.php

Now, generate the documentation for the first time by running:

php artisan l5-swagger:generate

The documentation will be available at: http://your-app-name.test/api/documentation

Documenting Endpoint


/**
 * @OA\Get(
 *     path="/api/users",
 *     summary="Retrieve a list of users",
 *     @OA\Tags(name="Users"),
 *     @OA\Response(
 *         response=200,
 *         description="List of users",
 *         @OA\JsonContent(
 *             type="array",
 *             @OA\Items(ref="#/components/schemas/User")
 *         )
 *     ),
 *     @OA\Response(
 *         response=401,
 *         description="Unauthorized"
 *     )
 * )
 */
public function index() {
    return User::all();
}

Defining Schemas

We can define a schema for API response models to make the documentation more detailed:

/**
 * @OA\Schema(
 *     schema="User",
 *     type="object",
 *     title="User",
 *     @OA\Property(property="id", type="integer", example=1),
 *     @OA\Property(property="name", type="string", example="John Doe"),
 *     @OA\Property(property="email", type="string", example="johndoe@example.com")
 * )
 */

Conclusion

With just a few steps, we successfully integrated and generated API documentation in Laravel using L5 Swagger. By adding Schemas and Tags, our documentation becomes even more comprehensive and developer-friendly.

Do you have any questions or suggestions? Leave a comment!