1、根据Laravel版本选择Swagger的版,详情:https://github.com/DarkaOnLine/L5-Swagger/wiki/Installation-&-Configuration 如Laravel6执行:composer require "darkaonline/l5-swagger:6.*"
2、执行:php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider" 如果是使用了nwidart/laravel-modules,要修改config/l5-swagger.php,如下:'annotations' => [ base_path('app'), base_path('Modules'), ],
3、查看一下路由列表,执行:php artisan route:list 4、创建一个API控制器,执行:php artisan make:controller Api/UserController
代码如下:
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
/**
* @OA\Get(
* path="/api/users",
* tags={"演示"},
* summary="用户列表",
* @OA\Parameter(name="page",description="当前页码",required=true,in="query",@OA\Schema(type="integer")),
* @OA\Parameter(name="pageSize",description="每页数量",required=true,in="query",@OA\Schema(type="integer")),
* @OA\Parameter(name="keyword",description="搜索关键字",required=false,in="query",@OA\Schema(type="string")),
* @OA\Response(
* response=200,
* description="非200都表示失败"
* ),
* @OA\Response(
* response="default",
* description=""
* )
* )
*/
public function index(Request $request)
{
$pageSize = $request->input('pageSize') ?? 1;
$arr = [];
if($pageSize > 1) {
for ($i=1; $i<$pageSize; $i++) {
array_push($arr, ['id'=>$i,'user_name'=>'jiang'.$i]);
}
}
return $arr;
}
5、添加路由Route::get('users','Api\UserController@index');
6、查看一下路由列表,执行:php artisan route:list
7、生成API文档,执行:php artisan l5-swagger:generate
/**
* @OA\Post(
* path="/api/users",
* tags={"演示"},
* summary="新增用戶",
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/json",
* @OA\Schema(
* required={"name", "age"},
* @OA\Property(property="name", default="G1621084", type="string", description="姓名"),
* @OA\Property(property="age", default="22", type="integer", description="年龄"),
* @OA\Property(property="gender", default="男", type="string", description="性别")
* )
* )
* ),
* @OA\Parameter(name="Authorization",description="Bearer+' '+token",required=true,in="header", @OA\Schema(type="string")),
* @OA\Response(
* response=200,
* description="成功"
* )
* )
*/
中文文档:
https://learnku.com/laravel/t/7430/how-to-write-api-documents-based-on-swagger-php
英文文档 :
https://blog.quickadminpanel.com/laravel-api-documentation-with-openapiswagger/