1.composer添加swg依赖
composer.json添加:
"yii2mod/yii2-swagger": "*",
执行composer update
2.配置swg
在SiteController添加下边代码:
/**
* @SWG\Swagger(
* basePath="/",
* schemes={"http","https"},
* produces={"application/json"},
* consumes={"application/json"},
* @SWG\ExternalDocumentation(description="Swagger官方文档",url="https://bfanger.nl/swagger-explained/#schemaObject"),
* @SWG\Info(version="1.0", title="SWG标题", description="SWG接口文档"),
* @SWG\Tag(name="模块", description="模块"), //文档模块
* )
*/
public function actions()
{
return [
'docs' => [
'class' => 'yii2mod\swagger\SwaggerUIRenderer',
'restUrl' => Url::to(['site/json-schema']),
],
'json-schema' => [
'class' => 'yii2mod\swagger\OpenAPIRenderer',
'scanDir' => [
Yii::getAlias('@app/modules/release/controllers'),
Yii::getAlias('@app/modules/release/models')
],
],
];
}
3.代码添加swg注释
在需要配置的方法添加swg注释:
/**
* @SWG\Post(
* path="/release/content-list",
* tags={"Content"},
* summary="获取内容列表",
* @SWG\Parameter(
* name="rawBody",
* in="body",
* description="传入参数",
* required=true,
* type="string",
* @SWG\Schema(ref="#/definitions/InContentList") //输入参数注释文件(详见InContentList.php)
* ),
* @SWG\Response(
* response = 200,
* description = "请求成功",
* @SWG\Schema(ref="#/definitions/OutContentList") //输出参数注释文件(详见OutContentList.php)
* ),
* @SWG\Response(
* response = 500,
* description = "请求失败",
* ),
* )
*/
public function actionContentList()
{
}
输入和输出swg注释:InBase,OutBase是输入和输出公共参数部分
InContentList:
/**
* @SWG\Definition(required={"name"}) //这里的注释必须写 required 里边是必须字段
*/
class InContentList
{
/**
* @SWG\Property(
* type="string", //参数类型
* example="Jade", //参数实例
* description="名称" //参数注释
* )
*/
public $name;
}
OutContentList:
/**
* @SWG\Definition() //这里的注释必须写
*/
class OutContentList
{
/**
* @SWG\Property(
* type="array", //参数类型
* @SWG\Items(
* @SWG\Property(
* property="id", //数组包含字段
* type="string", //字段类型
* description="ID" //字段描述
* ),
* @SWG\Property(
* property="name",
* type="string",
* description="名称"
* ),
* @SWG\Property(
* property="address",
* type="string",
* description="地址"
* ),
* )
* )
*/
public $list; //返回数组
}