Frameworks

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.

Top 6 Cross-Platform Mobile Application Frameworks

Mobile industry and mobile app development industry both are at the peak of their advancement. The new additions in technology not only forces us to say ‘wow’ but also captivates us in it as well. But the human kinds are just trapped into it without knowing much technicalities.

So, before you join this mobile app development section, get some education on types of mobile app development tools.

Join me to check the Top 6 cross-platform mobile application frameworks.

1) Appcelerator:

Appcelerator introduces pace in the app development process. It permits developers to create apps with fewer lines of code.

This tool supports Android, iOS, browser-based HTML5 applications and windows. This tool can be employed for both native app and cross-platform application development. This tool backs the development of an app when the application reacts with a web service.

Why is it Popular?

  • It devoid ” write once, run everywhere” concept.
  • It holds many platform-specific API’s, user interface and features.
  • Developers can create mobile applications without mastering the coding of Android and iOS platforms individually.

2) Xamarin:

If you have planned for having a native app for your enterprise, then Xamarin stands as a better option. It utilizes the business logic layers and data access across platforms. This aspect turns beneficial when large amounts of local data, image recognition and offline mode are required to be implemented. Though it is built on the C# programming language, still it can run on the .NET common language infrastructure. This app is employed for developing apps for Windows, iOS & Android platforms.

Why So Popular?

  • It is a mono framework that permits communication with the API of mobile devices.
  • It empowers mobile app developers to create a robust and scalable application using its QA & testing features.
  • It restrains bug and offers a faster time to market.
  • It requires less coding; hence, a single test approves the coding of both platforms.
  • It generates an opportunity for the developers to opt for the best from a host of free & paid components.
  • Xamarin Component Store consists of third-party web services, UI controls & cross-platform libraries.
  • It’s easy to integrate backends like Salesforce, Microsoft Azure and many others.

3) PhoneGap:

PhoneGap is listed in the cross-platform app development section. It permits the development of various mobile app with minimum efforts. It even allows developers to stretch the functionality of the app with the support of plug-in architecture.

Why Choose PhoneGap?

  • Open Source License, free framework for mobile app development.
  • It is a robust tool for creating an app, which just requires general information or skills.
  • Holds a large community of developers for accumulating new codes and modules to enhance the quality of the app.
  • Can be used for developing a single app that can run on all types of mobile devices.
  • This tool functions on CSS3, JavaScript and HTML5.
  • Integrated with several libraries to save time and enhance functionality.
  • Applications developed using this tool works smoothly over multiple platforms.
  • The backend system improves the pace of development of mobile apps.
  • This tool even taps into the hardware (accelerometer, geo-location, camera, etc.) of the devices.

4) Sencha:

Sencha is an MVC-based JavaScript framework that permits developers to use it through a fingertip’s touch, ultimately increasing the responsiveness of the app.

This platform is mentioned for rapid mobile app development. One can develop a native app fitting with the latest versions of Android, iOS and Blackberry, then this platform will be the best choice. Coding can be done in HTML5 and then can be used for iOS and Android application.

Why is Sencha Used?

  • It holds a good number to supporting community.
  • It provides end-to-end testing solution for Ext JS.
  • It nullifies the dependence on multiple versions and libraries.
  • It has single coding which is valid for all components.
  • Consist of 115 fully backed components that are open to integration with a variety of frameworks such as FOSS, Angular etc.
  • It is rich with commercially backed UI widgets for toolbars, menus and lists.

5) Ionic:

If you are having a mindset to develop a hybrid mobile application, then switching to this HTML5 based mobile development framework will hopefully end your search. Ionic framework is an open-source SDK that provides web technologies like HTML5, SASS and CSS for creating hybrid mobile apps. It accompanies several default CSS components and JavaScript components to provide a platform for making a mobile application.

Why Choose Ionic?

  • It does not need the approval of MDM or app store to fix bugs or to change content or update the app.
  • It has an ability to automate workflow from native binary to QA.
  • One can create Native app binaries in the cloud with an Ionic package.
  • It has a central shared dashboard displaying ongoing activity feeds.
  • It provides tools and services to develop highly interactive apps.
  • It offers industry-specific defaults and pre-built work-flows to automate development work.
  • It is built on top of the AngularJS, making the application development process easy.

6. Framework7:

Framework7 is designed to create a native iPhone application. It has also started backing for Android apps. It has a limitation; it is iOS focused, so not compatible with all the platforms.

Why go with Framework 7?

  • It has a specific UI elements animation, touch interaction and visualization.
  • It functions in complex-free HTML layout connected with JS files and CSS Framework.
  • It offers a variety of ready-made- UI widgets and elements like media lists, form elements, list views, popups etc.
  • Capable of introducing customized styles in the applications.
  • It backs iOS swipe back action.
  • Provides better video ad experience with the support of VI.

Ending my words:

It is never easy to conclude on a particular option when you are catered for multiple options. One can only flow in the right direction if knows the need and requirement of applications and aware of the functionalities of different tools.

Every single step in the process affects the outcomes so, necessarily you need to seize the knowledge and apply the same before concluding to a particular option.

‘Your every step can change your Future’ Period.

Hire Laravel Developers Who Surpass The 5 Common Mistakes

We are breathing in the era which is predominated by technologies. The domination over each and every sector including business has fostered the demand for more and more advancement in the field. Today, developers are engaged in the utilization of PHP. The excessive success received by the use of the PHP framework has approved its importance and assures for its future purposes. Laravel is considered as the most updated PHP framework that can incorporate the applications of programming codes and syntax but in an unusual way.

Laravel has been overlapping others in terms of features, scalability and performance. It stands as one of the most fancied PHP frameworks. The ability to simplify everyday tasks like routing, authentication, catching and sessions have expanded the utility of Laravel. It provides leverages to developers to draft their infrastructure, individually designed for their application.

However, the plight is to find a reliable Laravel developer that has not been introduced in the list of mistake does— one who holds the good grip in the programming.

Let’s check out what are the most mistakes done by Laravel developers:

1. Laravel documentation suggests that “Form:: close” should be closed as “Form:: close!” tag but most of the programmers forget and later spend much time in finding the error.

2. Still, most of the developers are in the habit of using params for validation of user input, though the best way to validate is via “Form Request” feature of Laravel.

3. Most of the Laravel developers skip the use of migration feature to avoid time consumption. They build new database tables and add new fields to database tables. However, it’s a completely unacceptable practice of professional developers. They should use the available database migration for modification or addition of new things in the database.

4. Routing is considered as the soul of any Laravel based application, but most of the professionals using the same are prone to mistakes in drafting the routing logic. It happens at times that they don’t remember to add a new route and get stuck for finding the reason behind Error 404. Sometimes they write they “get” rule in place of “post” and mess up searching the error in coding.

5. Laravel is treasured with one of the most potent form libraries in the open source world. The most common mistake done by developers is that usually miss adding CSRF hidden field token in the program. CSRF token shields the application from cross-site request forgery attack, but unfortunately, most of the developers ignore it because of lack of knowledge.

Getting reliable programmers can be a tough task to accomplish. But to sort out your problem is our ambition. Prompt Softech consist of professionals’ team who can help you for developing Laravel based programs to scale you with the rest.

Please share your experience and views in the comment box.