Framework

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.

How should I Select a Technology Stack for my Startup?

Switching to one-another technology has not just become a trend but also demand of the time. The advancement in technology has triggered the use and demand in parallel. The mobile app development industry is the most influenced of all. The changes in the programs and the addition of latest technologies has explored a better way of utilising the already existing one.

There has been plight between developers for introducing either Angular or React in their projects until a new JavaScript library became part of the family.

Vue.js is a most demanded JavaScript library used for creating web interfaces. When it is joined with other tools, it acts as “framework”.

Vue.js is not new; it has been present since 2013, but last year it occupied the market with maximum downloads.

Whereas Angular is an open-source framework used for building dynamic websites and applications. It comes under the umbrella of MEAN stack and allows a wide range of code editors.

Vue.Js was developed with an intention to overcome the issues bulging with Angular Framework. This framework provides an easy way to develop simple page web application.

Why Choose Angular Development Framework?

It has been considered a perfect JS framework as it:

  • Server-Side Rendering: Angular JS Framework is very SEO-friendly. It provides good Server-Side Rendering (SSR) features to enhance the page activity on the client side.
  • Separation of Concerns: Angular supports MVC model which enables easy separation of concerns and permits cleaner faster development.
  • Deep linking Module: This format offers an extended linking module for the development of single page app. It explains about the working of Ajax and benefits of adding it into the app project.
  • Tools and Filters: It even permits an easy blend of various tools and filters into the development environment. This grants high-speed front-end experience.
  • Testing and Maintenance: The Angular Framework supports refactoring and debugging that helps developers in the maintenance and testing process. It even permits to check the complete project with a single testing tool like Karma, Protractor and Jasmine. This limits the hassle and grants expert results.
  • Update Scope with CLI: Angular CLI is easy to utilise and install. It provides mobility experts with easy commands and offers effective testing tools. It is even backed by several engineers and platforms which enables it to update all the app component.

Why opt for Vue.js?

  • Memory Consumption: Memory consumption has been an issue but this particular feature of Vue.js attracts users. Development of an App using Vue.js framework can make it less memory consuming. This framework offers good features in low memory consumption.
  • Learning-Not an Issue: It has represented itself as one of most like JavaScript framework which has simple CLI but offers advanced and huge documentation. These features lure users and set it as a first priority.
  • Readability: This framework is user-friendly because of being written in simple JavaScript with clean codes. The simple codes are easy to read and forwards its use.
  • Small Size File: The size of the app developed on this platform is normally small and can be easily downloaded.
  • Integration Scope: Vue.Js supports a simple and easy integration process. So it allures developers for developing both single page application from scratch and integrated advanced component in already functioning program.
  • Server-Side Rendering: This platform also offers Server-side rendering option to enhance the working speed of pages on the client’s end. It incorporates a better result and good experience.

When to Choose Which- Vue.js vs Angular?

1) Popularity:
The popularity of Vue.Js has been emerging with the vigorous speed in last year. The percentage of untouched people has shrunk from 5 to 1 %, reflecting the occupancy.

But GitHub disclosed that though Vue has achieved good ratings but fails in commits and contributors.

2) Learning Curve:
In Vue, you really not to worry about getting proficiency at concepts like MVC and TypeScript. Vue.Js supports inbuilt app templates and provides customization option. Since it is designed by combining Angular and React- it’s not hard to bring Angular or React-based mobility solution on Vue.js platform.

3) Architecture:
Architecture influences the comparison as it holds importance in JavaScript Framework. Angular supports MVVM (Model-View-ViewModel) and MVC (Model-View-Controller) for designing the web application and dynamic websites.

Vue focuses on ViewModel and represents limited data. This Characteristic makes Vue.Js weaker to Angular.

4) Complexity:
Vue.js is designed quite later so it’s much easier and simpler than any other platform. So no hotchpotch and trouble while using it.

5) Scalability:
When you have to provide remark on the basis of scalability then Angular leaves the Vue far behind. Angular consist of proper modular development structure whereas Vue just holds template-based syntax. Thus it limits the reusability of code in large-size apps.

6) TypeScript Support:
Angular is extremely integrated with TypeScript that is an upgraded version of JavaScript. If one has to use Angular then needs to learn TypeScript. In the case of Vue.js, JavaScript is still writing code. However, it provides an option to Vue.js developers to easily collaborate TypeScript Features in it.

7) App Size and Loading Time:
Though Angular have latest traits like tree-shaking and AOT compilation to minimise the size of an App but it still fails in comparison to Vue. Apps developed using Vue Platform are light in size so can be easily downloaded.

8) Flexibility:
The next feature that determines the usefulness of any JS framework is Flexibility. It supports a variety of build systems without affecting app structure.

9) App Performance:
The use of the Document Object Model (DOM) determines the performance level. Angular Uses real DOM due to which complete web or app pages faces changes even if a single component is changed. Vue wins this battle as it does not affect the entire page and assures modification in the components required.

10) Data Binding:
Vue.js supports the one-way data binding concept that restricts the alteration of UI element without changing the model state. On the other side, Angular offers two-way binding concept which makes the modification easy in UI element without disturbing the model state and vice-versa.

11) Ease of Deployment:
Though development to deployment is easy in Angular app development still it requires to focus on writing a “good” Angular application. If not focused, it will become tough to enjoy the advantage of Ahead-of-Time compilation (AoT), lazy loading, module system and many other peculiarities.

Vue offers full support and enables to build a complex setup or import anything into the app environment which can respond in optimizing the code. Thus providing an easy compilation process.

12) Testing:
Angular has proved itself better in the aspect of testing as it provides multiple tools like Karma and Jasmine, enabling the test of development code individually. Vue has been tough in this purpose for developers. It’s not easy for developers to provide bug-free applications using Vue.js.

13) Mobility Solutions:
Angular is used for developing real-time apps like chat application and instant messaging. On the other hand, Vue.js is fit for creating lightweight single page application with an accessible interface.

14) Community Support:
Vue.js have less number of commits and contributors though it has a good number of watchers forks and stars on GitHub. In fact, the migration helper tool of Vue.js is not considered very influencing as it has no roadmap which could help in versioning and planning.

Angular is supported by Google and run by an open source community.

Certainly, this feature of Angular makes it a winner in term of Community support.

Thus, we are now capable of differentiating between the above two platforms. Its all up to you now to choose the right framework as per the need and requirements.