Installation:
composer require zquintana/lara-swag dev-master
Add the service provider to config/app.php:
ZQuintana\LaraSwag\Provider\LaraSwagProvider::class
Publish Config & Assets:
php artisan vendor:publish --provider="ZQuintana\LaraSwag\Provider\LaraSwagProvider::class"
This generates:
config/lara_swag.php (configuration)routes/lara_swag.php (Swagger UI routes)Register Routes:
Include the generated lara_swag.php in your routes/api.php (or routes/web.php if using Laravel <5.3):
Route::group(['prefix' => 'api'], function () {
require_once base_path('routes/lara_swag.php');
});
Annotate a Controller: Add PHPDoc-style annotations to your controller methods to define API endpoints:
/**
* @api {get} /users Retrieve a list of users
* @apiName GetUsers
* @apiGroup User
* @apiSuccess {Object[]} users List of users
*/
public function index()
{
return User::all();
}
Access Swagger UI:
Visit /api/docs (or the configured path) to view the generated API documentation.
Generate documentation for a single controller to validate the package works. For example:
/**
* @api {post} /users Create a new user
* @apiName CreateUser
* @apiGroup User
* @apiParam {String} name User's name
* @apiParam {String} email User's email
* @apiSuccess {Object} user Created user
*/
public function store(Request $request)
{
return User::create($request->all());
}
Refresh /api/docs to see the new endpoint documented.
Annotation-Based Documentation:
@api, @apiName, @apiGroup, @apiParam, @apiSuccess, etc., in PHPDoc blocks for controllers and methods./**
* @api {get} /users/:id Get a user by ID
* @apiName GetUser
* @apiGroup User
* @apiParam {Number} id User's ID
* @apiSuccess {Object} user User details
* @apiSuccessExample Success Response:
* HTTP/1.1 200 OK
* {
* "user": {
* "id": 1,
* "name": "John Doe"
* }
* }
*/
public function show($id)
{
return User::findOrFail($id);
}
Grouping Endpoints:
@apiGroup to logically group related endpoints (e.g., User, Auth, Product).Request/Response Examples:
@apiSuccessExample and @apiErrorExample to provide sample responses:
/**
* @apiErrorExample Error Response:
* HTTP/1.1 404 Not Found
* {
* "error": "User not found"
* }
*/
Authentication:
@apiHeader for tokens):
/**
* @apiHeader {String} Authorization Bearer token
*/
public function sensitiveData()
{
// Requires auth
}
Integration with Laravel Routes:
@apiName for consistency. Use named routes:
Route::get('/users/{id}', ['as' => 'users.show', 'uses' => 'UserController@show']);
Custom Templates:
resources/views/vendor/lara_swag directory.Dynamic Documentation:
php artisan route:cache) for better performance in production.Versioning:
/v1/api/docs) to document multiple API versions separately.Testing:
public function testAnnotationsAreParsed()
{
$reflection = new \ReflectionClass(UserController::class);
$method = $reflection->getMethod('index');
$docComment = $method->getDocComment();
$this->assertStringContainsString('@api {get} /users', $docComment);
}
CI/CD:
Annotation Parsing Issues:
@ or malformed tags)./api/docs/json).Route Mismatches:
@apiName or @api paths don’t match actual routes, causing broken links in Swagger UI.Caching:
php artisan route:clear) or disable caching in config/lara_swag.php during development:
'cache' => env('APP_ENV') !== 'local',
Beta Limitations:
Template Overrides:
publish command is run and templates are placed in resources/views/vendor/lara_swag. Clear view cache if necessary:
php artisan view:clear
Inspect Generated JSON:
/api/docs/json to see the raw Swagger JSON. Errors here will break Swagger UI.paths object due to unparsed annotations.Check Logs:
APP_DEBUG=true) and inspect Laravel logs (storage/logs/laravel.log) for annotation parsing errors.Validate Annotations:
grep -r "@api" app/Http/Controllers/ || echo "No annotations found!"
Custom Annotations:
ZQuintana\LaraSwag\Parser\AnnotationParser class or use Laravel’s service container to bind a custom parser.Post-Processing JSON:
lara_swag.json event:
Event::listen('lara_swag.json', function ($json) {
$json['info']['title'] = 'Custom API Title';
return $json;
});
Dynamic Tagging:
public function handle($request, Closure $next)
{
if ($request->is('admin/*')) {
$request->lara_swag_tags = ['Admin'];
}
return $next($request);
}
Integration with API Testing:
public function testApiWithSwag()
{
$swagJson = file_get_contents(public_path('api/docs/json'));
$data = json_decode($swagJson, true);
// Assert endpoints exist, etc.
}
Localization:
resources/lang/vendor/lara_swag directory.How can I help you explore Laravel packages today?