swagger3在php项目中的使用

以下以thinkphp6框架及dev.think.com项目域名进行示范:

下载swagger-ui

git clone https://github.com/swagger-api/swagger-ui.git

复制swagger-ui目录下dist文件到php项目根目录

如:thinkphp6的public目录下

打开php项目安装swagger-php拓展

composer require zircote/swagger-php

编写文档接口

<?php
use think\facade\Route;

Route::get('/swagger', function() {
   $openapi = \OpenApi\scan('../app');

    header('Content-Type: application/json');
    echo $openapi->toJson();
});

编辑dist目录下index.html文件,修改url地址为文档路由地址

window.onload = function() {
  // Begin Swagger UI call region
  const ui = SwaggerUIBundle({
    url: "http://dev.think.com/swagger",//路由地址
    dom_id: '#swagger-ui',
    deepLinking: true,
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: "StandaloneLayout"
  })

注解格式参考

/**
 * @OA\Info(title="thinkphp6接口文档", version="1.0.1")
 */

/**
    * @OA\Get(path="/api/article",
    *   tags={"文章管理"},
    *   summary="文章列表",
    *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
    *   @OA\Parameter(name="page", in="query", description="页码", @OA\Schema(type="int", default="1")),
    *   @OA\Parameter(name="limit", in="query", description="行数", @OA\Schema(type="int", default="10")),
    *   @OA\Response(response="200", description="The User")
    * )
    */
public function index()
{
       $limit = $this->request->param('limit/d', 10);
       $data = ArticleModel::paginate($limit);
       return $this->jsonReturn(200, 'success', $data);
}

   /**
    * @OA\Post(path="/api/article",
    *   tags={"文章管理"},
    *   summary="新增文章",
    *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string")),
    *   @OA\RequestBody(
    *     @OA\MediaType(
    *       mediaType="multipart/form-data",
    *         @OA\Schema(
    *           @OA\Property(description="文章名称", property="title", type="string", default="dd"),
    *           @OA\Property(description="文章内容", property="content", type="string"),
    *           required={"title", "content"})
    *       )
    *     ),
    *   @OA\Response(response="200", description="successful operation")
    * )
    */
public function save()
   {
       $param = $this->request->post();
       $rule = [
           'title' => 'require',
           'content' => 'require'
       ];

       $param = array_intersect_key($param, $rule);
       try {
           $this->validate($param, $rule);
       } catch (ValidateException $e) {
           return $this->jsonReturn(412, $e->getError());
       }

       ArticleModel::create([
           'title' => $param['title'],
           'content' => $param['content'],
           'created_at' => date('Y-m-d H:i:s')
       ]);

       return $this->jsonReturn();
   }

   /**
    * @OA\Get(path="/api/article/{id}",
    *   tags={"文章管理"},
    *   summary="文章详情",
    *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string")),
    *   @OA\Parameter(name="id", in="path", description="文章id", @OA\Schema(type="int")),
    *   @OA\Response(response="200", description="The User")
    * )
    */
   public function read($id)
   {
       $data = ArticleModel::whereId($id)->find();
       return $this->jsonReturn(200, 'success', $data);
   }

   /**
    * @OA\Put(path="/api/article/{id}",
    *   tags={"文章管理"},
    *   summary="编辑文章",
    *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string")),
    *   @OA\Parameter(name="id", in="path", description="文章id", @OA\Schema(type="int")),
    *   @OA\RequestBody(
    *     @OA\MediaType(
    *       mediaType="content-type/json",
    *         @OA\Schema(
    *           @OA\Property(description="文章名称", property="title", type="string"),
    *           @OA\Property(description="文章内容", property="content", type="string"),
    *           required={"title", "content"})
    *       )
    *     ),
    *   @OA\Response(response="200", description="successful operation")
    * )
    */
   public function update($id)
   {
       $param = $this->request->put();
       $rule = [
           'title' => 'require',
           'content' => 'require'
       ];

       $param = array_intersect_key($param, $rule);

       try {
           $this->validate($param, $rule);
       } catch (ValidateException $e) {
           return $this->jsonReturn(412, $e->getError());
       }

       ArticleModel::whereId($id)->update([
           'title' => $param['title'],
           'content' => $param['content'],
           'updated_at' => date('Y-m-d H:i:s')
       ]);

       return $this->jsonReturn();
   }

   /**
    * @OA\Delete(path="/api/article/{id}",
    *   tags={"文章管理"},
    *   summary="删除文章",
    *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string")),
    *   @OA\Parameter(name="id", in="path", description="文章id", @OA\Schema(type="int")),
    *   @OA\Response(response="200", description="The User")
    * )
    */
   public function delete($id)
   {
       ArticleModel::destroy($id);
       return $this->jsonReturn();
   }

PUT、POST请求方式的注解格式不一样

Paramter参数的in参数

1、header:参数在header头中传递
2、query:参数在地址后传递如 http://dev.think.com?id=1
3、path:参数在rest地址中如 http://dev.think.com/user/1
4、cookie:参数在cookie中传递

Schema配置

1、type:指定字段类型
2、default:指定字段默认值

更多使用方式参考php项目中vendor中zircote\swagger-php目录下的Examples文件
访问http://dev.think.com/dist/既可使用swagger

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Go 1.17 ,你可以使用 embed 包将静态文件嵌入到可执行文件,因此可以将 Swagger UI 嵌入到 Go Web 项目,而不需要单独部署 Swagger UI。 以下是在 Goland 项目使用 Swagger 的步骤: 1. 安装 Swagger 相关依赖:在项目添加 `github.com/swaggo/swag` 和 `github.com/swaggo/gin-swagger` 两个依赖库,可以使用以下命令: ``` go get -u github.com/swaggo/swag go get -u github.com/swaggo/gin-swagger go get -u github.com/swaggo/gin-swagger/swaggerFiles ``` 2. 在项目添加 Swagger 注释:在需要生成 Swagger 文档的接口上添加注释,例如: ``` // @Summary 获取用户信息 // @Description 根据用户ID获取用户信息 // @Tags 用户管理 // @Produce json // @Param id path int true "用户ID" // @Success 200 {object} UserResponse // @Failure 400 {string} string "请求参数错误" // @Router /users/{id} [get] func GetUserByID(c *gin.Context) { // ... } ``` 3. 生成 Swagger 文档:在项目根目录下执行以下命令,生成 Swagger 文档: ``` swag init ``` 该命令会在项目生成一个 `docs` 目录,其包含了 Swagger 文档的 JSON 文件和 HTML 文件。 4. 在项目嵌入 Swagger UI:在项目添加一个 `swagger` 目录,并将 Swagger UI 的静态文件拷贝到该目录。可以从 Swagger 官网(https://swagger.io/tools/swagger-ui/)下载最新的 Swagger UI 版本。 ``` ├── main.go ├── go.mod ├── go.sum ├── docs │ ├── docs.go │ ├── swagger.json │ └── swagger.yaml └── swagger ├── index.html ├── swagger-ui-standalone-preset.js ├── swagger-ui-standalone-preset.js.map ├── swagger-ui.css ├── swagger-ui.css.map ├── swagger-ui.js ├── swagger-ui.js.map └── swagger-ui.min.js ``` 5. 在项目添加 Swagger UI 的路由:在项目添加一个路由,将 Swagger UI 的 HTML 文件和静态文件提供给用户访问,例如: ``` router.GET("/swagger/*any", gin.WrapH(http.FileServer(http.Dir("./swagger")))) ``` 这样,用户可以通过访问 `/swagger/index.html` 来查看 Swagger 文档。 6. 启动项目并访问 Swagger UI:在 Goland 启动项目,然后在浏览器访问 `http://localhost:8080/swagger/index.html`,即可访问 Swagger UI 并查看文档。 需要注意的是,这种方式虽然可以将 Swagger UI 嵌入到可执行文件,但是每次修改 Swagger UI 后都需要重新编译可执行文件,因此不建议在生产环境使用。如果你需要在生产环境使用 Swagger UI,建议单独部署一个 Swagger UI 服务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值