swagger simplifies the process of API development and documentation. In Laravel, Swagger is often integrated using packages that provide tools to generate interactive API documentation based on the OpenAPI Specification.
 

Step 1: Install the Swagger Package

Open your terminal and navigate to your Laravel project's root directory. Use Composer to install the Swagger package. As of my last knowledge update in January 2022, the darkaonline/l5-swagger package is a popular choice for Laravel Swagger integration. To install this package, run the following command:
 
composer require darkaonline/l5-swagger

This command fetches the necessary files and adds the Swagger package to your Laravel project.

 

Step 2: Publish Configuration

Once the package is installed, you need to publish its configuration file. This file allows you to customize various settings related to Swagger in your Laravel application.
 
php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider"

 

This command will copy the configuration file to the config directory of your Laravel project.

Step 3: Configure Swagger

Open the configuration file (config/l5-swagger.php) and customize the settings according to your Laravel project. Pay attention to options such as enable, api, and paths.
 

Step 4: Set Base URL with an Environment Variable (Optional)

Consider setting the base URL as an environment variable in your .env file:
 
L5_SWAGGER_CONST_HOST=http://project.test/api/v1

 

Step 5: Annotating Laravel Code

1. @OA\Info: General API Information
 
 
       /**
         * @OA\Info(
         *      title="Your API Title",
         *      version="1.0",
         *      description="Your API Description",
         *      @OA\Contact(
         *          email="contact@example.com",
         *          name="Contact Name"
         *      ),
         *      @OA\License(
         *          name="Your API License",
         *          url="http://yourapi.com/license"
         *      )
         * )
         */
 
This annotation provides general information about your API, including its title, version, and a brief description. You can also include additional details such as contact information and licensing.
 
2. @OA\SecurityScheme: JWT Authentication
 
      /**
       * @OA\SecurityScheme(
       *      securityScheme="bearerAuth",
       *      type="http",
       *      scheme="bearer",
       *      bearerFormat="JWT",
       * )
       */
     
This annotation defines a security scheme named "bearerAuth" for handling JWT (JSON Web Token) authentication. It specifies that the JWT should be passed in the "Authorization" header using the "bearer" scheme. Adjust the details according to your specific JWT authentication setup. 
 
Where to Place these Annotations 
You would typically place these annotations at the beginning of your Swagger-annotated Laravel controller file or in a dedicated file specifically for Swagger documentation. Including them at the beginning helps provide an overview of the API's general information and authentication details. Here's a hypothetical example of how you might structure your Swagger annotations in a Laravel controller:
 
        /**
         * @OA\Info(
         *      title="Your API Title",
         *      version="1.0",
         *      description="Your API Description",
         *      @OA\Contact(
         *          email="contact@example.com",
         *          name="Contact Name"
         *      ),
         *      @OA\License(
         *          name="Your API License",
         *          url="http://yourapi.com/license"
         *      )
         * )
         */
        /**
         * @OA\SecurityScheme(
         *      securityScheme="bearerAuth",
         *      type="http",
         *      scheme="bearer",
         *      bearerFormat="JWT",
         * )
         */
        namespace App\Http\Controllers;
        use Illuminate\Http\Request;
        class YourController extends Controller
        {
            // Your controller methods with Swagger annotations
        }
        
 
These annotations set the stage for comprehensive API documentation by providing key information about the API and specifying authentication details. Remember to tailor the annotations to match the specifics of your Laravel API.
 
You can certainly include Swagger annotations in a base controller, such as Controller.php, to be shared across multiple controllers in your Laravel project. By doing so, you centralize the common annotations and make it more efficient to manage and update the Swagger documentation for your API.
 
3. Annotating for functions
Annotating functions in the context of Swagger refers to adding Swagger annotations to the methods (functions) within your Laravel controllers that represent API endpoints. These annotations provide essential metadata about each API endpoint, such as the HTTP method, path, summary, description, parameters, responses, and more. Here's a breakdown of how to annotate functions for Swagger in Laravel:
 
 
Example Annotated Controller Method:
 
 
      /**
       * @OA\Get(
       *      path="/api/users",
       *      operationId="getUsersList",
       *      tags={"Users"},
       *      summary="Get list of users",
       *      description="Returns a list of users",
       *      @OA\Response(
       *          response=200,
       *          description="Successful operation",
       *          @OA\JsonContent(ref="#/components/schemas/User")
       *      ),
       *      @OA\Response(
       *          response=401,
       *          description="Unauthorized"
       *      ),
       *      @OA\Response(
       *          response=403,
       *          description="Forbidden"
       *      ),
       *      @OA\Response(
       *          response=404,
       *          description="Not Found"
       *      )
       * )
       */
      public function getUsers() {
          // Your controller logic here
      }
 
  • @OA\Get: Indicates that this is an HTTP GET request. Other HTTP methods like @OA\Post, @OA\Put, etc., are used for different request types.
  • path="/api/users": Specifies the endpoint path for this API method.
  • operationId="getUsersList": A unique identifier for the operation. It helps distinguish between different operations in your Swagger documentation.
  • tags={"Users"}: Assigns tags to the operation, providing a way to organize and group related API endpoints.
  • summary="Get list of users": A brief summary of what the API endpoint does. It's a concise description intended to quickly convey the purpose.
  • description="Returns a list of users": A more detailed description of the API endpoint, providing additional context or information.
  • @OA\Response: Describes the possible responses for this API endpoint, including HTTP status codes and response content.
  • @OA\JsonContent(ref="#/components/schemas/User"): Specifies the response content type as JSON and refers to the Swagger schema for the "User" data model.
 

Step 6: Generate Swagger Documentation

Run the Swagger documentation generator to create the documentation files:

php artisan l5-swagger:generate
 

Step 7: Access Swagger UI

Visit the Swagger UI in your web browser. By default, it's often available at:

http://localhost:8000/api/documentation

Adjust the URL based on your Laravel project's configuration.

 

Step 8: Explore and Test API Documentation

Explore the Swagger UI to view and test your API documentation. Verify that the generated documentation accurately reflects your Laravel code.
 

Step 9: Keep Documentation Updated

As your Laravel project evolves, remember to update your Swagger annotations to keep the API documentation accurate. Re-run the documentation generator as needed.

By following these steps, you should have a well-documented Laravel API using Swagger. Adjust the details based on your project's specific requirements and configurations.