Set up Laravel with Swagger for comprehensive API documentation. Step-by-step instructions
Prerequisites:
- Laravel installed on your system.
- Composer installed on your system.
- Basic knowledge of Laravel and PHP.
- A text editor or integrated development environment (IDE).
Step 1: Create a Laravel Project
If you don’t have a Laravel project already, create one using Composer. Open your terminal and run the following command:
composer create-project --prefer-dist laravel/laravel your-api-project
Replace your-api-project
with your desired project name.
Step 2: Install Swagger-PHP Library
You’ll need the Swagger-PHP library to generate Swagger documentation. Install it using Composer:
composer require zircote/swagger-php
Step 3: Create API Routes
In Laravel, define your API routes in the routes/api.php
file. You can create routes as you normally would for your API.
// routes/api.php
use Illuminate\Support\Facades\Route;
Route::get('/users', 'UserController@index');
Route::post('/users', 'UserController@store');
Route::get('/users/{id}', 'UserController@show');
// Add more routes as needed
Step 4: Generate Swagger Annotations
In your controller methods, use Swagger annotations to document your API. Here’s an example of how to annotate a controller method:
/**
* @SWG\Get(
* path="/users",
* summary="Get a list of users",
* tags={"Users"},
* @SWG\Response(response=200, description="Successful operation"),
* @SWG\Response(response=400, description="Invalid request")
* )
*/
public function index()
{
// Your API logic here
}
You can find more information on Swagger annotations in the Swagger-PHP documentation.
Step 5: Generate Swagger Documentation
After annotating your controllers, you need to generate Swagger documentation. You can do this using the artisan
command provided by the darkaonline/l5-swagger
package.
First, install the package:
composer require darkaonline/l5-swagger
Now, publish the Swagger configuration:
php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider"
Edit the config/l5-swagger.php
file to customize the Swagger configuration if needed.
Step 6: Generate Swagger Documentation
Run the following command to generate the Swagger documentation:
php artisan l5-swagger:generate
Swagger UI will be available at http://your-api-project.test/api/documentation
. Replace your-api-project.test
with your local development domain.
Step 7: Access Swagger UI
Visit the Swagger UI URL in your browser. You will see a user-friendly interface where you can explore and test your API endpoints.
Step 8: Document Additional Endpoints
Repeat Step 4 for any additional endpoints you want to document in your API.
That’s it! You’ve successfully set up Laravel with Swagger for comprehensive API documentation. Keep your Swagger annotations up to date as you make changes to your API to ensure accurate documentation.