#TECH

Swagger Integration with Laravel

Do you work on the documentation for your API in the application? I hear a faint yes! I understand it’s one of the areas which every developer despises. But here’s the thing- documentation is the core part of any application.

It helps you understand what an application does without jumping into the whole application. Without any documentation, even a small project is hard to understand by peers and co-workers. They will find difficult to find the API endpoints and usages.

Swagger is the most popular and real-time authorization framework of API developer tool. Swagger allows real-time authorization and endpoint testing for testers and developers without any extra efforts. Swagger is launched and maintained by SmartBear.

This tutorial will guide you on how you can integrate swagger with Laravel project in a few steps. So let’s start integrating swagger in our application-

Swagger integration with Laravel

 

  1. Let’s create our new Laravel application using the following mentioned command.

composer create-project --prefer-dist laravel/laravel blog

 

      2. Install the composer using the command mentioned below.

composer require zircote/swagger-php

     

      3. Swagger requires the hostname of our application, so in this tutorial, we will be using hostname as localhost. You need to run the following commands to create a development folder and corresponding swagger scripts.

mkdir development && cd development
touch swagger.sh && chmod +x swagger.sh
touch swagger-constants.php
touch swagger-v1.php

 

      4. We need to edit the swagger.sh to generate the documentation. Let’s add the script in the file. This file also has the path where we will show the output JSON.

#!/bin/bash

mkdir ../public/swagger php ../vendor/bin/swagger --bootstrap ./swagger-constants.php --output ../public/swagger ./swagger-v1.php ../app/Http/Controllers

   

        5. Now we need to add the following lines inside our swagger-constants.php file.

<?php
define("API_HOST", 'localhost:8000');

   

        6. Edit the last file that we created in Laravel scripts i.e swagger-v1.php

<?php
/**
 * @SWG\Swagger(
 *     schemes={"http"},
 *     host=API_HOST,
 *     basePath="/",
 *     @SWG\Info(
 *         version="1.0.0",
 *         title="Swagger Integration with PHP Laravel",
 *         description="Integrate Swagger in Laravel application",
 *         termsOfService="",
 *         @SWG\Contact(
 *             email="sachit.wadhawan@quovantis.com"
 *         ),
 *     ),
 * )
 */

     

       7. Run the scripts file swagger.sh using the following command.

./swagger.sh

     

       8. You should see the output as mentioned below.

# Output
Swagger-PHP 2.0.13
------------------
-----------------------
0 operations documented
-----------------------

Hurray! But wait, we still need to do some more setup to finally test our application’s endpoints.

      9. Create a custom controller called GetComponentDetailController inside the (app/Http/Controllers/GetComponentDetailController.php) and endpoints to access this controller inside our route file.

Route::get('/getDeatails, 'GetComponentDetailController@getData');


10. Our GetComponentSectionInfo controller will look like this-

<?php

namespace App\Http\Controllers;

use http\Env\Response;
use Illuminate\Http\Request;

class GetComponentDetailController extends Controller
{
    /**
     * Get Component Name and Component Description
     *
     * @param Request $request
     * @return Response|string
     */
    public function getData(Request $request)
    {
        $userData = $request->only([
            'ComponentName',
            'ComponentDescription',
        ]);

        if (empty($userData['ComponentName']) && empty($userData['ComponentDescription'])) {
            return new \Exception('Missing data', 404);
        }
        return $userData['ComponentName'] . ' ' . $userData['ComponentDescription'];
    }
}


11. We can now test this endpoint on our browser like this-

http://localhost:8000/getDetails?ComponentName=sachit&ComponentDescription=wadhawan

 

If you followed all the steps correctly, you will see the output as below-
      Output-

Component Name is sachit and Component Description is wadhawan


12. Till now we have our documentation ready with the respected output but we need to add user interface so that we can test our application’s endpoints. When we run our swagger.sh file, it generates a subfolder inside a public folder with a file named as swagger.json which contains the information about endpoints and required data.

/app
/public
|__ /swagger


13. For the user interface download the entire folder from this 
GitHub link and place it inside the swagger folder. Now, we need to edit the paths in the downloaded files. Let’s first update the index.html which is placed in dist folder. For the reference, you can copy and paste directly from the below-

<!-- HTML for static distribution bundle build -->
<!DOCTYPE html>
<html lang="en">
 <head>
   <meta charset="UTF-8">
   <title>Swagger UI</title>
   <link rel="stylesheet" type="text/css" href="./swagger-ui.css" >
   <link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
   <link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
   <style>
     html
     {
       box-sizing: border-box;
       overflow: -moz-scrollbars-vertical;
       overflow-y: scroll;
     }

     *,
     *:before,
     *:after
     {
       box-sizing: inherit;
     }

     body
     {
       margin:0;
       background: #fafafa;
     }
   </style>
 </head>

 <body>
   <div id="swagger-ui"></div>

   <script src="./swagger-ui-bundle.js"> </script>
   <script src="./swagger-ui-standalone-preset.js"> </script>
   <script>
   window.onload = function() {

     // Build a system
     const ui = SwaggerUIBundle({
       url: "window.location.protocol + "//" + window.location.hostname + ":" + window.location.port + "/swagger/swagger.json",
       dom_id: '#swagger-ui',
       deepLinking: true,
       presets: [
         SwaggerUIBundle.presets.apis,
         SwaggerUIStandalonePreset
       ],
       plugins: [
         SwaggerUIBundle.plugins.DownloadUrl
       ],
       layout: "StandaloneLayout"
     })

     window.ui = ui
   }
 </script>
 </body>
</html>


14. To generate documentation in the swagger.json file, let’s add the swagger annotation above the getData method and run
./swagger.sh file to generate the JSON in the swagger.json file.

/**
* @SWG\Get(
*     path="/getDetails",
*     description="Return a Component name and description",
*     @SWG\Parameter(
*         name="ComponentName",
*         in="query",
*         type="string",
*         description="Component name",
*         required=true,
*     ),
*     @SWG\Parameter(
*         name="ComponentDescription",
*         in="query",
*         type="string",
*         description="Component Description",
*         required=true,
*     ),
*     @SWG\Response(
*         response=200,
*         description="OK",
*     ),
*     @SWG\Response(
*         response=404,
*         description="Please provide both data"
*     )
* )
*/


15. Now try this 
link to open swagger UI. You should see something like this.


16. Click on any route endpoint, there will be an input field for component name and component description as shown above. Enter the value and execute the GET request. You will see the output like this.

You can check this link for more swagger documentation. 

Hope you find this useful. For any help, please drop in your comments.


Reference-

  1. Check this Github link.
  2. Check this YouTube video.

You might also like