Swagger php注解常用语法梳理

Swagger php注解常用语法梳理

快速编写你的 RESTFUL API 接口文档工具,通过注释定义接口和模型,可以和代码文件放置一起,也可以单独文件存放。

Swagger 优势

  1. 通过代码注解定义文档,更容易保持代码文档的一致性
  2. 模型复用,减少文档冗余,带来更可靠的文档
  3. 提供客户端访问接口,可以直接调试接口,不需要第三方工具进行调用测试接口
  4. 支持权限认证,等功能

下面详细介绍下Swagger的参数、对象和编写规范;一下是以Laravel 和Swagger为基础进行梳理分享,参考swagger官网文档进行整理,安装和简单使用 >>请这边走

福利彩蛋:没有好玩的 API 接口?上百款免费接口等你来,免费 API,免费 API 大全

一、 @OA\Info 声明一个API版本信息

Api版本信息、联系人/组织信息、许可信息

1、基础信息

参数

字段名称 类型 描述
version string 需要 Api版本信息。
title string 需要 API的标题。
description string 参数的简要说明。
termsOfService string API的服务条款。
contact 联系对象 API的联系信息。
license 许可对象 API的许可证信息。
php 复制代码
 /**
 * @OA\Info(
 *      version="1.0.0",
 *      title="服务端API",
 *      description="服务端API",
 *      termsOfService="http://example.com/terms/",
 *      @OA\Contact(
 *          url="http://www.example.com/support"
 *          email="miy@126.com",
 *          name="开发支持"
 *      ),
 *     @OA\License(
 *         name="Apache 2.0",
 *         url="http://www.apache.org/licenses/LICENSE-2.0.html"
 *     )
 * )
 */

2、@OA\Contact 联系信息

API的公开联系信息:参数如下

字段名称 类型 描述
url string 联系人/组织的站点。
name string 联系人/组织的名称。
email string 联系人/组织的邮箱。
php 复制代码
 /**
 *@OA\Contact(
 *    url="http://www.example.com/support"
 *    email="miy@126.com",
 *    name="开发支持"
 * ),
 */

3、@OA\License 联系信息

API的公开许可信息:参数如下

字段名称 类型 描述
url string 联系人/组织的站点。
name string 联系人/组织的名称。
email string 联系人/组织的邮箱。
php 复制代码
 /**
 * @OA\License(
 *      name="Apache 2.0",
 *      url="http://www.apache.org/licenses/LICENSE-2.0.html"
 *)
 */

二、@OA\Server 服务器新

API 服务器

字段名称 类型 描述
url string Api服务器地址,。
description string Api服务器描述。
variables string 联系人/组织的邮箱。
php 复制代码
/**
 *  @OA\Server(
 *      url=L5_SWAGGER_CONST_HOST,
 *      description="L5 Swagger OpenApi dynamic host server"
 *  )
 *
 *  @OA\Server(
*      url="https://projects.dev/api/v1",
 *      description="L5 Swagger OpenApi Server"
 * )
 */

三、@OA\Post、Get、Put、Delete 参数描述

字段名称 类型 描述
tags boolean 接口名称。
path string 需要。接口请求地址。
summary string 接口简短描述,Ui界面在path后面展示,这个字段应该少于120个字符,对接友好
description string 接口详情描述,接口展开描述接口功能或样例。
operationId string 友好的操作描述名称,Id在api操作描述中名称唯一,工具库可以使用这个Id标识唯一的操作
security 安全对象 注明该请求使用哪些安全策略:值列表描述了可以使用的替代安全方案(也就是说,安全需求之间存在逻辑或)。该定义覆盖任何已声明的顶层security。要删除顶级安全声明,可以使用空数组。
parameters 参数对象 适用于此操作的参数列表。如果在路径项目中已经定义了一个参数,新的定义将覆盖它,但是不能删除它。该列表不得包含重复的参数。一个独特的参数是由一个名称和位置的组合来定义的。该列表可以使用引用对象链接到在Swagger对象参数中定义的参数(如果参数巨多可以使用ref引入params对象)。最多可以有一个"body"参数。
responses 响应对象 需要。执行此操作时返回的可能响应列表。
schemes string 操作的传输协议。值必须是从列表:"http","https","ws","wss"。该值将覆盖Swagger对象schemes定义。
deprecated boolean 声明此操作将被弃用。宣布的操作的使用应该被禁止。默认值是false。
produces string 操作可以产生的类型列表。这将覆盖producesSwagger对象的定义。可以使用空值清除全局定义。值必须如MIME类型下所述
consumes string 该操作可以使用的类型列表。这将覆盖consumesSwagger对象的定义。可以使用空值清除全局定义。值必须如MIME类型下所述。
externalDocs 外部文档对象 有关此操作的其他外部文档。

MIME类型必须类似如下(包含在RFC 6838中)

