ITS
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.
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.
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:
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
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”
php artisan jwt:secret
We can publish the configuration file for `darkaonline/l5-swagger` by running the following command:
php artisan vendor:publish –provider “L5Swagger\L5SwaggerServiceProvider”
/**
* @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);
}
Create a LoginController to handle the login logic with following command:
php artisan make:controller LoginController
/**
* @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);
}
/**
* @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);
}
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’);
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”
* )
*/
php artisan l5-swagger:generate
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
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.