Swagger

How to Use Swagger Tool for API Documentation

How to Use Swagger Tool for API Documentation?

Swagger is a framework that is used to describe the API using a common language that is familiar to everyone. It can be referred to as a blueprint for a house.

We can compare it with the blueprint of a house. You can choose the building materials of your choice, but you have to stick with the main construction design.

So here are a few commands which will undoubtedly clear your plight of  ‘How to use Swagger tool?’ Swagger – Tool for API documentation.

Swagger – Tool for API documentation.

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

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

2. If you want to install the swagger with the new version of laravel then run the following command.

composer require "darkaonline/l5-swagger:5.8.*"

3. If you want to install the older version of the swagger, then run the command mentioned below.

composer require zircote/swagger-php

4. You can publish Swagger’s configuration and view files into your project by running the following command

$ php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider"

5. Running the above command will generate the l5-swagger.php file inside the config directory. The l5-swagger.php file will contain swagger related configuration.

6. If you are using laravel 5.5 or above versions of it then no need to add L5SwaggerServicesProvider into the config. It will be automatically added using the Auto Discovery feature of laravel.

7. But if you are using the below versions of laravel 5.5, then you need to add the L5SwaggerServicesProvider into the config. You can set the L5SwaggerServicesProvider by following ways.

  • Open your AppServiceProvider (located in app/Providers) and add this line in the register function
$this->app->register(\L5Swagger\L5SwaggerServiceProvider::class);
  • or open your config/app.php and add this line in providers section
L5Swagger\L5SwaggerServiceProvider::class,

8. If you want To generate the Swagger/OpenApi documentation for your API, then you have to follow a set of annotations offered by Swagger to declare and manipulate the output.

You can add these annotations in your controller, model or even a separate file.

9. Once the annotations are added, you can run PHP artisan l5-swagger: generate to generate the documentation.

Or, you can set L5_SWAGGER_GENERATE_ALWAYS to true in your .env file so that your documentation will automatically be generated.

10. Confirm that your settings in config/l5-swagger.php are proper.

Swagger Annotations:

1. Annotations are defined as a format of writing swagger documentation through which they can be generated into swagger.json.

  • Annotations are required to be placed in controllers so that they can directly handle endpoints and validation.

2. @OA\<Method-name>() refers to what kind of HTTP method we’ll use. The method can be GET, POST, PUT or DELETE.

3. Path, the route of our endpoint.

4. @OA\Parameter refers to the name of the parameters that will pass to API.

5. Query, the parameter will be passed through a query string.

6. @OA\Response() which kind of response and code will we return if the data is correct or incorrect.

Example:

  • For this Practical, we can create a custom controller called UserController, and Inside the UserController, we can create a method named as login.
  • First Let’s create a route for the Login method defines inside the UserController. The Route can be set inside the routes/api.php
  • Route of Login method can be look like this
Route::post('login', 'UserController@login');
  • Now create a controller named as UserController inside the app/Http/Controllers directory. In Laravel controller can be created via the following the command.
php artisan make:controller UserController
  • Here is code my UserController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\Auth;
use Lcobucci\JWT\Parser;
use Symfony\Component\HttpFoundation\Response as ResponseHTTP;
use Validator;

/*
  @OA\Info(
      description="",
      version="1.0.0",
      title="Food App API",
 )
 */

/*
  @OA\SecurityScheme(
      securityScheme="bearerAuth",
          type="http",
          scheme="bearer",
          bearerFormat="JWT"
      ),
 */
class AccountController extends Controller {

/*
      @OA\Post(
          path="/v1/login",
          tags={"Login"},
          summary="Login",
          operationId="login",
      
          @OA\Parameter(
              name="email",
              in="query",
              required=true,
              @OA\Schema(
                  type="string"
              )
          ),    
          @OA\Parameter(
              name="password",
              in="query",
              required=true,
              @OA\Schema(
                  type="string"
              )
          ),    
          @OA\Response(
              response=200,
              description="Success",
              @OA\MediaType(
                  mediaType="application/json",
              )
          ),
          @OA\Response(
              response=401,
              description="Unauthorized"
          ),
          @OA\Response(
              response=400,
              description="Invalid request"
          ),
          @OA\Response(
              response=404,
              description="not found"
          ),
      )
     */

    /*
      login API 
      
      @return \Illuminate\Http\Response 
     */
    public function login(Request $request) {
        try {
            $validator = Validator::make($request->all(), [
                'email' => 'required',
                'password' => 'required',
            ]);
            
            $data = [];
            
            if ($validator->fails()) {
                $errors = $validator->errors();
                foreach ($errors->all() as $field => $validationMessage) {
                    $data['error'][] = $validationMessage;
                }
                $success = [
                    'status' => ResponseHTTP::HTTP_BAD_REQUEST,
                    'data' => $data
                ];
                $message = 'Validation failed!.';
            } else {
                if (Auth::guard()->attempt(['email' => request('email'), 'password' => request('password')])) {
                    $user = Auth::user()->select('id', 'first_name', 'last_name', 'email', 'avatar', 'referral_code')->where('id', Auth::id())->get()->first();

                    $data['token'] = $user->createToken('MyApp')->accessToken;
                    $data['user'] = $user;

                    $success = [
                        'status' => ResponseHTTP::HTTP_OK ,
                        'data' => $data,
                    ];

                    $message = 'Login successfull!.';

                    //store device information
                    UserDevice::addUserDevices($request, $user, config('constants.status.active'));
                } else {
                    $success = [
                        'status' => ResponseHTTP::HTTP_BAD_REQUEST ,
                    ];
                    $message = 'Invalid Email or Password!.';

                }
            }
            
            return $this->APIResponse->respondWithMessageAndPayload($success ,$message);
        } catch (\Exception $e) {
            return $this->APIResponse->handleAndResponseException($e);
        }
    }
}
?>
  • To generate the swagger documentation file just run php artisan l5-swagger: generate command.
  • The generated swagger documentation can be access via entering ting /documentation prefix in your project.
  • Example:
http://<project name>/documentation
  • The generated documentation can look like this.

Before we could conclude, let’s have an expeditious check over the features of the swagger tool.

The most interesting feature of this tool is that it uses a universal language. This feature makes it the best option because it is easily understandable for both developers & non-developers.

The second feature which intensifies its worth is its adjustable feature. This tool can be used for testing and bug fixing.

The third feature which adds worth to it is that one can use the same documentation for accelerating various API-dependent processes.

Hope this blog has helped and brought you closer to the Swagger tool. If you have something to share, then please write it in the comment box given below.