Swagger, now known as OpenAPI, is a powerful tool to describe your API's endpoints, request parameters, responses, and more in a standardized format. It helps both frontend developers and external users understand how to interact with your API.
In this article, we'll walk through the process of integrating Swagger/OpenAPI documentation into a Laravel API using the l5-swagger
package.
Step 1: Install the l5-swagger
Package
To get started with Swagger documentation in your Laravel application, you first need to install the l5-swagger
package. This package makes it easy to generate and display OpenAPI documentation.
Run the following command to install l5-swagger
via Composer:
composer require darkaonline/l5-swagger
Step 2: Publish the Configuration File
After installing the package, publish the configuration file for l5-swagger
. This allows you to customize the settings for the Swagger UI and the OpenAPI documentation.
Use this command:
php artisan vendor:publish --provider="L5Swagger\L5SwaggerServiceProvider"
This will create the config/l5-swagger.php
configuration file, where you can tweak the settings for Swagger.
Step 3: Set Up OpenAPI Annotations
OpenAPI documentation is built using annotations in the code. These annotations describe your API’s endpoints, input parameters, output responses, and more.
The primary annotation is @OA\Info
, which contains the metadata about your API, such as its title, version, and description.
Where to Place OpenAPI Annotations
You can place OpenAPI annotations in the following locations:
- Controller: Directly within the controller that defines your routes.
- Separate Documentation Class: A dedicated file or class that contains all of your OpenAPI annotations.
Example: Adding @OA\Info
in a Controller
Here's how you can add @OA\Info
in a controller. For this example, we will add it to an ApiController
:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
/**
* @OA\Info(
* title="HookBox API",
* version="1.0.0",
* description="This is the API documentation for the HookBox API. It handles webhook requests and responses, allowing users to generate and display data dynamically."
* )
*/
class ApiController extends Controller
{
// Your controller methods here
}
Example: Adding @OA\Info
in a Separate Documentation Class
If you want to keep your OpenAPI metadata separate from your controllers, you can create a new class specifically for OpenAPI annotations.
Create a file like app/Swagger/ApiDocumentation.php
:
<?php
namespace App\Swagger;
/**
* @OA\Info(
* title="HookBox API",
* version="1.0.0",
* description="This is the API documentation for the HookBox API. It handles webhook requests and responses, allowing users to generate and display data dynamically."
* )
*/
class ApiDocumentation
{
// Other Swagger-related annotations if needed
}
Other Useful OpenAPI Annotations
Here are some other useful annotations you can add in your controllers or routes:
-
@OA\PathItem
: Defines the API paths. -
@OA\Operation
: Describes individual operations (endpoints) for your API. -
@OA\Parameter
: Describes input parameters for your endpoints. -
@OA\Response
: Describes the response structure for an endpoint.
Example of defining an endpoint with annotations:
/**
* @OA\Get(
* path="/api/endpoint",
* summary="Fetch data",
* @OA\Response(
* response=200,
* description="Success",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="data", type="string", example="Sample data")
* )
* )
* )
*/
public function getData()
{
return response()->json(['data' => 'Sample data']);
}
Step 4: Generate Swagger Documentation
After you've added the annotations in your code, it's time to generate the Swagger documentation.
Run the following artisan command:
php artisan l5-swagger:generate
This command will scan your controllers for OpenAPI annotations, generate the JSON file that describes your API, and store it in the storage/api-docs
directory by default.
Step 5: Display Swagger UI
Once the documentation is generated, you can display it via a Swagger UI in your browser. The l5-swagger
package includes a built-in Swagger UI that you can access by visiting the following URL in your browser:
http://localhost:8000/docs
By default, l5-swagger
will serve the Swagger UI at the /docs
endpoint, where you can see your API documentation in a user-friendly format.
Customizing the Swagger UI
You can customize how the Swagger UI is served by modifying the config/l5-swagger.php
configuration file. For example, you can change the route for the documentation, the title of the Swagger UI page, and more.
'ui' => [
'path' => 'docs', // The path where the Swagger UI is served
'title' => 'HookBox API Documentation' // Customize the title of the Swagger UI page
],
Step 6: Serve the Swagger UI Publicly
If you want your API documentation to be publicly available, make sure the route is accessible without authentication. By default, Swagger UI is available to users without any authentication, but you can configure access control for security if needed.
To ensure it is publicly available, add the following to your routes:
Route::get('/docs/hookbox-api-docs.json', function () {
return response()->json(Storage::get('api-docs/hookbox-api-docs.json'));
})->withoutMiddleware('auth:api');
This will allow public access to your Swagger documentation.
Step 7: Troubleshooting
Here are some common issues and troubleshooting tips:
1. Error: "Unauthorized" when accessing the docs
If you're getting an "Unauthorized" error while trying to access the Swagger UI, make sure that you have disabled authentication for the Swagger route as shown in Step 6.
2. Error: "No OpenAPI info found"
If you're seeing an error like "No OpenAPI info found," ensure that the @OA\Info
annotation is correctly placed in your controller or another relevant file. Also, make sure you've run the php artisan l5-swagger:generate
command after making any changes.
3. Customization Issues
You can tweak the look and feel of the Swagger UI by modifying the l5-swagger.php
configuration file. This file allows you to customize paths, API versioning, and other settings.
Conclusion
By following these steps, you can easily generate and display Swagger (OpenAPI) documentation for your Laravel API using the l5-swagger
package. With proper annotations, you provide clear and interactive documentation that helps developers understand how to interact with your API.
Swagger/OpenAPI documentation also makes it easier to onboard new developers and improves collaboration between teams. So, integrate it into your Laravel API and enhance the developer experience!
Top comments (0)