DEV Community

Aleson França
Aleson França

Posted on

1

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

<?php
/**
 * @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();
}
Enter fullscreen mode Exit fullscreen mode

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")
 * )
 */
Enter fullscreen mode Exit fullscreen mode

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!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

Try REST API Generation for Snowflake

DevOps for Private APIs. Automate the building, securing, and documenting of internal/private REST APIs with built-in enterprise security on bare-metal, VMs, or containers.

  • Auto-generated live APIs mapped from Snowflake database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay