Laravel Swagger Integration: A Comprehensive Step-by-Step Guide

By:

ITS

Category:

Laravel development

Introduction
In today’s software development landscape, building and utilizing APIs is common. However, one critical aspect often overlooked is API documentation, which facilitates collaboration and ensures smooth integration. This guide focuses on integrating Swagger, an open-source framework, with Laravel, a popular PHP framework, to enhance API documentation capabilities. Following the step-by-step instructions, you can seamlessly document and consume RESTful web services in your Laravel projects using Laravel Swagger. By the end of this guide, you will have the knowledge and skills to effectively leverage Swagger, significantly improving the documentation process for your Laravel projects.

What is Swagger?

Swagger is a powerful software framework that assists developers in creating, documenting, and utilizing RESTful web services. It offers a range of tools that enable the creation of API documentation that is easily accessible and understandable for developers. By leveraging the OpenAPI specification, Swagger automatically generates interactive API documentation, making it simple for developers to explore and experiment with various API endpoints and parameters.

Benefits of Integrating Laravel with Swagger

Integrating Laravel with Swagger brings numerous benefits to your API development process, including standardized and comprehensive Laravel API documentation with Swagger. Here are the key advantages of using Swagger Laravel integration.

  • Standardized and Comprehensive API Documentation
    Swagger provides a standardized format for documenting your Laravel APIs, ensuring consistency and clarity. It allows you to document endpoints, parameters, response models and create comprehensive and easily understandable API documentation.
  • Automated Documentation Generation
    Integration Laravel with Swagger API documentation can be automatically generated from your codebase. It eliminates manual documentation maintenance, saving time and effort while ensuring the documentation remains up-to-date as your code evolves.
  • Enhanced Collaboration
    Swagger is a common language for discussing API functionalities among developers, testers, and stakeholders. Providing a clear and structured documentation format improves collaboration and reduces errors with effective communication.
  • Simplified API Testing
    Laravel with Swagger integration includes Swagger UI, a powerful tool for testing and validating APIs.You can directly interreact with your APIs from the documentation, making it easier to validate endpoints, test responses, and ensure API reliability.
  • Interactive Documentation and API Exploration
    Swagger generates interactive documentation allowing developers and consumers to explore and interact with APIs. This includes the ability to test endpoints, experiment with different parameters, and view example requests and responsesNow that we have learned the benefits of this integration, let’s move on to the requirements and setup for integrating Swagger with Laravel.

Requirements and Setup for Laravel Swagger

