Laravel API Documentation Made Easy: Step-by-Step Swagger Integration

MD ARIFUL HAQUE - Oct 29 - - Dev Community

Integrating Swagger with Laravel for API documentation involves a few steps to set up Swagger UI and configure your endpoints for documentation. Swagger is popular for RESTful API documentation as it generates interactive, easily navigable documentation. Here’s a step-by-step guide on how to integrate Swagger with a Laravel application:

Prerequisites

Ensure you have the following:

  • Laravel project installed (composer create-project --prefer-dist laravel/laravel your_project_name)
  • PHP version >= 7.4
  • Composer

Step 1: Install Swagger Package

Install darkaonline/l5-swagger, a popular package for integrating Swagger with Laravel.

Run the following command in your terminal:

composer require "darkaonline/l5-swagger"
Enter fullscreen mode Exit fullscreen mode

Step 2: Publish Swagger Configuration

Once the package is installed, publish the configuration file to allow customization.

php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider"
Enter fullscreen mode Exit fullscreen mode

This command will generate a l5-swagger.php config file in the config directory and a swagger folder in the public directory, which is where Swagger UI assets will be stored.

Step 3: Configure Swagger in Laravel

Open the config/l5-swagger.php file and update a few settings for your API. Some key settings to check:

  • default: Set to default if you plan on using a single Swagger configuration.
  • documentations: Adjust any API information and set the paths and basePath for the routes.
  • info: Customize the API documentation information:
  'info' => [
      'title' => 'My API Documentation',
      'description' => 'This is the API documentation for my Laravel application.',
      'version' => '1.0.0',
      'termsOfService' => 'http://swagger.io/terms/',
      'contact' => [
          'email' => 'contact@example.com',
      ],
      'license' => [
          'name' => 'Apache 2.0',
          'url' => 'https://www.apache.org/licenses/LICENSE-2.0.html',
      ],
  ],
Enter fullscreen mode Exit fullscreen mode

Step 4: Create Swagger Annotations

Swagger uses annotations to document each API endpoint. Install swagger-php to enable annotations support.

composer require "zircote/swagger-php"
Enter fullscreen mode Exit fullscreen mode

Now, in your controller methods, add Swagger annotations for documentation. Here’s an example for a UserController:

use App\Models\User;
use Illuminate\Http\Request;

/**
 * @OA\Get(
 *     path="/api/users",
 *     tags={"Users"},
 *     summary="Get list of users",
 *     description="Returns list of users",
 *     @OA\Response(
 *         response=200,
 *         description="successful operation"
 *     ),
 *     @OA\Response(
 *         response=400,
 *         description="Bad request"
 *     ),
 *     @OA\Response(
 *         response=404,
 *         description="Resource Not Found"
 *     )
 * )
 */
public function index() {
    return User::all();
}
Enter fullscreen mode Exit fullscreen mode

This annotation describes an endpoint /api/users, its response codes, and what each response represents.

Step 5: Generate Swagger Documentation

To generate the Swagger JSON documentation, run the following Artisan command:

php artisan l5-swagger:generate
Enter fullscreen mode Exit fullscreen mode

This command generates a swagger.json file in the storage/api-docs folder. This file contains your documented endpoints in a JSON format readable by Swagger UI.

Step 6: View Swagger UI

To view your generated API documentation, navigate to:

http://your-domain.com/api/documentation
Enter fullscreen mode Exit fullscreen mode

Here, you should see Swagger UI displaying your API endpoints, methods, and descriptions in an interactive format.

Step 7: Customize Swagger UI (Optional)

In the config/l5-swagger.php file, you can make additional customizations, such as enabling/disable Swagger UI, updating theme colors, and setting custom paths.

Example of a Complete Controller with Annotations

Here's a complete UserController example to demonstrate how multiple endpoints can be documented with Swagger annotations:

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * @OA\Get(
     *     path="/api/users",
     *     tags={"Users"},
     *     summary="Get list of users",
     *     description="Returns list of users",
     *     @OA\Response(
     *         response=200,
     *         description="successful operation"
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="Bad request"
     *     )
     * )
     */
    public function index() {
        return User::all();
    }

    /**
     * @OA\Post(
     *     path="/api/users",
     *     tags={"Users"},
     *     summary="Create a new user",
     *     description="Create a new user in the system",
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             required={"name","email"},
     *             @OA\Property(property="name", type="string", example="John Doe"),
     *             @OA\Property(property="email", type="string", example="john@example.com")
     *         ),
     *     ),
     *     @OA\Response(
     *         response=201,
     *         description="User created successfully"
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="Bad request"
     *     )
     * )
     */
    public function store(Request $request) {
        $validated = $request->validate([
            'name' => 'required|string',
            'email' => 'required|string|email|unique:users',
        ]);

        $user = User::create($validated);

        return response()->json($user, 201);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 8: Update Routes to Match Documentation

Ensure your routes in routes/api.php match the documented endpoints in your Swagger annotations:

Route::get('users', [UserController::class, 'index']);
Route::post('users', [UserController::class, 'store']);
Enter fullscreen mode Exit fullscreen mode

Summary

  1. Install Swagger via composer.
  2. Publish and configure the Swagger package.
  3. Annotate endpoints in your controllers.
  4. Generate Swagger JSON using the Artisan command.
  5. Access Swagger UI to view interactive API documentation.

This setup will give you a fully functional Swagger integration with Laravel. You can customize and add more complex annotations as needed.

Connect with me:@ LinkedIn and checkout my Portfolio.

Please give my GitHub Projects a star ⭐️

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player