html 复制代码
    application/json
    application/xml
    application/x-www-form-urlencoded
    multipart/form-data
    text/plain; charset=utf-8
    text/html
    application/pdf
    image/png

示例

php 复制代码
/**
 * 
 * @OA\Get(
 *      path="/users",
 *      operationId="getListOfUsers",
 *      tags={"Users"},
 *      description="Get list of users",
 *      security={{"Authorization-Bearer":{}}}, 
 *      @OA\Parameter(
 *         name="Authorization",
 *         in="header",
 *         required=true,
 *         description="Bearer {access-token}",
 *         @OA\Schema(
 *              type="bearerAuth"
 *         ) 
 *      ), 
 *      @OA\Response(
 *          response=200,
 *          description="Get list of users.",
 *          @OA\JsonContent(type="object",
 *              @OA\Property(property="message", type="string"),
 *              @OA\Property(property="data", type="array",
 *                  @OA\Items(type="object",
 *                      @OA\Property(property="id", type="integer"),
 *                      @OA\Property(property="name", type="string"),
 *                      @OA\Property(property="email", type="string"),
 *                  ),
 *              ),
 *          ),
 *       ),
 *       @OA\Response(response=401, description="Unauthorized"),
 *       @OA\Response(response=404, description="Not Found"),
 * )
 * 
 *
 */

1、@OA\Parameter 参数说明

字段名称 类型 描述
name string 需要。参数的名称。参数名称区分大小写。
in string 需要。参数的位置。可能的值是"query","header","path","formData"或"body"。
description string 参数的简要说明。这可能包含使用的例子。
type string 参数的类型。取值权限:"string","number","integer","boolean","array","file"。
required boolean 确定此参数是否是必需的。其默认值是false。
format string 参数格式。
default * 默认值。

示例:

php 复制代码
    /**
     *
     * @OA\Post(
     *      path="/api/login",
     *      tags={"手机验证码登录"},
     *      summary="手机验证码登录",
     *      description="用户登录(手机号+验证码)",
     *
     *      @OA\Parameter(ref="#/components/parameters/authToken"),//这里引入了authToken参数
     *      @OA\RequestBody( 
     *          @OA\MediaType(
     *              *mediaType="application/json",
     *              mediaType="application/x-www-form-urlencoded",
     *              @OA\Schema(ref="#/components/schemas/MobileLogin") //这里引入了手机验证码登录属性模板
     *          )
     *      ),
     *      @OA\Response(
     *          response=200,
     *          description="successful operation",
     *          @OA\JsonContent(
     *              ref="#/components/schemas/MsgExport",//这里引入了公共响应模板
     *              example={"code":0,"reason":"接口响应消息","result":{"status":1},"params":{}},
     *          )
     *       ),
     *
     * )
     *如果有多个参数的话且复用度较高,可以独立设置params,然后引用 
     * @OA\Parameter(
    *     in="header",
    *     name="authToken",
    *     description="测试HeaderToken",
    *     required=true,
    *     @OA\Schema(
    *          type="string"
    *     )
    * ),
     */

2、@OA\Response 参数描述

字段名称 类型 描述
description string 必填 响应的简短描述。。
schema 模式对象 响应结构的定义。它可以是一个基元,一个数组或一个对象。如果此字段不存在,则表示没有内容作为响应的一部分返回。
headers 标题对象 与响应一起发送的标题列表。
examples 示例对象 响应消息的一个例子。

示例:

php 复制代码
    /*
     * @OA\Response(
     *          response=200,
     *          description="successful operation",
     *          @OA\JsonContent(ref="#/components/schemas/MsgExport")
     *       )
     */

3、@OA\Schema

php 复制代码
/**
*定义可以复用的响应模板:
*
*  @OA\Schema(
*       schema="MsgExport",
*       required={"code","reason"},
*       @OA\Property(
*            property="code",
*            type="integer",
*            format="int32",
*            description="状态码"
*       ),
*       @OA\Property(
*            property="reason",
*            type="string",
*            description="提示消息"
*            ),
*       @OA\Property(
*            property="result",
*            type="array",
*            description="请求结果",
*            @OA\Items(
*                 @OA\Property(
*                      property="id",
*                      type="integer",
*                      description="ID"
*                  ),
*            )
*       ),
*       @OA\Property(
*            property="params",
*            type="array",
*            description="其他二外参数",
*       ),
* ),
*
*定义手机验证码登录属性模板:
*@OA\Schema(
*      description:"短信验证码登录属性",
*      schema="MobileLogin",
*      required={"mobile", "code","codeType"},
*      example={"mobile":"18913556768","code":"123123","codeType":1},
*      @OA\Property(
*          property="mobile",
*          type="string",
*          description="手机号"
*      ),
*      @OA\Property(
*          property="code",
*          type="string",
*          description="在验证码"
*      ),
*     @OA\Property(
*          property="codeType",
*          type="integer",
*          description="验证码类型",
*          default=1,
*      ),
* )
*/

4、@OA\SecurityScheme 鉴权

