Swagger & OpenAPI Specification

目录

OpenAPI Specification

Swagger Specification 是一种 API Specification(API 规范),2015 年,SmartBear Software 将 Swagger Specification 捐赠给 Linux Foundation,并改称为 OpenAPI Specification,简称(OAS)。SmartBearSoftware 也作为 OpenAPI Initiative(OAI)的创始成员,该机构以开放和透明的方式管理 OAS 的发展。

OpenAPI Specification 本质上是一种 RESTful API 的 API Description Format(描述格式),允许用户用于描述整个 API。OpenAPI 规范可以用 YAML 或 JSON 编写,包括:

  • 每个 API 的可用端点(e.g. /users)和操作(e.g. GET /users,POST /users)。
  • 操作参数每个操作的输入和输出。
  • 认证方式。
  • 联系信息,许可证,使用条款和其他信息。

通常的,我们可以根据需要手动的编写一个 OpenAPI Specification 或者让它从源代码中的注释自动生成。

Swagger 生态组件

Swagger 是基于 OpenAPI Specification 的一系列生态组件:

  • Swagger Hub:基于 OpenAPI Specification 的设计和文档平台。
  • Swagger Inspector:基于 OpenAPI Specification 的测试平台。
  • Swagger Editor:基于浏览器的编辑器,我们可以使用它来编写我们 OpenAPI 规范。
  • Swagger Codegen:基于 OpenAPI Specification 的(服务端或客户端)代码生成工具。
  • Swagger UI:将我们编写的 OpenAPI 规范呈现为交互式的 API 文档。
  • ReDoc:一款优雅的 OpenAPI Specification UI 平台。

编写 OpenAPI 规范文件

基本概念

OpenAPI Root Object(根对象)

在这里插入图片描述

在这里插入图片描述

OpenAPI 数据类型

在这里插入图片描述

定义一个请求 API

一个请求 API 主要由 Endpoint、Parameters、Body 等部分组成,我们需要分别定义。

  • 官方示例:https://editor.swagger.io/

定义元信息(Metadata)

在这里插入图片描述

title: 这是标题(必填)。
description: 这里是一段描述。
termsOfService: API 可以测试地址。
contact:
  name: 联系人。
  url: 联系人地址。
  email: 联系人邮箱。
license:
  name: Apache 2.0 授权信息
  url: https://www.apache.org/licenses/LICENSE-2.0.html
version: OpenAPI 版本号(必填)

定义请求 Endpoint

/pets:  # API 请求路径,如果需要 path value 可以使用 /pets/{petId}。
  get:  # get 请求,同理还有 put,post,delete,options 等方法。
    description: 这是一段描述信息。
    responses:  # 响应部分定义。
      '200':  # 响应码。
        description: 又是一段描述 。
        content: # 内容。
          application/json:  # context-type。
            schema:
              type: array  # 类型。
              items:  # array 字段所包含的元素。
                $ref: '#/components/schemas/pet'  # 引用组件,每个元素是一个组件,下文详细说明。

定义请求 Parameters

在这里插入图片描述

  • 在 Header 中添加参数。
name: token
in: header # 这里是固定值。
description: token to be passed as a header # 描述信息。
required: true # 是否必需的。
schema:
  type: array # 类型。
  items:
    type: integer
    format: int64
  • 在 Path 中添加参数。
name: username
in: path # 这里是固定值。
description: username to fetch
required: true
schema:
  type: string
  • 在 Query 中添加参数。
name: id
in: query # 这里是固定值。
description: ID of the object to fetch
required: false
schema:
  type: array
  items:
    type: string
style: form
explode: true

定义请求 Body

这里使用 requestBody 作为请求体。

description: user to add to the system # 描述信息。
content:  # 定义请求体。
  'application/json': # context-type
    schema: # 请求的格式。
      $ref: '#/components/schemas/User' # 组件。
    examples: # 例子。
      user:
        summary: User Example
        externalValue: 'http://foo.bar/examples/user-example.json'

  'application/xml': # context-type
    schema:
      $ref: '#/components/schemas/User'
    examples:
      user:
        summary: User Example in XML
        externalValue: 'http://foo.bar/examples/user-example.xml'

  'text/plain': # context-type
    examples:
      user:
        summary: User example in text plain format
        externalValue: 'http://foo.bar/examples/user-example.txt'

  '*/*':
    examples: # context-type
      user: 
        summary: User example in other format
        externalValue: 'http://foo.bar/examples/user-example.whatever'

定义可复用组件

当我们使用 curl 此类的工具调用 API 时,通常会使用 JSON 格式类编写 Request Body。为了让 Request Body 具有一定的可重用性,所以 OpenAPI 引入了 Components(组件)的概念。简而言之,就是可重用的 Schema。

components:
  schemas:
    ErrorModel:
      type: object
      required:
      - message
      - code
      properties:
        message:
          type: string
        code:
          type: integer
          minimum: 100
          maximum: 600
    ExtendedErrorModel:
      allOf:
      - $ref: '#/components/schemas/ErrorModel'
      - type: object
        required:
        - rootCause
        properties:
          rootCause:
            type: string

示例

# OpenAPI的版本,可用版本  3.0.0, 3.0.1, 3.0.2
openapi: 3.0.0
info:
  title: '标题'
  description: '描述'
  version: '此OAS的版本,示例0.1.9'
 
# 提供此 API 的服务器地址列表
servers:
  - url: http://api.example.com/v1
    description: Optional server description, e.g. Main (production) server
  - url: http://staging-api.example.com
    description: Optional server description, e.g. Internal staging server for testing
 
# API 端点列表
paths:
  # 端点 /users
  /users:
    # 端点 /users 的 GET 方法
    get:
      # 描述性信息
      summary: Returns a list of users.
      description: Optional extended description in CommonMark or HTML.
      # 响应规格说明
      responses:
        # 200响应说明
        '200':    # status code
          description: A JSON array of user names
          # 200 响应是 JSON 格式
          content:
            application/json:
              # JSON 的 Schema
              schema: 
                # 数组类型
                type: array
                items: 
                  type: string
    # 端点 /users 的 POST 方法
    post:
      summary: Creates a user.
      # 请求体
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                username:
                  type: string
      responses: 
        '201':
          description: Created
  # 端点 /user/{userId} 的 POST 方法
  # {} 中的是路径变量
  /user/{
    
    userId}:
    get:
      summary: Returns a user by ID.
      # 参数说明
      parameters:
        - name: userId
          # 这是一个路径变量
          in: path
          required: true
          description: The ID of the user to return.
          # Schema 中可以包含字段的验证规则
          schema:
            type: integer
            format: int64
            minimum: 1
      responses:
        '200':
          description: A user object.
          content:
            application/json:
              schema:
                # 对象类型
                type: object
                # 包含属性声明
                properties:
                  id:
                    type: integer
                    format: int64
                    example: 4
                  name:
                    type: string
                    example: Jessica Smith
        # 异常处理
        '400':
          description: The specified user ID is invalid (not a number).
        '404':
          description: A user with the specified ID was not found.
        default:
          description: Unexpected error

参考文档

https://help.coding.net/docs/management/api/import/openapi.html
https://www.breakyizhan.com/swagger/2806.html

猜你喜欢

转载自blog.csdn.net/Jmilk/article/details/108498624