Swagger2.0结构说明

Swagger2.0结构说明

元数据

1.每个Swagger规范都以Swagger版本开始

swagger: "2.0"

2.需要指定API的info-title,description(可选),version(API版本,不是文件版本/Swagger版本)

info:
  title: Instruction API
  description:this is the API's description
  version:1.0.0
  • version 可以是自定义字符串,eg:1.0-beta,2018-02-02等
  • description 可以使多行的
  • info 中也可以支持其他信息对象,例如license, contact等

API调用的基础URL

所有API调用的基础URL由host , schemes , basePath(根级别)组成

 host: api.instruction.com
 basePath: /example
 schemes: 
      - https

基础路径的设置已经完成,若是加上端点/users就可以形成完整的路径了:
<scheme>://<host>/<basePath>/users

路径

API路径paths和操作在API规范的全局部分定义,GET /用户可以用以下来描述:

paths:
  /users:
     get:
        summary:Returns a list of users.
     description: Optional extended description in Markdown.
      produces:
          - application/json
      responses:
          200:
            description: OK

可以理解为是相对路径,完整路径如下:
scheme://host/basePath/path

  • 支持路径模版:
    意味着您可以使用花括号{}将URL的部分标记为路径参数:
paths:
  /users/{userId}:
      get:
          summary: Returns a user by ID.
          parameters:
                - in: path
                  name: userId
                  required: true
                  type: integer
                  minimum: 1
                  description: Parameter description in Markdown.
          responses:
                200:
                  description: OK

eg: /users/1

Consumes和Produces定义

  • consumes:指定处理请求的提交内容类型(Content-Type)
  • produces:指定返回的内容类型,仅当request请求头中的(Accept)中包含指定类型才可以
consumes:
    - application/json
    - application/xml
produces:
    - application/json
    - application/xml
  • 这里的类型均为MIME类型
  • consumes只影响与POST,PUT和PATCH等请求主体的操作。对于像GET这样的无人机操作,它会被忽略

响应

