php swagger安装和使用

博客分类: software 阅读次数: comments

php swagger安装和使用

简介

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。

入门

swagger-php 的目的是使用 phpdoc 注释来生成一个 swagger.jsonswagger.yaml

安装

composer require zircote/swagger-php

帮助

使用 ./vendor/bin/openapi --help 获取帮助

Usage: openapi [--option value] [/path/to/project ...]

Options:
  --output (-o)     Path to store the generated documentation.
                    ex: --output openapi.yaml
  --exclude (-e)    Exclude path(s).
                    ex: --exclude vendor,library/Zend
  --pattern (-n)    Pattern of files to scan.
                    ex: --pattern "*.php" or --pattern "/\.(phps|php)$/"
  --bootstrap (-b)  Bootstrap a php file for defining constants, etc.
                    ex: --bootstrap config/constants.php
  --processor       Register an additional processor.
  --format          Force yaml or json.
  --debug           Show additional error information.
  --help (-h)       Display this help message.

使用

写(Write):

/**
 * @OA\Info(
 *     version="1.0",
 *     title="Example for response examples value"
 * )
 */

输出(To output):

openapi: 3.0.0
info:
  title: 'Example for response examples value'
  version: '1.0'

注意,教条注释支持数组,但是使用 {} 而不是 []
虽然教条也支持对象,但也使用 {} ,要求将属性名用 " 包围。

