轻松实现PHP项目的 Swagger Api 应用
1、安装swagger-php,全局配置命令
composer global require zircote/swagger-php
生成命令 ~/.composer/bin/openapi
export PATH="~/.composer/vendor/bin:$PATH"
2、进入php项目, 编写swagger注释代码
/**
* @OA\OpenApi(
* @OA\Info(
* version="1.0.0",
* title="api文档",
* description="api文档"
* ),
* @OA\Server(
* description="测试环境",
* url="http://localhost",
* ),
* @OA\Server(
* description="正式环境",
* url="http://api.wuguangping.com",
* )
* )
*
* @OA\Schema(
* schema="news",
* type="object",
* required={"title","content"},
* @OA\Property(
* property="id",
* type="integer",
* description="编号"
* ),
* @OA\Property(
* property="title",
* type="string",
* description="标题"
* ),
* @OA\Property(
* property="content",
* type="string",
* description="正文"
* ),
* @OA\Property(
* property="cover",
* type="string",
* description="配图地址"
* ),
* @OA\Property(
* property="time",
* type="string",
* description="发布时间"
* )
* )
*
* @OA\Schema(
* schema="Paging",
* @OA\Property(
* property="page",
* type="integer",
* description="页码",
* format="int32",
* default="1"
* ),
* @OA\Property(
* property="limit",
* type="integer",
* description="每页个数",
* format="int32",
* minimum="0",
* exclusiveMinimum=true,
* maximum="100",
* exclusiveMaximum=false
* )
* )
*/
class NewsController
{
/**
* @OA\Get(
* path="/news/{type}",
* summary="获取资讯",
* description="返回包含已发布的资讯列表",
* @OA\Parameter(
* name="type",
* in="path",
* required=true,
* description="类型",
* @OA\Schema(
* type="string",
* enum={"entertainment","Sports"}
* )
* ),
* @OA\Parameter(
* name="page",
* in="query",
* @OA\Schema(
* @OA\Items(ref="#/components/schemas/Paging")
* )
* ),
* @OA\Response(
* response=200,
* description="一个资讯列表",
* @OA\Schema(
* type="array",
* @OA\Items(ref="#/components/schemas/news")
* ),
* )
* )
*/
public function indexAction()
{
echo 'a';
}
}
3、执行命令,编译注释代码,生成openapi.yaml文档,这里使用的ThinkPHP5环境,扫描api模块下的控制器接口,生成到public根目录:
./vendor/zircote/swagger-php/bin/openapi --format yaml ./application/api/controller/ -o ./public/
4、下载 swagger-ui前端
git clone https://github.com/swagger-api/swagger-ui.git
5、使用默认项目 dist 文件夹
打开index.html,找到SwaggerUIBundle的url参数值为openapi.yaml生成的路径:
const ui = SwaggerUIBundle({
url: "/openapi.yaml",
})
6、浏览器打开dist项目中index.html