标签:index users 自动生成 文档 网页 contents pen 升级 base
swagger2 升级到了3,并改名为OpenAPI Spec,所有部分注解有一些变化,这里以thinkphp6+swagger-php3.0来配置找到dist目录, 打开index.html把其中的url改成自己到服务器url,这里我以本地配置为例:
如果想支持中文在index.html中加上
<script src=‘lang/translator.js‘ type=‘text/javascript‘>
</script><script src=‘lang/zh-cn.js‘ type=‘text/javascript‘></script>
原项目网页地址是:http://127.0.0.1:8806, 现在接口前端ui地址是:http://127.0.0.1:8806/swagger-ui/dist/index.html, 此时因为没有配置swagger.json只能显示头部,无法显示接口详细信息
composer require zircote/swagger-php
注意此时安装是使用最新版的3.0
$> php /usr/local/var/www/vendor/zircote/swagger-php/bin/openapi /usr/local/var/www/app/api/controller -o /usr/local/var/www/public/uploads
其中:
/usr/local/var/www/vendor/zircote/swagger-php/bin/openapi 为swagger-php插件生成json文件的主命令
/usr/local/var/www/app/api/controller 为接口目录,该目录会被主命令依次扫描生成对应json配置代码
/usr/local/var/www/public/uploads 为swagger.json存储文件的目录
public function apidoc(){
// $RootDir = $_SERVER[‘DOCUMENT_ROOT‘];$path =‘../app/api/controller‘; //你想要哪个文件夹下面的注释生成对应的API文档 $swagger = \OpenApi\scan($path); header(‘Content-Type: application/x-yaml‘); // var_dump($swagger); $swagger_json_path = ‘./uploads/swagger.json‘; $res = file_put_contents($swagger_json_path,$swagger->toYaml()); if ($res == true) { return redirect(‘http://127.0.0.1:8806/swagger-ui/dist/index.html‘); } }
自动生成swagger.json后会自动跳转到最开始配置到swagger-ui前端地址,我们可以尝试在controller目录下新建一个swagger.php,如下代码:
/**
- @OA\Swagger(
- schemes={"http"},
- host="127.0.0.1:8806",
- basePath="/",
- @OA\Info(
- version="1.0.0",
- title="接口文档",
- description="Version: 1.0.0",
- @OA\Contact(name = "daydream", email = "heheiscool@163.com")
- ),
*/
注意swagger格式,这里行前缀以*开头,大家自己替换下(这里编辑显示有点小问题)
然后显示以下就代表配置正常了:
案例:
<?php
use OpenApi\Annotations as OA;
/**
- @OA\Info(
- version="1.0",
- title="Example for response examples value"
- )
*//**
- @OA\Post(
- path="/users",
- summary="Adds a new user",
- @OA\RequestBody(
- @OA\MediaType(
- mediaType="application/json",
- @OA\Schema(
- @OA\Property(
- property="id",
- type="string"
- ),
- @OA\Property(
- property="name",
- type="string"
- ),
- example={"id": 10, "name": "Jessica Smith"}
- )
- )
- ),
- @OA\Response(
- response=200,
- description="OK"
- )
- )
*/
以上为post请求的例子,请区别与2.0的不同
<?php
namespace OpenApi\LinkExample;
/**
MVC controller that handles "users/" urls.
/
class UsersController
{/**
- @OA\Get(path="/2.0/users/{username}",
- operationId="getUserByName",
- @OA\Parameter(name="username",
- in="path",
- required=true,
- @OA\Schema(type="string")
- ),
- @OA\Response(response="200",
- description="The User",
- @OA\JsonContent(ref="#/components/schemas/user"),
- @OA\Link(link="userRepositories", ref="#/components/links/UserRepositories")
- )
- )
*/
public function getUserByName($username)
{
}
}
以上为get请求的例子
详细可以参考下原文档(后期有时间我再逐一补充完善):
1、https://github.com/zircote/swagger-php
2、https://swagger.io/docs/specification/basic-structure/
标签:index users 自动生成 文档 网页 contents pen 升级 base
原文地址:https://blog.51cto.com/13238147/2485065