Laravel Swagger Integration: Enhance Your API Structure

APIs are the backbone of modern applications, enabling different systems to communicate and exchange data seamlessly. As API usage grows, so does the need for clear, easy-to-understand API documentation.

Swagger, a powerful open-source tool, simplifies API documentation by generating interactive, user-friendly docs that developers can explore and test. Laravel Swagger integration allows you to create a well-documented, accessible API interface that enhances developer experience and boosts productivity.

In this guide, we’ll see how Laravel development experts set up Swagger in a Laravel project. By the end, you’ll have everything you need to create and maintain intuitive documentation for your Laravel REST APIs.

What is Swagger?

Swagger is a robust framework designed to help developers create, document, and use RESTful APIs more effectively. With Swagger, you can automate the generation of interactive API documentation based on the OpenAPI specification, a widely-adopted standard for describing APIs. This documentation provides a clear and accessible way for developers to explore API endpoints, test requests, and understand parameters—all directly within a web-based interface.

Swagger simplifies the often complex task of documenting APIs, making it easier for developers to understand how to work with them, and for teams to communicate and collaborate more effectively around API functionality.

Here are some benefits of integrating Laravel with Swagger:

  • Clear and Consistent Documentation: Swagger provides a structured format for documenting APIs, making everything easy to read and understand.
  • Automatic Updates: Documentation is automatically generated from your code, so it’s always up-to-date as your API changes.
  • Better Collaboration: Swagger’s documentation format helps developers, testers, and stakeholders communicate easily about API features.
  • Easy Testing: Swagger UI lets you test APIs directly from the documentation, simplifying validation.
  • Interactive Exploration: Developers can explore and interact with APIs in real-time, making it easy to see how endpoints work.

Need help with Laravel Swagger integration?

Steps to Follow for Laravel Swagger Integration

Now that we understand what Swagger is and why it’s beneficial to integrate with Laravel, let’s dive into the setup process.

Below are the steps to configure Swagger with JWT authentication in your Laravel project, ensuring that your API is both secure and well-documented.

Prerequisites

Before starting the integration, ensure the following prerequisites are met:

  • Laravel Installed: Make sure you have a Laravel project set up. You can install Laravel by following the instructions on the official Laravel website.
  • Composer Installed: Composer is required to manage PHP dependencies. If you don’t have it installed, download it from getcomposer.org.
  • L5-Swagger and JWT Auth Packages: You’ll be installing L5-Swagger (for API documentation) and tymon/jwt-auth (for JWT-based authentication) as part of this process. Ensure your project meets the compatibility requirements for these packages.
  • Database Configuration: JWT authentication relies on user data, so set up and configure a database with a users table in your Laravel application. Make sure your .env file has the correct database credentials.
  • Basic Knowledge of REST APIs: Understanding RESTful APIs and basic authentication flows will be helpful for setting up and using JWT with Swagger in Laravel.

Step 1: Installing L5-Swagger and JWT Auth Packages

Install both L5-Swagger for API documentation and tymon/jwt-auth for JWT-based authentication.

Run the following commands:

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

Publish the configuration files for both packages:

php artisan vendor:publish --provider="L5Swagger\L5SwaggerServiceProvider"
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

Step 2: Configuring JWT in Laravel

Generate a secret key for JWT:

php artisan jwt:secret

Open .env and set up the following JWT settings:

JWT_SECRET=your_jwt_secret_key

Update config/auth.php to configure JWT as the default guard for your application:

'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],
'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

Creating an Authentication Controller

Create a controller to manage JWT-based login and logout.

php artisan make:controller AuthController

In AuthController.php, add methods for login and logout functionality:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Tymon\JWTAuth\Facades\JWTAuth;

class AuthController extends Controller
{
    /**
     * @OA\Post(
     *     path="/api/login",
     *     operationId="login",
     *     tags={"Authentication"},
     *     summary="User login",
     *     description="User login and JWT token generation",
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             required={"email","password"},
     *             @OA\Property(property="email", type="string", format="email"),
     *             @OA\Property(property="password", type="string", format="password")
     *         ),
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="Successful login with JWT token",
     *         @OA\JsonContent(
     *             @OA\Property(property="access_token", type="string"),
     *             @OA\Property(property="token_type", type="string"),
     *             @OA\Property(property="expires_in", type="integer")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="Unauthorized"
     *     )
     * )
     */
    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');
        if (!$token = Auth::attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }
        return $this->respondWithToken($token);
    }

    /**
     * @OA\Post(
     *     path="/api/logout",
     *     operationId="logout",
     *     tags={"Logout"},
     *     summary="User logout",
     *     description="User logout and JWT token generation",
     *     @OA\RequestBody(
     *         required=false,
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="Successful logout",
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="Unauthorized"
     *     ),
     *     security={{"bearerAuth":{}}}
     * )
     */
    public function logout()
    {
        Auth::logout();
        return response()->json(['message' => 'Successfully logged out']);
    }

    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => Auth::factory()->getTTL() * 60
        ]);
    }
}

Step 3: Setting Up Swagger with JWT Authentication

Open config/l5-swagger.php and configure Swagger to include JWT in the header for requests:

  • Configure Security Definition:  Add a BearerAuth security definition to make Swagger use JWT tokens in API requests.
