Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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-

 

  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

/**
 * @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="[email protected]"
 *         ),
 *     ),
 * )
 */

     

       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-

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-



 
   Swagger UI


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.


This post first appeared on C.R.A.P. Design Principles To Improve Visual Appeal, please read the originial post: here

Share the post

Swagger Integration with Laravel

×

Subscribe to C.r.a.p. Design Principles To Improve Visual Appeal

Get updates delivered right to your inbox!

Thank you for your subscription

×