普通apiKey鉴权

php 复制代码
/**
 * @OA\SecurityScheme(
 *     type="apiKey",
 *     description="全局添加API Token鉴权",
 *     name="authorization",
 *     in="header",
 *     securityScheme="Authorization-Bearer"
 * )
 *
 */

示例演示渲染如下:

二、不分组接口

项目开发中接口众多,需要对相同业务类型进行分组显示,否则就是这样的:

如果有个几十个接口的话,页面可想而知

三、分组接口

swagger-php 提供了tag,上面的情况是没有弄清楚tag的作用,才导致接口零散无须

在添加接口注解的时候合理充分的使用tag可以是接口测试页面变得简洁有序更友好:

1.定义顶层Tag

可以在控制器的顶层定义一个父级tag,添加业务描述和接口简介

php 复制代码
/**
 * 处理登录相关的逻辑
 *
 * Class LoginController
 * @package App\Http\Controllers\Api
 * @OA\Tag(
 *     name="登录鉴权",
 *     description = "用户登录鉴权,安全秘钥获取、登录状态、登出"
 * )
 * @OA\Tag(
 *     name="分组1",
 *     description = "用户登录鉴权,安全秘钥获取、登录状态、登出"
 * )
 * @OA\Tag(
 *     name="分组2",
 *     description = "用户登录鉴权,安全秘钥获取、登录状态、登出"
 * )
 */

2.接口tag

接口定义和注解的时候添加tag,下面定义了三个tag,每一个接口可以属于多个tag分组,这里为了演示将接口进行了分组:定义分组(登录鉴权,分组1,分组2);未定义的分组(分组3)

php 复制代码
    /**    
     * @OA\Get(
     *      path="/api/pub/key",
     *      operationId="apiLoginKey",
     *      tags={"登录鉴权","分组1"},
     *      summary="秘钥获取",
     *      description="发送手机验证妈的时候对手机号进行加密,进行发送",
     *      @OA\Response(
     *          response=200,
     *          description="successful operation",
     *          @OA\JsonContent(ref="#/components/schemas/MsgExport")
     *       )
     * )
     *
     *
     * @OA\Get(
     *      path="/api/login/status",
     *      tags={"登录鉴权","分组1","分组3"},
     *      summary="登录状态",
     *      description="Returns project data",
     *     @OA\Response(
     *          response=200,
     *          description="successful operation",
     *          @OA\JsonContent(ref="#/components/schemas/MsgExport")
     *       )
     * )
     *
     * @OA\Post(
     *      path="/api/login",
     *      tags={"登录鉴权","分组2","分组3"},
     *      summary="手机验证码登录",
     *      description="用户登录(手机号+验证码)",
     *      @OA\Parameter(ref="#/components/parameters/authToken"),
     *      @OA\RequestBody(
     *          @OA\MediaType(
     *              mediaType="application/x-www-form-urlencoded",
     *              @OA\Schema(ref="#/components/schemas/MobileLogin")
     *          )
     *      ),
     *      @OA\Response(
     *          response=200,
     *          description="successful operation",
     *          @OA\JsonContent(
     *              ref="#/components/schemas/MsgExport",
     *              example={"code":0,"reason":"接口响应消息","result":{"status":1},"params":{}},
     *          )
     *       ),
     *
     * )
     *
     * @OA\Get(
     *      path="/api/login/logout",
     *      tags={"登录鉴权","分组2"},
     *      summary="登出",
     *      description="用户登出",
     *     @OA\Response(
     *          response=200,
     *          description="successful operation",
     *       )
     * )
     */

页面渲染结果如下:

定义的分组顶部显示,未定义的分组3,最后显示:

如何合理的规划和使用tag进行分组需要根据实际业务情况进行设计

福利彩蛋:没有好玩的 API 接口?上百款免费接口等你来,免费 API,免费 API 大全

相关推荐
梦中北山11 分钟前
JWT安全分析
开发语言·网络·安全·web安全·php
编程刘明24 分钟前
学会拥抱Python六剑客,提高编程效率
开发语言·数据库·python·程序人生·职场和发展·学习方法
不吃饭的猪24 分钟前
【无标题】
java·开发语言·docker
不会编程的小孩子24 分钟前
python 基础综合应用——小开发
开发语言·python
happy_plus37 分钟前
AutoX.js从某音分享链接解析出视频ID
开发语言·javascript·ecmascript
AI浩1 小时前
python Flask methods
开发语言·python·flask
在无清风1 小时前
数据结构(期末)
java·开发语言
极客代码1 小时前
深入剖析Python中的Pandas库:通过实战案例全方位解读数据清洗与预处理艺术
开发语言·人工智能·python·pandas
大数据小朋友1 小时前
Pand函数详解进阶:案例解析(第26天)
大数据·开发语言·数据仓库·python·pandas
pk_xz1234561 小时前
如何使用thinkPHP开发
运维·服务器·php