写本篇文章时,本人laravel版本为5.6.28
安装
composer require darkaonline/l5-swagger Using version ^5.6 for darkaonline/l5-swagger ... - Installing swagger-api/swagger-ui (v3.17.4) - Installing doctrine/annotations (v1.6.0) - Installing zircote/swagger-php (2.0.13) - Installing darkaonline/l5-swagger (5.6.5) ...
Salin selepas log masuk
运行
php artisan vendor:publish
Salin selepas log masuk
选择L5Swagger\L5SwaggerServiceProvider
这项
这时会添加两个文件
- /config/l5-swagger.php
- /resources/views/vendor/l5-swagger/index.blade.php
配置
在app/Http/Controllers/Controller.php
文件中class
前添加注释
<?php namespace App\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; /** * @SWG\Swagger( * basePath="/calculate-rates", * @SWG\Info( * title="项目名称 API", * version="1.0.0" * ) * ) */ class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; }
Salin selepas log masuk
运行命令
php artisan l5-swagger:generate
Salin selepas log masuk
Salin selepas log masuk
打开你的项目网址http://localhost/api/documentation
,你会看到swagger已经运行成功了,但是没有显示任何API文档。
编写文档
拿http://localhost/home
示例:
在HomeController
的index
方法上面编写文档
/** * @SWG\Get( * path="/home", * summary="用户资料", * @SWG\Response(response=200, description="请求成功"), * @SWG\Response(response=401, description="用户验证失败"), * @SWG\Response(response=500, description="服务器错误") * ) * */ public function index() { return view('home'); }
Salin selepas log masuk
再次运行命令
php artisan l5-swagger:generate
Salin selepas log masuk
Salin selepas log masuk
回到http://localhost/api/documentation
中刷新,文档就已经出来了,应该是长这个样子