对于每个操作,可以定义可能的状态代码,以及schema响应主体。schema可以通过内联定义或从外部定义引用 r e f ( 如 果 多 个 响 应 使 用 相 同 的 模 式 , 可 以 在 根 级 定 义 并 通 过 引 用 ref(如果多个响应使用相同的模式,可以在根级定义并通过引用 ref(使ref)。还可以为不同的内容类型提供示例响应

 paths:
  /users/{userId}:
    get:
        summary: 根据用户ID返回一个对象 user.
    parameters:
     - in: path
       name: userId
       required: true
       type: integer
       minimum: 1
       description: 根据ID返回对象
   responses:
    200:
      description: User成功获取
      schema:
        type: object
        properties:
          id:
            type: integer
            example: 1
          name:
            type: string
            example: BlingBlingY
    400:
      description:输入值不合法,不是数字.
      schema:
          $ref: "#/definitions/User"
    404:
      description: 不存在该用户.
    default:
      description: 未知错误
definitions:
  User:
  type: object
  properties:
    id:
      type: integer
      description: The user ID.
    username:
      type: string
      description: The user name.

输入和输出模型

全局的definitions允许定义通用数据结构。任何时候无论是request还是response,schema里需要用到,都可以通过$ref 来引用它们
例如:

{
  "id": 4,
  "name": "Arthur Dent"
}

可以表示为:

 definitions:
    User:
      properties:
        id:
            type: integer
        name:
            type: string
      # Both properties are required
      required:  
          - id
          - name

在请求主体模式和响应主体模式中引用:

paths:
  /users/{userId}:
    get:
        summary: Returns a user by ID.
        parameters:
            - in: path
              name: userId
              required: true
              type: integer
         responses:
              200:
                  description: OK
                  schema:
                    $ref: '#/definitions/User'
 /users:
    post:
         summary: Creates a new user.
         parameters:
            - in: body
              name: user
              schema:
                  $ref: '#/definitions/User'
        responses:
            200:
              description: OK

认证

在API中使用的身份验证关键词:securityDefinitions和security

securityDefinitions:
  BasicAuth:
    type: basic

security:
  - BasicAuth: []
  1. 目前API支持的三种认证方法:
  • 基本认证 - BasicAuth
  • API密钥 - ApiKey
  • OAuth2 公共流程
  1. securityDefinitions来定义该API支持的所有身份验证类型
securityDefinitions:
  BasicAuth:
    type: basic
  ApiKeyAuth:
    type: apiKey
    in: header
    name: X-API-Key
  OAuth2:
    type: oauth2
    flow: accessCode
    authorizationUrl:     https://example.com/oauth/authorize
    tokenUrl: https://example.com/oauth/token
    scopes:
      read: Grants read access
      write: Grants write access
      admin: Grants read and write access to administrative information

在定义了安全机制后securityDefinitions,您可以security分别在根级别或操作级别上添加该部分,将它们应用于整个API或单个操作。

在根级别上使用时,security将指定的安全机制全局应用于所有API操作,除非在操作级别上被覆盖。在以下示例中,可以使用API​​密钥或OAuth 2对API调用进行身份验证.ApiKeyAuth和OAuth2名称是指上文定义过的安全机制securityDefinitions

security:
  - ApiKeyAuth: []
  - OAuth2: [read, write]

全局security可以在个别操作中被覆盖,从而可以使用不同的认证类型,有的根本不认证,如下例:

paths:
  /billing_info:
    get:
      summary: Gets the account billing info
      security:
        - OAuth2: [admin]   # Use OAuth with a different scope
      responses:
        200:
          description: OK
        401:
          description: Not authenticated
        403:
          description: Access token does not have the required scope

  /ping:
    get:
      summary: Checks if the server is running
      security: []   # No security
      responses:
        200:
          description: Server is up and running
        default:
          description: Something is wrong
  1. 多种验证类型
    security模块可使用逻辑OR和AND组合安全要求,来实现所需的结果
security:    # A OR B
  - A
  - B
security:    # A AND B
  - A
    B
security:    # (A AND B) OR (C AND D)
  - A
    B
  - C
    D
  • 使用基本身份验证或API密钥:
security:
  - basicAuth: []
  - apiKey: []

security:
  - apiKey1: []
    apiKey2: []
  • API需要在请求中包含一对API密钥:
security:
  - apiKey1: []
    apiKey2: []
  • 使用OAuth 2或一对API密钥:
security:
  - oauth2: [scope1, scope2]
  - apiKey1: []
    apiKey2: []

参考资料:
https://swagger.io/docs/specification/about/

作者:小菜鸟_Sonya
链接:https://www.jianshu.com/p/c22bf8e173a1
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
npm提供了许多方便的工具和库来生成Swagger 2.0文档。其中一个流行的工具是swagger-jsdoc。通过结合使用JSDoc注释和swagger-jsdoc库,我们可以在JavaScript文件中定义API接口和相应的Swagger文档信息。 首先,在项目中安装npm包swagger-jsdoc。可以使用以下命令: ``` npm install swagger-jsdoc --save ``` 接下来,在项目的入口文件或者需要生成Swagger文档的文件中,引入swagger-jsdoc并配置Swagger文档的相关内容。例如: ```javascript /** * @swagger * definitions: * Pet: * properties: * name: * type: string * age: * type: integer * * @swagger * /pets: * get: * description: 获取所有宠物 * responses: * 200: * description: 成功获取宠物列表 * post: * description: 创建新宠物 * parameters: * - name: pet * description: 宠物对象 * in: body * required: true * schema: * $ref: '#/definitions/Pet' */ // 引入swagger-jsdoc const swaggerJSDoc = require("swagger-jsdoc"); const express = require("express"); const app = express(); // 配置Swagger文档 const swaggerSpec = swaggerJSDoc({ definition: { openapi: "3.0.0", // 使用Swagger版本2.0 info: { title: "宠物商店API文档", version: "1.0.0", description: "这里是宠物商店的API文档" } }, apis: ["./routes/**/*.js"], // 定义API接口的文件路径 }); // 在需要展示Swagger文档的路由上,使用swagger-ui-express库 app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerSpec)); // 其他路由及中间件... // 启动Express服务器... ``` 此外,还可以使用swagger-jsdoc提供的其他功能,例如支持路由的解析、文件导出等。更多的配置和用法可以查看swagger-jsdoc的官方文档。 通过以上步骤,我们就可以使用npm生成Swagger 2.0文档来描述我们的API接口及其相关信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值