OpenAPI Specification

莘翰采
2023-12-01

参考文档: Swagger Specification

1、为什么需要规范

  • 接口的使用者(front-end developer),调用者(client),提供者(server),维护者(back-end developer),测试者(tester),需要通过规范来统一思想,提高信息传达的效率;
  • 前端开发人员不需要关心后端开发的语言和平台,也不应该去查看后端的代码或开发文档,真正的做到面向接口文档开发
  • 接口定义文档可以通过代码生成工具生成各种语言形式的框架代码,避免需求变更时导致的数据不一致问题,提高开发效率;

2、接口文档的形式和定义

顾名思义,接口文档 就是定义和描述 服务接口的文档;接口定义规范(OAS - OpenAPI Specification) 则是 接口 的元模型,它详细规定了 接口 的元素和格式。将像 Java 代码Java 语言规范 的关系一样。

路径模板(Path Templating),URL 路径中的 {} 作为占位符,可以被响应的路径参数替换。

Media Types

  • text/plain; charset=utf-8
  • application/json

HTTP Status Codes

3、接口文档的详细规范

3.1 Format

根据 OpenAPI 规范,OpenAPI 的格式可以书写为 JSON 或 YAML但 API Request 和 Response 的消息体的格式不局限于 JSON 和 YAML。

现在很多配置文件(比如Nginx和大部分脚本语言的配置文件)都习惯使用 JSON 的方式。在 Springboot 中,推荐使用 properties 或者 YAML 文件来完成配置,但是对于较复杂的数据结构,YAML 远远优于 properties。

YAML 快速入门

YAML 1.2

3.2 文档结构:Document Structure

OpenAPI 文档可以是当个文件,也可以是多个文件,开发者按需求而定。多文档的情况下,可以使用 $ref 来引用其他文档,具体参照 JSON Schema 规范。

根文档(root OpenAPI document)推荐命名为: openapi.json 或 openapi.yaml !

3.3 数据类型:Data Types

数据类型,可校验,可测试。

OAS 中的类型定义:

类型格式说明
integerint32signed 32 bits
integerint64signed 64 bits
numberfloatfloat
numberdoubledouble
string
stringbytebase64 encoded characters
stringbinaryany sequence of octets
boolean
stringdateAs defined by full-date - RFC3339
stringdate-timeAs defined by date-time - RFC3339
stringpasswordA hint to UIs to obscure input.

3.4 富文本格式

文档中 description 字段的内容支持 CommonMark 规范的 markdown 格式,因此 OpenAPI 文档渲染工具至少要支持 CommonMark 0.27.

3.5 Schema

  • OpenAPI Object
  • Info Object
  • Contact Object
  • License Object
  • Server Object
  • Server Variable Object
  • Components Object
  • Paths Object
  • Path Item Object
  • Operation Object
  • External Documentation Object
  • Parameter Object
  • Request Body Object
  • Media Type Object
  • Encoding Object
  • Responses Object
  • Response Object
  • Callback Object
  • Example Object
  • Link Object
  • Header Object
  • Tag Object
  • Reference Object
  • Schema Object
  • Discriminator Object
  • XML Object
  • Security Scheme Object
  • OAuth Flows Object
  • OAuth Flow Object

1、OpenAPI Object

该文档为根文档:

Field NameTypeDescription
openapistringREQUIRED:
infoInfo ObjectREQUIRED: 提供 API 所需的元数据
servers[Server Object]提供目的连接相关信息对象的数组
pathsPaths ObjectREQUIRED. 指定 API 的路径和操作信息
componentsComponents ObjectAn element to hold various schemas for the specification.
security[Security Requirement Object]A declaration of which security mechanisms can be used across the API. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. Individual operations can override this definition.
tags[Tag Object]A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The tags that are not declared MAY be organized randomly or based on the tools’ logic. Each tag name in the list MUST be unique.
externalDocsExternal Documentation ObjectAdditional external documentation.

Info Object Example : JSON

{
  "title": "Sample Pet Store App",
  "description": "This is a sample server for a pet store.",
  "termsOfService": "http://example.com/terms/",
  "contact": {
    "name": "API Support",
    "url": "http://www.example.com/support",
    "email": "support@example.com"
  },
  "license": {
    "name": "Apache 2.0",
    "url": "https://www.apache.org/licenses/LICENSE-2.0.html"
  },
  "version": "1.0.1"
}

Info Object Example : YAML

title: Sample Pet Store App
description: This is a sample server for a pet store.
termsOfService: http://example.com/terms/
contact:
  name: API Support
  url: http://www.example.com/support
  email: support@example.com
license:
  name: Apache 2.0
  url: https://www.apache.org/licenses/LICENSE-2.0.html
version: 1.0.1

2、Server Object

Field NameTypeDescription
urlstringREQUIRED. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in {brackets}.
descriptionstringAn optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation.
variablesMap[string, Server Variable Object]A map between a variable name and its value. The value is used for substitution in the server’s URL template.

Example : JSON

{
  "servers": [
    {
      "url": "https://{username}.gigantic-server.com:{port}/{basePath}",
      "description": "The production API server",
      "variables": {
        "username": {
          "default": "demo",
          "description": "this value is assigned by the service provider, in this example `gigantic-server.com`"
        },
        "port": {
          "enum": [
            "8443",
            "443"
          ],
          "default": "8443"
        },
        "basePath": {
          "default": "v2"
        }
      }
    }
  ]
}

Example: YAML

servers:
- url: https://{username}.gigantic-server.com:{port}/{basePath}
  description: The production API server
  variables:
    username:
      # note! no enum here means it is an open value
      default: demo
      description: this value is assigned by the service provider, in this example `gigantic-server.com`
    port:
      enum:
        - '8443'
        - '443'
      default: '8443'
    basePath:
      # open meaning there is the opportunity to use special base paths as assigned by the provider, default is `v2`
      default: v2