For Laravel Swagger Integration and utilization of its API documentation capabilities, you will need to make sure to have the following requirements and setup in place
  • Laravel Framework: First, Ensure you have Laravel installed on your system. Laravel Swagger is a package that integrates with Laravel to generate API documentation using the Swagger/OpenAPI specification.
  • Composer: Composer is a useful tool for managing dependencies in PHP projects. It simplifies the process of including external libraries or packages in your application. To utilize Composer, you must have it installed on your system.
  • You can download and install Composer from the official website (https://getcomposer.org).

Step-by-Step Guide for Laravel Swagger Integration

To install Laravel Swagger and enable Bearer token authentication for login, follow these steps after meeting the requirements.

1. Create a new Laravel project or navigate to your existing Laravel project.
2. Open your command prompt or terminal and navigate to the main directory of your Laravel Projects using the suitable commands.
3. To implement Laravel Swagger with Bearer token authentication for login, you can follow these step-by-step instructions:

Step 1: Install Required Packages

Install the `darkaonline/l5-swagger` package and the `tymon/jwt-auth` package using Composer by running the following command in the terminal:

composer require darkaonline/l5-swagger tymon/jwt-auth

Step 2: Configure JWT Authentication

After installing the `tymon/jwt-auth` package, publish the configuration file by running the following command in the terminal which will create a file `config/jwt.php`.

php artisan vendor:publish –provider=”Tymon\JWTAuth\Providers\LaravelServiceProvider”

Next we need to create JWT secret key by running the following command:

php artisan jwt:secret

Step 3: Configure Swagger

We can publish the configuration file for `darkaonline/l5-swagger` by running the following command:

php artisan vendor:publish –provider “L5Swagger\L5SwaggerServiceProvider”

Step 4: Implement User Registration Logic

Open/Add the UserController and add the register method to handle user registration. Here’s an example:

/**
* @OA\Post(
* path=”/api/register”,
* summary=”Register a new user”,
* @OA\Parameter(
* name=”name”,
* in=”query”,
* description=”User’s name”,
* required=true,
* @OA\Schema(type=”string”)
* ),
* @OA\Parameter(
* name=”email”,
* in=”query”,
* description=”User’s email”,
* required=true,
* @OA\Schema(type=”string”)
* ),
* @OA\Parameter(
* name=”password”,
* in=”query”,
* description=”User’s password”,
* required=true,
* @OA\Schema(type=”string”)
* ),
* @OA\Response(response=”201″, description=”User registered successfully”),
* @OA\Response(response=”422″, description=”Validation errors”)
* )
*/
public function register(Request $request)
{
$validatedData = $request->validate([
‘name’ => ‘required|string|max:255’,
’email’ => ‘required|string|email|unique:users|max:255’,
‘password’ => ‘required|string|min:8’,
]);

$user = User::create([
‘name’ => $validatedData[‘name’],
’email’ => $validatedData[’email’],
‘password’ => Hash::make($validatedData[‘password’]),
]);

return response()->json([‘message’ => ‘User registered successfully’], 201);
}

Step 5: Create Login Controller

Create a LoginController to handle the login logic with following command:

php artisan make:controller LoginController

Step 6: Implement Login Logic

/**
* @OA\Post(
* path=”/api/login”,
* summary=”Authenticate user and generate JWT token”,
* @OA\Parameter(
* name=”email”,
* in=”query”,
* description=”User’s email”,
* required=true,
* @OA\Schema(type=”string”)
* ),
* @OA\Parameter(
* name=”password”,
* in=”query”,
* description=”User’s password”,
* required=true,
* @OA\Schema(type=”string”)
* ),
* @OA\Response(response=”200″, description=”Login successful”),
* @OA\Response(response=”401″, description=”Invalid credentials”)
* )
*/
public function login(Request $request)
{
$credentials = $request->only(’email’, ‘password’);
if (Auth::attempt($credentials)) {
$token = Auth::user()->createToken(‘api_token’)->plainTextToken;
return response()->json([‘token’ => $token], 200);
}
return response()->json([‘error’ => ‘Invalid credentials’], 401);
}

Step 7: Implement Logged In User Details

Open the UserController.php file and add the following code to fetch the logged-in user details:

/**
* @OA\Get(
* path=”/api/user”,
* summary=”Get logged-in user details”,
* @OA\Response(response=”200″, description=”Success”),
* security={{“bearerAuth”:{}}}
* )
*/
public function getUserDetails(Request $request)
{
$user = $request->user();
return response()->json([‘user’ => $user], 200);
}

Step 8: Create Routes

Route::post(‘/register’, ‘App\Http\Controllers\UserController@register’);
Route::post(‘/login’, ‘App\Http\Controllers\LoginController@login’);
Route::get(‘/user’, ‘App\Http\Controllers\UserController@getUserDetails’)->middleware(‘auth:sanctum’);

Step 9: Generate Swagger

You can add this to app/Http/Controllers/Controller.php:

/**
* @OA\Info(
* title=”Swagger with Laravel”,
* version=”1.0.0″,
* )
* @OA\SecurityScheme(
* type=”http”,
* securityScheme=”bearerAuth”,
* scheme=”bearer”,
* bearerFormat=”JWT”
* )

*/

Then Generate the Swagger documentation by running the following command:

php artisan l5-swagger:generate

Step 10: View Swagger Documentation

To view the Swagger documentation in your web browser simply navigate to the following URL: http://your-app-url/api/documentation

Upon accessing the Swagger UI, you will be able to see the available GET/POST endpoints along with their respective required parameters. Additionally, you will find more information about the possible responses that can be managed from the Swagger annotations within the controller’s file.

You will notice an “Authorize” button or input field within the Swagger UI. A modal or input field will appear by clicking this button, allowing you to manually enter the bearer token required for accessing authenticated APIs.

For more details, you can visit the GitHub Repository

Conclusion

Laravel Swagger Integration simplifies designing, documenting, and consuming APIs. It operates an automated way to generate interactive API documentation based on the OpenAPI specification. Following the step-by-step guide, you can easily integrate Swagger into your Laravel projects. Consider partnering with a Laravel development company such as Inspire Techno Solution to simplify the design, documentation, and utilization of your laravel based web applications.

We are trusted by over 650+ clients.
Join them by using our services and grow your business.

Get Started

SiteLogo
“At Inspire Techno Solution , our mission is to continuously innovate the best ways to train the next generation of developers and to transform the way tech education is delivered.”

Find a Career with us

Related Blogs

Real-time Chat App using Laravel Pusher and Jquery | Inspire Techno Solution

Real-time Chat App using Laravel Pusher and Jquery

Pusher is a cloud-based platform enabling developers to quickly create real-time web and mobile applications.
Laravel Octane to Scale your Application in 2024 | Inspire Techno Solution

Laravel Octane to Scale your Application in 2024

Laravel has gained a lot of attention in recent years, though it has been a
Laravel Swagger Integration A Comprehensive Step-by-Step Guide | Inspire Techno Solution

Laravel Swagger Integration: A Comprehensive Step-by-Step Guide

This guide offers a comprehensive and easy-to-follow tutorial on Laravel Swagger Integration. Following the step-by-step