如何生成swagger-ui需要的json或者yaml的文件?
tp5根目录,
composer require zircote/swagger-php
方案1: 有需要的时候手动执行命令生成api_doc.json文件
添加命令
application/command.php
新增一行: \app\common\command\run\AutoCreateApiDoc::class
, 就可以执行 php think run:autoCreateApiDoc
手动生成swagger json配置文件, 配置文件所在路径 public/api_doc.json
/**
* Created by querying.
* Date: 19-2-20
* Time: 下午5:15
*/
namespace app\common\command\run;
use function \OpenApi\scan;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\App;
class AutoCreateApiDoc extends Command
{
protected function configure()
{
$this->setName("run:autoCreateApiDoc")->setDescribe("生成swagger-api文档");
}
protected function execute(Input $input, Output $output)
{
try {
$openapi = scan(App::getAppPath());
header('Content-Type: application/x-yaml');
$jsonStr = $openapi->toJson();
file_put_contents(App::getRootPath(). '/public/api_doc.json', $jsonStr);
} catch (\Throwable $e) {
echo $e->__toString();
}
}
}
方案2: swagger-ui直接输入的url,实时返回配置文件信息(优点:接口文档实时更新,缺点:每次打开时间较长)
新增接口
<?php
$openapi = scan(App::getAppPath());
header('Content-Type: application/x-yaml');
$jsonStr = $openapi->toJson();
echo $jsonStr;
部署swagger-ui,自动化测试接口文档
下载现成的ui组件
git clone https://github.com/swagger-api/swagger-ui.git
修改swagger.json文件地址,路径public/swagger-ui/dist/index.html
修改对应的url就可以了
<script>
window.onload = function() {
const ui = SwaggerUIBundle({
// 改动这里 ===========
// 改动这里, 这就是通过http请求,获取到swagger-json数据
// 这里更换下url就好了
url: "http://engine/api_doc.json",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
window.ui = ui
}
</script>
来源:oschina
链接:https://my.oschina.net/u/3095457/blog/3013209