Server Variable Object

  • enum: 当参数的取值范围为有限的 string 集合时,通过 enum 来定义该数组;
  • default: 用来定义默认值;

3、Components Object

组件对象中定义了一组可复用的对象。

Field NameTypeDescription
schemasMap[string, Schema ObjectReference Object]
responsesMap[string, Response ObjectReference Object]
parametersMap[string, Parameter ObjectReference Object]
examplesMap[string, Example ObjectReference Object]
requestBodiesMap[string, Request Body ObjectReference Object]
headersMap[string, Header ObjectReference Object]
securitySchemesMap[string, Security Scheme ObjectReference Object]
linksMap[string, Link ObjectReference Object]
callbacksMap[string, Callback ObjectReference Object]

以上字段的所有属性名称必须符合 ^[a-zA-Z0-9\.\-_]+$ 格式;

例如:
User User_1 User_Name user-name my.org.User

组件对象示例:

"components": {
  "schemas": {
    "GeneralError": {
      "type": "object",
      "properties": {
        "code": {
          "type": "integer",
          "format": "int32"
        },
        "message": {
          "type": "string"
        }
      }
    },
    "Category": {
      "type": "object",
      "properties": {
        "id": {
          "type": "integer",
          "format": "int64"
        },
        "name": {
          "type": "string"
        }
      }
    },
    "Tag": {
      "type": "object",
      "properties": {
        "id": {
          "type": "integer",
          "format": "int64"
        },
        "name": {
          "type": "string"
        }
      }
    }
  },
  "parameters": {
    "skipParam": {
      "name": "skip",
      "in": "query",
      "description": "number of items to skip",
      "required": true,
      "schema": {
        "type": "integer",
        "format": "int32"
      }
    },
    "limitParam": {
      "name": "limit",
      "in": "query",
      "description": "max records to return",
      "required": true,
      "schema" : {
        "type": "integer",
        "format": "int32"
      }
    }
  },
  "responses": {
    "NotFound": {
      "description": "Entity not found."
    },
    "IllegalInput": {
      "description": "Illegal input for operation."
    },
    "GeneralError": {
      "description": "General Error",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/GeneralError"
          }
        }
      }
    }
  },
  "securitySchemes": {
    "api_key": {
      "type": "apiKey",
      "name": "api_key",
      "in": "header"
    },
    "petstore_auth": {
      "type": "oauth2",
      "flows": {
        "implicit": {
          "authorizationUrl": "http://example.org/api/oauth/dialog",
          "scopes": {
            "write:pets": "modify pets in your account",
            "read:pets": "read your pets"
          }
        }
      }
    }
  }
}

4、Paths Object

Path 对象中保存了 api 的相对路径,拼接在 Server 对象中的路径后可得 api 的全路径。字段名称以 / 开头。

路径匹配规则:

  • /pets/mine 先匹配 /pets/mine,然后匹配 /pets/{id}
  • /pets/{id}/pets/{name} 是等效的
  • /{entity}/me/books/{id} 在匹配时会产生歧义

Paths Object Example:

{
  "/pets": {
    "get": {
      "description": "Returns all pets from the system that the user has access to",
      "responses": {
        "200": {          
          "description": "A list of pets.",
          "content": {
            "application/json": {
              "schema": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/pet"
                }
              }
            }
          }
        }
      }
    }
  }
}

5、Path Item Object

Field NameTypeDescription
$refstringAllows for an external definition of this path item. The referenced structure MUST be in the format of a Path Item Object. If there are conflicts between the referenced definition and this Path Item’s definition, the behavior is undefined.
summarystringAn optional, string summary, intended to apply to all operations in this path.
descriptionstringAn optional, string description, intended to apply to all operations in this path. CommonMark syntax MAY be used for rich text representation.
getOperation ObjectA definition of a GET operation on this path.
putOperation ObjectA definition of a PUT operation on this path.
postOperation ObjectA definition of a POST operation on this path.
deleteOperation ObjectA definition of a DELETE operation on this path.
optionsOperation ObjectA definition of a OPTIONS operation on this path.
headOperation ObjectA definition of a HEAD operation on this path.
patchOperation ObjectA definition of a PATCH operation on this path.
traceOperation ObjectA definition of a TRACE operation on this path.
servers[Server Object]An alternative server array to service all operations in this path.
parameters[Parameter ObjectReference Object]

Path Item Object Example

{
  "get": {
    "description": "Returns pets based on ID",
    "summary": "Find pets by ID",
    "operationId": "getPetsById",
    "responses": {
      "200": {
        "description": "pet response",
        "content": {
          "*/*": {
            "schema": {
              "type": "array",
              "items": {
                "$ref": "#/components/schemas/Pet"
              }
            }
          }
        }
      },
      "default": {
        "description": "error payload",
        "content": {
          "text/html": {
            "schema": {
              "$ref": "#/components/schemas/ErrorModel"
            }
          }
        }
      }
    }
  },
  "parameters": [
    {
      "name": "id",
      "in": "path",
      "description": "ID of pet to use",
      "required": true,
      "schema": {
        "type": "array",
        "items": {
          "type": "string"
        }
      },
      "style": "simple"
    }
  ]
}

6、Operation Object
7. External Documentation Object
8. Parameter Object
9. Request Body Object
10. Media Type Object
11. Encoding Object
12. Responses Object
13. Response Object
14. Callback Object
15. Example Object
16. Link Object
17. Header Object
18. Tag Object
19. Reference Object
20. Schema Object

4、示例

 类似资料:

相关阅读

相关文章

相关问答