Swagger for Laravel

Integration of Swagger in Laravel Application

Now here step by step to install and configure the swagger api for laravel documentations.

Step 1: Install Swagger open Api

Now install the Swagger according to the Laravel version that you have installed. For more information visit DarkaOnLine/L5-Swagger

composer require "darkaonline/l5-swagger"

Step 2: Publish Swagger’s configuration

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

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

Step 2.1: Add Swagger Annotation to Controller.php

  • At first, we need to add few Swagger Annotations in Controller.php which is located at app/Http/Controllers/Controller.php
<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    /**
     * @OA\Info(
     *      version="1.0.0",
     *      title="Integration Swagger in Laravel with Passport Auth Documentation",
     *      description="Implementation of Swagger with in Laravel",
     *      @OA\Contact(
     *          email="admin@admin.com"
     *      ),
     *      @OA\License(
     *          name="Apache 2.0",
     *          url="http://www.apache.org/licenses/LICENSE-2.0.html"
     *      )
     * )
     *
     * @OA\Server(
     *      url=L5_SWAGGER_CONST_HOST,
     *      description="Demo API Server"
     * )

     *
     *
     */
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

  • Now create two controller named ApiController and AuthController inside app/Http/Controllers/Api/V1 directory. In Laravel controller can be created via the following the command

    php artisan make:controller Api/V1/ApiController

    php artisan make:controller Api/V1/AuthController

 

Step 3: Enable passport authentication

Enable passport authentication we need to uncomment Open API 3.0 support in security array of config/l5-swagger.php file

'security' => [

        // Open API 3.0 support
        'passport' => [ // Unique name of security
            'type' => 'oauth2', // The type of the security scheme. Valid values are "basic", "apiKey" or "oauth2".
            'description' => 'Laravel passport oauth2 security.',
            'in' => 'header',
            'scheme' => 'https',
            'flows' => [
                "password" => [
                    "authorizationUrl" => config('app.url') . '/oauth/authorize',
                    "tokenUrl" => config('app.url') . '/oauth/token',
                    "refreshUrl" => config('app.url') . '/token/refresh',
                    "scopes" => []
                ],
            ],
        ],
    ],

Step 4: Update Routes

Now, we need to create routes for API just update the below routes.

routes\api.php

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::post('login', 'Api\AuthController@login');
Route::post('register', 'Api\AuthController@register');

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

 

Step 5: Create Controller

Now create a new controller AuthController using the following the command.

php artisan make:controller Api/AuthController

After genrating the controller update the below code on it.

app\Http\Controllers\Api\AuthController.php

<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Hash;
use App\User;

class AuthController extends Controller
{
      /**
        * @OA\Post(
        * path="/api/register",
        * operationId="Register",
        * tags={"Register"},
        * summary="User Register",
        * description="User Register here",
        *     @OA\RequestBody(
        *         @OA\JsonContent(),
        *         @OA\MediaType(
        *            mediaType="multipart/form-data",
        *            @OA\Schema(
        *               type="object",
        *               required={"name","email", "password", "password_confirmation"},
        *               @OA\Property(property="name", type="text"),
        *               @OA\Property(property="email", type="text"),
        *               @OA\Property(property="password", type="password"),
        *               @OA\Property(property="password_confirmation", type="password")
        *            ),
        *        ),
        *    ),
        *      @OA\Response(
        *          response=201,
        *          description="Register Successfully",
        *          @OA\JsonContent()
        *       ),
        *      @OA\Response(
        *          response=200,
        *          description="Register Successfully",
        *          @OA\JsonContent()
        *       ),
        *      @OA\Response(
        *          response=422,
        *          description="Unprocessable Entity",
        *          @OA\JsonContent()
        *       ),
        *      @OA\Response(response=400, description="Bad request"),
        *      @OA\Response(response=404, description="Resource Not Found"),
        * )
        */
      public function register(Request $request)
      {
          $validated = $request->validate([
              'name' => 'required',
              'email' => 'required|email|unique:users',
              'password' => 'required|confirmed',
              'mobile_number' => 'required',
          ]);

          $data = $request->all();
          $data['password'] = Hash::make($data['password']);
          $user = User::create($data);
          $success['token'] =  $user->createToken('authToken')->accessToken;
          $success['name'] =  $user->name;
          return response()->json(['success' => $success]);
      }