对象和数组(Arrays and Objects

将同一类型的多个注释放置在一个对象数组中。对于对象,属性的约定是使用与注释相同的字段名:response@OA\Response,property 在 @OA\Property,等等

/**
 * @OA\Get(
 *   path="/api/endpoint",
 *   @OA\Parameter(name="filter",in="query", @OA\JsonContent(
 *      @OA\Property(property="type", type="string"),
 *      @OA\Property(property="color", type="string"),
 *   )),
 *   @OA\Response(response=200, description="Success")
 * )
 */

生成(Generates):

openapi: 3.0.0
paths:
  /api/endpoint:
    get:
      parameters:
        -
          name: filter
          in: query
          content:
            application/json:
              schema:
                properties:
                  type: { type: string }
                  color: { type: string }
                type: object
      responses:
        '200':
          description: Success

Swagger-PHP 检测基于上下文的值(Swagger-PHP detects values based on context)。Swagger-PHP着眼于减少重复的注释上下文。

<?php
namespace OpenApi\LinkExample;
/**
 * @OA\Schema(schema="user")
 */
class User
{

    /**
     * @OA\Property()
     * @var string
     */
    public $username;

    /**
     * @OA\Property()
     * @var string
     */
    public $uuid;
}

结果(results in):

openapi: 3.0.0
components:
  schemas:
      user:
	      properties:
	        username:
	          type: string
	        uuid:
	          type: string
	      type: object

实例

可以参照开发者的 github 的例子:zircote/swagger-php

我自己写了一个测试的类:

<?php
declare (strict_types = 1);
namespace Controller;

use OpenApi\Annotations as OA;

class TesUserController
{

    /**
     * @OA\Get(
     *     path="/testapi/user",
     *     tags={"testuser"},
     *     summary="用户列表",
     *     description="测试api接口,获取用户列表",
     *     operationId="TestController_list",
     *     @OA\Parameter(name="Authorization", in="header", description="jwt签名", required=true,
     *         @OA\Schema(type="string", default="Bearer ")
     *     ),
     *     @OA\Parameter(name="page", in="query", description="页码",
     *         @OA\Schema(type="int", default="1")
     *     ),
     *     @OA\Parameter(name="page_size", in="query", description="页数",
     *         @OA\Schema(type="int", default="20")
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="测试用户列表返回",
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="total_count", type="string", description="用户数量"),
     *             @OA\Property(property="list", type="array", description="用户信息返回",
     *                 @OA\Items(type="object",
     *                     @OA\Property(property="user_id", type="integer", description="用户id"),
     *                     @OA\Property(property="nickname", type="string", description="用户昵称"),
     *                     @OA\Property(property="avatar", type="string", description="用户头像"),
     *                     @OA\Property(property="login_log", type="array", description="用户登陆日志",
     *                         @OA\Items(type="object",
     *                             @OA\Property(property="datetime", type="integer", description="登陆时间"),
     *                             @OA\Property(property="ip", type="string", description="ip地址")
     *                         )
     *                     )
     *                 )
     *             )
     *         )
     *     )
     * )
     */
    public function lists()
    {
        return $this->response->success($data);
    }

    /**
     * @OA\Get(
     *     path="/testapi/user/{user_id}",
     *     tags={"testuser"},
     *     summary="用户详细信息",
     *     description="测试api接口,获取用户详细信息",
     *     operationId="TestController_info",
     *     @OA\Parameter(name="Authorization", in="header", description="jwt签名", required=true,
     *         @OA\Schema(type="string", default="Bearer ")
     *     ),
     *     @OA\Parameter(name="user_id", in="path", description="用户id", required=true,
     *         @OA\Schema(type="int", default="1")
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="测试用户详细信息返回",
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="user_id", type="integer", description="用户id"),
     *             @OA\Property(property="nickname", type="string", description="用户昵称"),
     *             @OA\Property(property="avatar", type="string", description="用户头像"),
     *             @OA\Property(property="login_log", type="array", description="用户登陆日志",
     *                 @OA\Items(type="object",
     *                     @OA\Property(property="datetime", type="integer", description="登陆时间"),
     *                     @OA\Property(property="ip", type="string", description="ip地址")
     *                 )
     *             )
     *         )
     *     )
     * )
     */
    public function info()
    {
        return $this->response->success($data);
    }

    /**
     * @OA\Post(
     *     path="/testapi/user",
     *     tags={"testuser"},
     *     summary="创建新用户",
     *     description="测试api接口,创建新用户",
     *     operationId="TestController_create",
     *     @OA\Parameter(name="Authorization", in="header", description="jwt签名", required=true,
     *         @OA\Schema(type="string", default="Bearer ")
     *     ),
     *     @OA\RequestBody(description="List of user object",
     *         @OA\MediaType(mediaType="application/x-www-form-urlencoded",
     *             @OA\Schema(type="object",
     *                 @OA\Property(property="nickname", type="string", description="用户昵称"),
     *                 @OA\Property(property="avatar", type="string", description="用户头像")
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="测试新用户详细信息返回",
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="user_id", type="integer", description="用户id"),
     *             @OA\Property(property="nickname", type="string", description="用户昵称"),
     *             @OA\Property(property="avatar", type="string", description="用户头像")
     *         )
     *     )
     * )
     */
    public function create()
    {
        return $this->response->success($data);
    }

    /**
     * @OA\Put(
     *     path="/testapi/user/{user_id}",
     *     tags={"testuser"},
     *     summary="修改用户",
     *     description="测试api接口,修改用户",
     *     operationId="TestController_update",
     *     @OA\Parameter(name="Authorization", in="header", description="jwt签名", required=true,
     *         @OA\Schema(type="string", default="Bearer ")
     *     ),
     *     @OA\Parameter(name="user_id", in="path", description="用户id", required=true,
     *         @OA\Schema(type="int", default="1")
     *     ),
     *     @OA\RequestBody(description="List of user object",
     *         @OA\MediaType(mediaType="application/x-www-form-urlencoded",
     *             @OA\Schema(type="object",
     *                 @OA\Property(property="nickname", type="string", description="用户昵称"),
     *                 @OA\Property(property="avatar", type="string", description="用户头像")
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="测试修改用户详细信息返回",
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="user_id", type="integer", description="用户id"),
     *             @OA\Property(property="nickname", type="string", description="用户昵称"),
     *             @OA\Property(property="avatar", type="string", description="用户头像")
     *         )
     *     )
     * )
     */
    public function update()
    {
        return $this->response->success($data);
    }

    /**
     * @OA\Delete(
     *     path="/testapi/user/{user_id}",
     *     tags={"testuser"},
     *     summary="删除用户",
     *     description="测试api接口,删除用户",
     *     operationId="TestController_update",
     *     @OA\Parameter(name="Authorization", in="header", description="jwt签名", required=true,
     *         @OA\Schema(type="string", default="Bearer ")
     *     ),
     *     @OA\Parameter(name="user_id", in="path", description="用户id", required=true,
     *         @OA\Schema(type="int", default="1")
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="是否成功删除用户",
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="status", type="boolean", description="true 删除成功")
     *         )
     *     )
     * )
     */
    public function delete()
    {
        return $this->response->success($data);
    }
}

通过命令./vendor/bin/openapi --e=/path/to/project -o=storage/swagger/ -f=yaml 生成swagger文件

openapi: 3.0.0
info:
  title: 导购相关API
  description: 导购任务API
  contact:
    name: shixuefeng
    url: 'https://canren.github.io/'
    email: shixuefeng@shopex.cn
  version: 1.0.0
servers:
  -
    url: ''
    description: 'API server'
paths:
  /testapi/user:
    get:
      tags:
        - testuser
      summary: 用户列表
      description: 测试api接口,获取用户列表
      operationId: TestController_list
      parameters:
        -
          name: Authorization
          in: header
          description: jwt签名
          required: true
          schema:
            type: string
            default: 'Bearer '
        -
          name: page
          in: query
          description: 页码
          schema:
            type: int
            default: '1'
        -
          name: page_size
          in: query
          description: 页数
          schema:
            type: int
            default: '20'
      responses:
        '200':
          description: 测试用户列表返回
          content:
            application/json:
              schema:
                properties:
                  total_count: { description: 用户数量, type: string }
                  list: { description: 用户信息返回, type: array, items: { properties: { user_id: { description: 用户id, type: integer }, nickname: { description: 用户昵称, type: string }, avatar: { description: 用户头像, type: string }, login_log: { description: 用户登陆日志, type: array, items: { properties: { datetime: { description: 登陆时间, type: integer }, ip: { description: ip地址, type: string } }, type: object } } }, type: object } }
                type: object
    post:
      tags:
        - testuser
      summary: 创建新用户
      description: 测试api接口,创建新用户
      operationId: TestController_create
      parameters:
        -
          name: Authorization
          in: header
          description: jwt签名
          required: true
          schema:
            type: string
            default: 'Bearer '
      requestBody:
        description: 'List of user object'
        content:
          application/x-www-form-urlencoded:
            schema:
              properties:
                nickname:
                  description: 用户昵称
                  type: string
                avatar:
                  description: 用户头像
                  type: string
              type: object
      responses:
        '200':
          description: 测试新用户详细信息返回
          content:
            application/json:
              schema:
                properties:
                  user_id: { description: 用户id, type: integer }
                  nickname: { description: 用户昵称, type: string }
                  avatar: { description: 用户头像, type: string }
                type: object
  '/testapi/user/{user_id}':
    get:
      tags:
        - testuser
      summary: 用户详细信息
      description: 测试api接口,获取用户详细信息
      operationId: TestController_info
      parameters:
        -
          name: Authorization
          in: header
          description: jwt签名
          required: true
          schema:
            type: string
            default: 'Bearer '
        -
          name: user_id
          in: path
          description: 用户id
          required: true
          schema:
            type: int
            default: '1'
      responses:
        '200':
          description: 测试用户详细信息返回
          content:
            application/json:
              schema:
                properties:
                  user_id: { description: 用户id, type: integer }
                  nickname: { description: 用户昵称, type: string }
                  avatar: { description: 用户头像, type: string }
                  login_log: { description: 用户登陆日志, type: array, items: { properties: { datetime: { description: 登陆时间, type: integer }, ip: { description: ip地址, type: string } }, type: object } }
                type: object
    put:
      tags:
        - testuser
      summary: 修改用户
      description: 测试api接口,修改用户
      operationId: TestController_update
      parameters:
        -
          name: Authorization
          in: header
          description: jwt签名
          required: true
          schema:
            type: string
            default: 'Bearer '
        -
          name: user_id
          in: path
          description: 用户id
          required: true
          schema:
            type: int
            default: '1'
      requestBody:
        description: 'List of user object'
        content:
          application/x-www-form-urlencoded:
            schema:
              properties:
                nickname:
                  description: 用户昵称
                  type: string
                avatar:
                  description: 用户头像
                  type: string
              type: object
      responses:
        '200':
          description: 测试修改用户详细信息返回
          content:
            application/json:
              schema:
                properties:
                  user_id: { description: 用户id, type: integer }
                  nickname: { description: 用户昵称, type: string }
                  avatar: { description: 用户头像, type: string }
                type: object
    delete:
      tags:
        - testuser
      summary: 删除用户
      description: 测试api接口,删除用户
      operationId: TestController_update
      parameters:
        -
          name: Authorization
          in: header
          description: jwt签名
          required: true
          schema:
            type: string
            default: 'Bearer '
        -
          name: user_id
          in: path
          description: 用户id
          required: true
          schema:
            type: int
            default: '1'
      responses:
        '200':
          description: 是否成功删除用户
          content:
            application/json:
              schema:
                properties:
                  status: { description: 'true 删除成功', type: boolean }
                type: object

相关链接

php-swagger:https://github.com/zircote/swagger-php