'securityDefinitions' => [
    'BearerAuth' => [
        'type' => 'apiKey',
        'description' => 'Enter token in format (Bearer <token>)',
        'name' => 'Authorization',
        'in' => 'header',
    ],
],
  • Set Global Security Requirement: Require JWT for all API endpoints by default.
'security' => [
    [
        'BearerAuth' => []
    ],
],
  • Adjust Middleware: In app/Http/Kernel.php, add jwt.auth to the api middleware group to secure routes using JWT.
'api' => [
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    \Tymon\JWTAuth\Http\Middleware\Authenticate::class,
],
  • Exclude Login Route from JWT: In routes/api.php, use the auth:api middleware to require JWT for other routes but exclude /login.
Route::group(['middleware' => 'auth:api'], function() {
    Route::post('/logout', [AuthController::class, 'logout']);
    // Add other secured routes here
});
  • Add Implementation to User Model file (implements JWTSubject) and below methods.

Example: class User extends Authenticatable implements JWTSubject

Add the required methods by the JWTSubject interface:

public function getJWTIdentifier()
{
    return $this->getKey();
}

public function getJWTCustomClaims()
{
    return [];
}

Step 4: Documenting API Endpoints with Swagger Annotations

To document endpoints with Swagger annotations, use @OA tags in your controller methods. For secured endpoints, add security to each annotation.

Add Info and Security Scheme in the app/Http/Controllers/Controller.php file.

Example:

/**
* @OA\Info(
*     title="Swagger with Laravel",
*     version="1.0.0",
* )
* @OA\SecurityScheme(
*     type="http",
*     securityScheme="bearerAuth",
*     scheme="bearer",
*     bearerFormat="JWT"
* )
*/
class Controller extends BaseController
{
    use AuthorizesRequests, ValidatesRequests;
}

Create a UserController and get the list.

php artisan make:controller UserController

Paste the following code in UserController:

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * @OA\Get(
     *     path="/api/users",
     *     operationId="getUsers",
     *     tags={"Users"},
     *     summary="Get list of users",
     *     description="Returns list of users",
     *     @OA\Response(
     *         response=200,
     *         description="Successful operation",
     *         @OA\JsonContent(
     *             type="array",
     *             @OA\Items(ref="#/components/schemas/User")
     *         ),
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="Unauthorized",
     *     ),
     *     @OA\Response(
     *         response=404,
     *         description="Resource Not Found",
     *     ),
     *     security={{"bearerAuth":{}}}
     * )
     */
    public function getUsers() {
        $users = User::all();
        return response()->json($users);
    }
}

Modify the api.php routes:

Route::group(['middleware' => 'auth:api'], function() {
    Route::post('/logout', [AuthController::class, 'logout']);
    Route::get('/users', [UserController::class, 'getUsers']);
});
Route::post('/login', [AuthController::class, 'login']);

Step 5: Testing JWT-Secure API with Swagger UI

After setting up and documenting the endpoints, generate the Swagger documentation JSON file:

php artisan l5-swagger:generate

Accessing Swagger UI and Authenticating

Run the application server:

php artisan serve

Visit Swagger UI at http://localhost:8000/api/documentation.

Authenticate Using JWT:

  • Go to the /login endpoint in Swagger, input email and password, and execute the request.
  • Copy the JWT token from the response.
  • On the top right, click Authorize and paste the token in the format Bearer <your_token>.

Now, Swagger will use this token to authenticate all subsequent API requests.

Now, Access the Users route and click Try It then click Execute. Then it will get the response:

[
  {
    "id": 1,
    "name": "John Doe",
    "email": "johndoe@example.com",
    "email_verified_at": null,
    "created_at": "2024-10-29T11:43:20.000000Z",
    "updated_at": "2024-10-29T11:43:20.000000Z"
  }
]

If you try to access the /api/users endpoint without authentication, you will see an error message indicating unauthorized access:

{
  "message": "Unauthenticated."
}

Testing Secured Endpoints

Access any secured endpoint to see Swagger automatically include the JWT token, allowing access to resources.

Take your project to the next level with expert Laravel development

FAQs on Laravel Swagger Integration

What is Swagger in Laravel?
Swagger in Laravel is a tool that automatically generates interactive documentation for APIs, making it easier for developers to explore and understand API endpoints.
Is Swagger easy to use?
Yes, Swagger is user-friendly and offers interactive, auto-generated documentation, allowing developers to easily test and explore APIs.
Can Swagger generate documentation?
Yes, Swagger generates documentation automatically from your code, providing clear, up-to-date API documentation with minimal manual effort.

Conclusion

With Swagger integrated into your Laravel project, your API documentation becomes interactive, clear, and easy to use. Adding JWT authentication takes it a step further by securing access, making sure only authorized users can interact with your endpoints.

By following these steps, you’ve set up a system that’s both developer-friendly and secure. Now, you can enjoy smoother collaboration and more efficient testing, all while keeping your API well-documented and reliable.

If you need professional assistance in creating powerful Laravel APIs, hire experienced Laravel developers.

author
Mayur Upadhyay is a tech professional with expertise in Shopify, WordPress, Drupal, Frameworks, jQuery, and more. With a proven track record in web development and eCommerce development.

Leave a comment