      /**
        * @OA\Post(
        * path="/api/login",
        * operationId="authLogin",
        * tags={"Login"},
        * summary="User Login",
        * description="Login User Here",
        *     @OA\RequestBody(
        *         @OA\JsonContent(),
        *         @OA\MediaType(
        *            mediaType="multipart/form-data",
        *            @OA\Schema(
        *               type="object",
        *               required={"email", "password"},
        *               @OA\Property(property="email", type="email"),
        *               @OA\Property(property="password", type="password")
        *            ),
        *        ),
        *    ),
        *      @OA\Response(
        *          response=201,
        *          description="Login Successfully",
        *          @OA\JsonContent()
        *       ),
        *      @OA\Response(
        *          response=200,
        *          description="Login Successfully",
        *          @OA\JsonContent()
        *       ),
        *      @OA\Response(
        *          response=422,
        *          description="Unprocessable Entity",
        *          @OA\JsonContent()
        *       ),
        *      @OA\Response(response=400, description="Bad request"),
        *      @OA\Response(response=404, description="Resource Not Found"),
        * )
        */
      public function login(Request $request)
      {
          $validator = $request->validate([
              'email' => 'email|required',
              'password' => 'required'
          ]);

          if (!auth()->attempt($validator)) {
              return response()->json(['error' => 'Unauthorised'], 401);
          } else {
              $success['token'] = auth()->user()->createToken('authToken')->accessToken;
              $success['user'] = auth()->user();
              return response()->json(['success' => $success])->setStatusCode(200);
          }
      }
}

Step 6: Generate Swagger

To generate the swagger documentation file just run php artisan l5-swagger: generate command.

php artisan l5-swagger:generate

More then times when you generate the swagger It will return an error

Required @OA\Info() not found

That means that you have to create that notation first. So let’s add it. I prefer creating Abstract controller for an API, but you can add this to app/Http/Controllers/Controller.php

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

/**
 * @OA\Info(
 *    title="Your super  ApplicationAPI",
 *    version="1.0.0",
 * )
 */
class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

Step 7: Open the Documentation

http://laravel-project.co/api/documentation

Note: we are using body parameter for creating api documentation in laravel with swagger open api. If you want to add query paramter then add some like below code.

Api Docuentation using Query Parameters

Below code for user register..

/**
     * @OA\Post(
     ** path="/api/user-register",
     *   tags={"Register"},
     *   summary="Register",
     *   operationId="register",
     *
     *  @OA\Parameter(
     *      name="name",
     *      in="query",
     *      required=true,
     *      @OA\Schema(
     *           type="string"
     *      )
     *   ),
     *  @OA\Parameter(
     *      name="email",
     *      in="query",
     *      required=true,
     *      @OA\Schema(
     *           type="string"
     *      )
     *   ),
     *   @OA\Parameter(
     *       name="mobile_number",
     *      in="query",
     *      required=true,
     *      @OA\Schema(
     *           type="integer"
     *      )
     *   ),
     *   @OA\Parameter(
     *      name="password",
     *      in="query",
     *      required=true,
     *      @OA\Schema(
     *           type="string"
     *      )
     *   ),
     *      @OA\Parameter(
     *      name="password_confirmation",
     *      in="query",
     *      required=true,
     *      @OA\Schema(
     *           type="string"
     *      )
     *   ),
     *   @OA\Response(
     *      response=201,
     *       description="Success",
     *      @OA\MediaType(
     *           mediaType="application/json",
     *      )
     *   ),
     *   @OA\Response(
     *      response=401,
     *       description="Unauthenticated"
     *   ),
     *   @OA\Response(
     *      response=400,
     *      description="Bad Request"
     *   ),
     *   @OA\Response(
     *      response=404,
     *      description="not found"
     *   ),
     *      @OA\Response(
     *          response=403,
     *          description="Forbidden"
     *      )
     *)
     **/

 

 

Reference: Laravel API Documentation with OpenAPI/Swagger – Quick Admin Panel

Reference2: Laravel API Documentation with Swagger Open Api and Passport (codingdriver.com)

Leave a Reply

Your email address will not be published.