什么是 OpenAPI 规范?

OpenAPI 规范 (OAS) 定义了一个标准的、与编程语言无关的 HTTP API 接口描述,允许人类和计算机在无需访问源代码、其他文档或检查网络流量的情况下发现和理解服务的 功能。当通过 OpenAPI 正确定义时,消费者可以使用最少的实现逻辑来理解和交互远程服务。类似于接口描述对较低级别编程所做的事情,OpenAPI 规范消除了调用服务的猜测。

本文档的状态

此规范的真相来源是上面引用的 HTML 文件,即“此版本”。

1. OpenAPI 规范

本文档中的关键词“ 必须 ”、“ 禁止 ”、“ 必需 ”、“ ”、“ 不应 ”、“ 应该 ”、“ 不应该 ”、“ 推荐 ”、“ 不推荐 ”、“ 可能 ”和“ 可选 ”应按 BCP 14 [ RFC2119 ] [ RFC8174 ] 中的描述进行解释,当且仅当它们以全部大写字母出现时,如这里所示。

本文档根据 Apache 许可证 2.0 版 获得许可。

2. 简介

OpenAPI 规范 (OAS) 定义了一个标准的、与语言无关的 RESTful API 接口,允许人类和计算机在无需访问源代码、文档或通过网络流量检查的情况下发现和理解服务的 功能。当正确定义时,消费者可以使用最少的实现逻辑来理解和交互远程服务。

然后,OpenAPI 定义可用于文档生成工具显示 API、代码生成工具以各种编程语言生成服务器和客户端、测试工具以及许多其他用例。

定义或描述 API 的文档(或一组文档)。OpenAPI 定义使用并符合 OpenAPI 规范。

路径模板是指使用由花括号 ({}) 分隔的模板表达式来标记 URL 路径的一部分以使用路径参数替换。

路径中的每个模板表达式 必须 对应于包含在 路径项 本身和/或路径项的每个 操作 中的路径参数。

3.3 媒体类型

媒体类型定义分散在多个资源中。媒体类型定义 应该 符合 [ RFC6838 ]。

一些可能的媒体类型定义示例

  text/plain; charset=utf-8
  application/json
  application/vnd.github+json
  application/vnd.github.v3+json
  application/vnd.github.v3.raw+json
  application/vnd.github.v3.text+json
  application/vnd.github.v3.html+json
  application/vnd.github.v3.full+json
  application/vnd.github.v3.diff
  application/vnd.github.v3.patch

3.4 HTTP 状态码

HTTP 状态码用于指示执行操作的状态。可用状态码由 [ RFC7231 ] 第 6 节 定义,已注册的状态码列在 IANA 状态码注册表 中。

4. 规范

OpenAPI 规范使用 语义版本 2.0.0 (semver) 进行版本控制,并遵循 semver 规范。

semver 的 major . minor 部分(例如 3.0 必须 指定 OAS 功能集。通常, .patch 版本用于解决本文档中的错误,而不是功能集。支持 OAS 3.0 的工具 应该 兼容所有 OAS 3.0.* 版本。工具 不应该 考虑补丁版本,例如不区分 3.0.0 3.0.1

OpenAPI 规范的每个新次要版本 必须 允许任何针对规范的先前次要版本(在同一主要版本内)有效的 OpenAPI 文档,更新到新的规范版本,并具有等效的语义。此类更新 必须 仅需要将 openapi 属性更改为新的次要版本。

例如,有效的 OpenAPI 3.0.2 文档,在将其 openapi 属性更改为 3.1.0 后, 必须 成为有效的 OpenAPI 3.1.0 文档,在语义上等效于原始的 OpenAPI 3.0.2 文档。OpenAPI 规范的新次要版本 必须 编写以确保这种形式的向后兼容性。

与 OAS 3.*.* 兼容的 OpenAPI 文档包含一个必需的 openapi 字段,用于指定其使用的 OAS 的语义版本。(OAS 2.0 文档包含一个名为 swagger 且值为 "2.0" 的顶级版本字段。)

4.2 格式

符合 OpenAPI 规范的 OpenAPI 文档本身是一个 JSON 对象,可以以 JSON YAML 格式表示。

例如,如果一个字段具有数组值,则将使用 JSON 数组表示形式

"field" : [ 1 , 2 , 3 ]

规范中的所有字段名称都 区分大小写 。这包括用作映射中键的所有字段,除非明确指出键 不区分大小写

模式公开两种类型的字段:固定字段,具有声明的名称;模式字段,为字段名称声明正则表达式模式。

模式字段 必须 在包含的对象中具有唯一的名称。

为了保留在 YAML 和 JSON 格式之间进行双向转换的能力, YAML 1.2 版本 建议 与一些额外的约束一起使用。

  • 标签 必须 限于 JSON Schema 规则集 允许的标签。
  • YAML 映射中使用的键 必须 限于标量字符串,如 YAML Failsafe 模式规则集 所定义。
  • 注意: 虽然 API 可以通过 YAML 或 JSON 格式的 OpenAPI 文档来定义,但 API 请求和响应主体以及其他内容不需要是 JSON 或 YAML。

    4.3 文档结构

    OpenAPI 文档 可以 由单个文档组成,也可以根据用户的意愿划分为多个相互关联的部分。在后一种情况下, $ref 字段 必须 用于规范中引用这些部分,如下面的 JSON Schema 定义所示。

    建议 将根 OpenAPI 文档命名为: openapi.json openapi.yaml

    4.4 数据类型

    OAS 中的原始数据类型基于 JSON Schema 规范 Wright 草案 00 支持的类型。请注意, integer 作为一种类型也受支持,并且被定义为没有小数部分或指数部分的 JSON 数字。 null 不支持作为类型(有关替代解决方案,请参阅 nullable )。使用 模式对象 定义模型,它是由 JSON Schema 规范 Wright 草案 00 扩展的子集。

    基元具有一个可选的修饰符属性: format 。OAS 使用多种已知的格式来详细定义正在使用的类型。但是,为了支持文档需求, format 属性是一个开放的 string 值属性,可以具有任何值。即使未在此规范中定义,也可以使用诸如 "email" "uuid" 等格式。 可以 。没有伴随 format 属性的类型遵循 JSON Schema 中的类型定义。不识别特定 format 的工具 可以 默认回退到仅使用 type ,就好像未指定 format 一样。

    OAS 定义的格式为

    4.5 富文本格式化

    在整个规范中, description 字段都被注释为支持 [ CommonMark ] markdown 格式。在 OpenAPI 工具呈现富文本时, 必须 至少支持 [ CommonMark-0.27 ] 中描述的 markdown 语法。工具 可以 选择忽略某些 CommonMark 功能以解决安全问题。

    4.6 URL 中的相对引用

    除非另有说明,否则所有作为 URL 的属性 可以 是 [ RFC3986 ] 第 4.2 节 中定义的相对引用。使用 服务器对象 中定义的 URL 作为基本 URI 解析相对引用。

    $ref 中使用的相对引用根据 JSON 引用 进行处理,使用当前文档的 URL 作为基本 URI。另请参阅 引用对象

    4.7 模式

    在下述说明中,如果一个字段没有被明确 要求 或用 必须 或 应该 描述,则可以认为它是 可选的。

    这是 OpenAPI 文档 的根文档对象。

    4.7.1.1 固定字段
    openapi 要求 。此字符串 必须 是 OpenAPI 文档使用的 语义版本号 ,表示 OpenAPI 规范版本 openapi 字段 应该 被工具规范和客户端用来解释 OpenAPI 文档。这与 API info.version 字符串 无关 要求 。提供有关 API 的元数据。元数据 可以 根据需要由工具使用。 servers [ 服务器对象 ] 服务器对象的数组,提供到目标服务器的连接信息。如果未提供 servers 属性或为空数组,则默认值为一个 服务器对象 ,其 url 值为 / paths 要求 。API 可用的路径和操作。 components 用于保存规范中各种模式的元素。 security [ 安全需求对象 ] 声明可以在整个 API 中使用哪些安全机制。值的列表包含可以使用的替代安全需求对象。只需满足安全需求对象之一即可授权请求。各个操作可以覆盖此定义。要使安全性可选,可以在数组中包含一个空的安全需求 ( {} )。 [ 标签对象 ] 规范中使用的标签列表,以及其他元数据。标签的顺序可以用来反映解析工具对它们的顺序。并非 操作对象 使用的所有标签都必须声明。未声明的标签 可以 随机组织或基于工具的逻辑组织。列表中的每个标签名称 必须唯一。 externalDocs 外部文档对象 其他外部文档。

    此对象 可以使用 规范扩展 进行扩展。

    4.7.2 Info 对象

    该对象提供有关 API 的元数据。元数据 可以根据需要由客户端使用,并且 可以在编辑或文档生成工具中为了方便起见而显示。

    4.7.2.1 固定字段
    "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://apache.ac.cn/licenses/LICENSE-2.0.html" "version" : "1.0.1"
    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://apache.ac.cn/licenses/LICENSE-2.0.html
    version: 1.0.1
    

    公开 API 的联系信息。

    "name" : "API Support" , "url" : "http://www.example.com/support" , "email" : "support@example.com"
    name: API Support
    url: http://www.example.com/support
    email: support@example.com
    

    公开 API 的许可证信息。

    必需 。目标主机的 URL。此 URL 支持服务器变量,并且 可以 是相对的,以指示主机位置相对于 OpenAPI 文档所在的服务器位置。当变量在 { 括号 } 中命名时,将进行变量替换。 一个可选字符串,描述由 URL 指定的主机。[ CommonMark ] 语法 可以 用于富文本表示。 Map[ string , 服务器变量对象 ] 变量名称与其值之间的映射。该值用于替换服务器的 URL 模板。

    此对象 可以使用 规范扩展 进行扩展。

    4.7.5.2 Server 对象示例

    单个服务器将描述为

    "url" : "https://development.gigantic-server.com/v1" , "description" : "Development server"
    url: https://development.gigantic-server.com/v1
    description: Development server
    

    以下显示了如何描述多个服务器,例如,在 OpenAPI 对象的 servers

    "servers": [ "url": "https://development.gigantic-server.com/v1", "description": "Development server" "url": "https://staging.gigantic-server.com/v1", "description": "Staging server" "url": "https://api.gigantic-server.com/v1", "description": "Production server"
    servers:
    - url: https://development.gigantic-server.com/v1
      description: Development server
    - url: https://staging.gigantic-server.com/v1
      description: Staging server
    - url: https://api.gigantic-server.com/v1
      description: Production server
    

    以下显示了如何在服务器配置中使用变量

    "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"
    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
    

    4.7.6 Server Variable 对象

    表示用于服务器 URL 模板替换的服务器变量的对象。

    必需 。用于替换的默认值,如果 提供备选值,则 必须 发送。请注意,此行为与 Schema 对象 处理默认值的方式不同,因为在这些情况下,参数值是可选的。如果定义了 enum ,则该值 应该 存在于枚举的值中。 服务器变量的可选描述。[ CommonMark ] 语法 可以 用于富文本表示。

    此对象 可以使用 规范扩展 进行扩展。

    4.7.7 Components 对象

    保存 OAS 不同方面的可重用对象集。除非组件对象中定义的所有对象被组件对象外部的属性显式引用,否则它们对 API 不会有任何影响。

    "implicit" : { "authorizationUrl" : "http://example.org/api/oauth/dialog" , "scopes" : { "write:pets" : "modify pets in your account" , "read:pets" : "read your pets"
    components:
      schemas:
        GeneralError:
          type: object
          properties:
            code:
              type: integer
              format: int32
            message:
              type: string
        Category:
          type: object
          properties:
              type: integer
              format: int64
            name:
              type: string
          type: object
          properties:
              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
    

    保存到各个端点及其操作的相对路径。路径附加到来自 Server 对象 的 URL,以构造完整的 URL。由于 ACL 约束 ,路径 可以 为空。

    4.7.8.1 模式化字段
    "/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"
    /pets:
        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'
    

    描述单个路径上可用的操作。由于 ACL 约束 ,路径项 可以 为空。路径本身仍然暴露给文档查看器,但他们将不知道哪些操作和参数可用。

    4.7.9.1 固定字段
    "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" 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

    描述路径上的单个 API 操作。

    操作 ID 用于标识操作的唯一字符串。ID 必须 在 API 中描述的所有操作中唯一。operationId 值 区分大小写 。工具和库 可以 使用 operationId 唯一地标识操作,因此, 建议 遵循常见的编程命名约定。 [ 参数对象 | 引用对象 ] 适用于此操作的参数列表。如果参数已在 路径项 中定义,则新定义将覆盖它,但永远不会删除它。列表 不得 包含重复的参数。唯一参数由 名称 位置 的组合定义。该列表可以使用 引用对象 链接到在 OpenAPI 对象的 components/parameters 中定义的参数。 请求体对象 | 引用对象 适用于此操作的请求体。 requestBody 仅支持 HTTP 方法,其中 HTTP 1.1 规范 [ RFC7231 ] 第 4.3.1 节 已明确定义了请求体的语义。在 HTTP 规范含糊不清的其他情况下,使用者 必须 忽略 requestBody 必需 。执行此操作时返回的可能响应列表。 Map[ string , 回调对象 | 引用对象 ] 与父操作相关的可能带外回调的映射。键是回调对象的唯一标识符。映射中的每个值都是一个 回调对象 ,它描述了 API 提供程序可能发起的请求以及预期的响应。 声明此操作已弃用。使用者 应该 避免使用已声明的操作。默认值为 false 。 [ 安全需求对象 ] 声明哪些安全机制可用于此操作。值列表包括可使用的替代安全需求对象。只需要满足安全需求对象之一即可授权请求。要使安全可选,可以在数组中包含一个空的安全需求 ( {} )。此定义覆盖任何已声明的顶级 security 。要删除顶级安全声明,可以使用空数组。 [ 服务器对象 ] 服务此操作的替代 server 数组。如果在路径项对象或根级别指定了替代 server 对象,则此值将覆盖它。

    此对象 可以使用 规范扩展 进行扩展。

    4.7.10.2 Operation 对象示例
    "tags" : [ "pet" "summary" : "Updates a pet in the store with form data" , "operationId" : "updatePetWithForm" , "parameters" : [ "name" : "petId" , "in" : "path" , "description" : "ID of pet that needs to be updated" , "required" : true , "schema" : { "type" : "string" "requestBody" : { "content" : { "application/x-www-form-urlencoded" : { "schema" : { "type" : "object" , "properties" : { "name" : { "description" : "Updated name of the pet" , "type" : "string" "status" : { "description" : "Updated status of the pet" , "type" : "string" "required" : [ "status" ] "responses" : { "200" : { "description" : "Pet updated." , "content" : { "application/json" : { } , "application/xml" : { } "405" : { "description" : "Method Not Allowed" , "content" : { "application/json" : { } , "application/xml" : { } "security" : [ "petstore_auth" : [ "write:pets" , "read:pets"
    tags:
    - pet
    summary: Updates a pet in the store with form data
    operationId: updatePetWithForm
    parameters:
    - name: petId
      in: path
      description: ID of pet that needs to be updated
      required: true
      schema:
        type: string
    requestBody:
      content:
        'application/x-www-form-urlencoded':
          schema:
           properties:
              name:
                description: Updated name of the pet
                type: string
              status:
                description: Updated status of the pet
                type: string
           required:
             - status
    responses:
      '200':
        description: Pet updated.
        content:
          'application/json': {}
          'application/xml': {}
      '405':
        description: Method Not Allowed
        content:
          'application/json': {}
          'application/xml': {}
    security:
    - petstore_auth:
      - write:pets
      - read:pets
    

    允许引用外部资源以获取扩展文档。

    in 字段指定了四个可能的参数位置

  • path - 与 路径模板 一起使用,其中参数值实际上是操作 URL 的一部分。这并不包括 API 的主机或基本路径。例如,在 /items/{itemId} 中,路径参数是 itemId
  • query - 附加到 URL 的参数。例如,在 /items?id=### 中,查询参数是 id
  • header - 作为请求的一部分预期的自定义标头。请注意,[ RFC7230 ] 第 22 页 指出标头名称不区分大小写。
  • cookie - 用于将特定的 cookie 值传递给 API。
  • 4.7.12.2 固定字段
    必需 。参数的名称。参数名称 区分大小写
    • 如果 in "path" ,则 name 字段 必须 对应于 路径 字段中 路径对象 中出现的模板表达式。有关更多信息,请参阅 路径模板
    • 如果 in "header" 并且 name 字段是 "Accept" "Content-Type" "Authorization" ,则 忽略参数定义。
    • 在所有其他情况下, name 对应于 in 属性使用的参数名称。
    必需 。参数的位置。可能的值为 "query" "header" "path" "cookie" description 参数的简要描述。这可能包含使用示例。[ CommonMark ] 语法 可以 用于富文本表示。 required 确定此参数是否为必填。如果 参数位置 "path" ,则此属性为 必需 ,其值 必须 true 。否则, 可以 包含该属性,其默认值为 false deprecated 指定参数已弃用,并且 应该 停止使用。默认值为 false allowEmptyValue 设置传递空值参数的能力。这仅对 query 参数有效,并允许发送具有空值的参数。默认值为 false 。如果使用了 style ,并且如果行为为 n/a (无法序列化),则 忽略 allowEmptyValue 的值。 不建议 使用此属性,因为它可能会在以后的修订版中删除。

    参数序列化规则以两种方式之一指定。对于更简单的场景, schema style 可以描述参数的结构和语法。

    style 根据参数值的类型描述如何序列化参数值。默认值(基于 in 的值):对于 query - form ;对于 path - simple ;对于 header - simple ;对于 cookie - form explode 当此值为 true 时,类型为 array object 的参数值会为数组的每个值或映射的键值对生成单独的参数。对于其他类型的参数,此属性无效。当 style form 时,默认值为 true 。对于所有其他样式,默认值为 false allowReserved 确定参数值 是否应该 允许保留字符,如[ RFC3986 ] 第 2.2 节 :/?#[]@!$&'()*+,;= 包含在内,无需进行百分比编码。此属性仅适用于 in 值为 query 的参数。默认值为 false schema Schema 对象 | 引用对象 定义用于参数的类型的模式。 example 参数潜在值的示例。如果存在,则示例 应该 与指定的模式和编码属性匹配。 example 字段与 examples 字段互斥。此外,如果引用包含示例的 schema ,则 example 覆盖 模式提供的示例。为了表示无法以 JSON 或 YAML 自然表示的媒体类型的示例,字符串值可以包含示例,并在必要时进行转义。 examples Map[ string , 示例对象 | 引用对象 ] 参数潜在值的示例。每个示例 应该 包含以参数编码中指定的正确格式的值。 examples 字段与 example 字段互斥。此外,如果引用包含示例的 schema ,则 examples 覆盖 模式提供的示例。

    对于更复杂的场景, content 属性可以定义参数的媒体类型和模式。参数 必须 包含 schema 属性或 content 属性,但不能同时包含两者。当与 schema 对象一起提供 example examples 时,示例 必须 遵循参数规定的序列化策略。

    primitive array object query cookie [ RFC6570 ] 第 3.2.8 节 定义的表单样式参数。此选项用 OpenAPI 2.0 中的 csv (当 explode 为 false 时)或 multi (当 explode 为 true 时)值替换 collectionFormat 。 simple array path header [ RFC6570 ] 第 3.2.2 节 定义的简单样式参数。此选项用 OpenAPI 2.0 中的 csv 值替换 collectionFormat 。 spaceDelimited array query 以空格分隔的数组值。此选项替换 OpenAPI 2.0 中等于 ssv collectionFormat 。 pipeDelimited array query 以管道分隔的数组值。此选项替换 OpenAPI 2.0 中等于 pipes collectionFormat 。 deepObject object query 提供了一种使用表单参数呈现嵌套对象。
    4.7.12.4 样式示例

    假设名为 color 的参数具有以下值之一

       string -> "blue"
       array -> ["blue","black","brown"]
       object -> { "R": 100, "G": 200, "B": 150 }
    

    下表显示了每个值的渲染差异示例。

    style explode empty array object "in": "header", "description": "token to be passed as a header", "required": true, "schema": { "type": "array", "items": { "type": "integer", "format": "int64" "style": "simple"
    name: token
    in: header
    description: token to be passed as a header
    required: true
    schema:
      type: array
      items:
        type: integer
        format: int64
    style: simple
    

    字符串值的路径参数

    "name": "username", "in": "path", "description": "username to fetch", "required": true, "schema": { "type": "string"
    name: username
    in: path
    description: username to fetch
    required: true
    schema:
      type: string
    

    字符串值的可选查询参数,通过重复查询参数允许多个值

    "name": "id", "in": "query", "description": "ID of the object to fetch", "required": false, "schema": { "type": "array", "items": { "type": "string" "style": "form", "explode": true
    name: id
    in: query
    description: ID of the object to fetch
    required: false
    schema:
      type: array
      items:
        type: string
    style: form
    explode: true
    

    自由格式查询参数,允许特定类型的未定义参数

    "in": "query", "name": "freeForm", "schema": { "type": "object", "additionalProperties": { "type": "integer" "style": "form"
    in:
    
    
    
    
        
     query
    name: freeForm
    schema:
      type: object
      additionalProperties:
        type: integer
    style: form
    

    使用content定义序列化的复杂参数

    "in": "query", "name": "coordinates", "content": { "application/json": { "schema": { "type": "object", "required": [ "lat", "long" "properties": { "lat": { "type": "number" "long": { "type": "number"
    in: query
    name: coordinates
    content:
      application/json:
        schema:
          type: object
          required:
            - lat
            - long
          properties:
              type: number
            long:
              type: number
    

    4.7.13 Request Body 对象

    描述单个请求正文。

    content Map[ string , 媒体类型对象 ] 必需 。请求正文的内容。键是媒体类型或媒体类型范围,请参阅[ RFC7231 ] 附录 D ,值描述它。对于匹配多个键的请求,只有最具体的键适用。例如,text/plain 覆盖 text/* required 确定请求中是否需要请求正文。默认为 false

    此对象 可以使用 规范扩展 进行扩展。

    4.7.13.2 Request Body 示例

    具有引用模型定义的请求正文。

    "description" : "user to add to the system" , "content" : { "application/json" : { "schema" : { "$ref" : "#/components/schemas/User" "examples" : { "user" : { "summary" : "User Example" , "externalValue" : "http://foo.bar/examples/user-example.json" "application/xml" : { "schema" : { "$ref" : "#/components/schemas/User" "examples" : { "user" : { "summary" : "User example in XML" , "externalValue" : "http://foo.bar/examples/user-example.xml" "text/plain" : { "examples" : { "user" : { "summary" : "User example in Plain text" , "externalValue" : "http://foo.bar/examples/user-example.txt" "*/*" : { "examples" : { "user" : { "summary" : "User example in other format" , "externalValue" : "http://foo.bar/examples/user-example.whatever"
    description: user to add to the system
    content:
      'application/json':
        schema:
          $ref: '#/components/schemas/User'
        examples:
          user:
            summary: User Example
            externalValue: 'http://foo.bar/examples/user-example.json'
      'application/xml':
        schema:
          $ref: '#/components/schemas/User'
        examples:
          user:
            summary: User Example in XML
            externalValue: 'http://foo.bar/examples/user-example.xml'
      'text/plain':
        examples:
          user:
            summary: User example in text plain format
            externalValue: 'http://foo.bar/examples/user-example.txt'
      '*/*':
        examples:
          user:
            summary: User example in other format
            externalValue: 'http://foo.bar/examples/user-example.whatever'
    

    作为字符串值数组的正文参数

    "description": "user to add to the system", "content": { "text/plain": { "schema": { "type": "array", "items": { "type": "string"
    description: user to add to the system
    required: true
    content:
      text/plain:
        schema:
          type: array
          items:
            type: string
    

    4.7.14 Media Type 对象

    每个媒体类型对象都为其键标识的媒体类型提供模式和示例。

    example 媒体类型的示例。示例对象 应该 采用媒体类型指定的正确格式。 example 字段与 examples 字段互斥。此外,如果引用包含示例的 schema ,则 example 覆盖 模式提供的示例。 examples Map[ string , 示例对象 | 引用对象 ] 媒体类型的示例。每个示例对象 应该 匹配媒体类型和指定的模式(如果存在)。 examples 字段与 example 字段互斥。此外,如果引用包含示例的 schema ,则 examples 覆盖 模式提供的示例。 encoding Map[ string , 编码对象 ] 属性名称与其编码信息之间的映射。键(即属性名称) 必须 在模式中作为属性存在。编码对象 仅在媒体类型为 multipart application/x-www-form-urlencoded 时应用于 requestBody 对象。

    此对象 可以使用 规范扩展 进行扩展。

    4.7.14.2 Media Type 示例
    "application/json" : { "schema" : { "$ref" : "#/components/schemas/Pet" "examples" : { "cat" : { "summary" : "An example of a cat" , "value" : "name" : "Fluffy" , "petType" : "Cat" , "color" : "White" , "gender" : "male" , "breed" : "Persian" "dog" : { "summary" : "An example of a dog with a cat's name" , "value" : { "name" : "Puma" , "petType" : "Dog" , "color" : "Black" , "gender" : "Female" , "breed" : "Mixed" "frog" : { "$ref" : "#/components/examples/frog-example"
    application/json:
      schema:
        $ref: "#/components/schemas/Pet"
      examples:
          summary: An example of a cat
          value:
            name: Fluffy
            petType: Cat
            color: White
            gender: male
            breed: Persian
          summary: An example of a dog with a cat's name
          value:
            name: Puma
            petType: Dog
            color: Black
            gender: Female
            breed: Mixed
        frog:
          $ref: "#/components/examples/frog-example"
    

    与 2.0 规范相比,OpenAPI 中的文件输入/输出内容使用与任何其他模式类型相同的语义进行描述。具体来说

    # content transferred with base64 encoding
    schema:
      type: string
      format: base64
    
    # content transferred in binary (octet-stream):
    schema:
      type: string
      format: binary
    

    这些示例适用于文件上传的输入有效负载或响应有效负载。

    用于在POST操作中提交文件的requestBody可能如下例所示

    requestBody:
      content:
        application/octet-stream:
          schema:
            # a binary file of any type
            type: string
            format: binary
    

    此外,可以指定特定的媒体类型MAY

    # multiple, specific media types may be specified:
    requestBody:
      content:
          # a binary file of type png or jpeg
        'image/jpeg':
          schema:
            type: string
            format: binary
        'image/png':
          schema:
            type: string
            format: binary       
    

    要上传多个文件,MUST使用multipart媒体类型

    requestBody:
      content:
        multipart/form-data:
          schema:
            properties:
              # The property name 'file' will be used for all files.
              file:
                type: array
                items:
                  type: string
                  format: binary
    

    要使用[ RFC1866 ]中的表单 URL 编码提交内容,可以使用以下定义

    requestBody:
      content:
        application/x-www-form-urlencoded:
          schema:
            type: object
            properties:
                type: string
                format: uuid
              address:
                # complex types are stringified to support RFC 1866
                type: object
                properties: {}
    

    在此示例中,传递到服务器时,requestBody中的内容MUST根据[RFC1866]进行字符串化。此外,address字段的复杂对象也将被字符串化。

    application/x-www-form-urlencoded内容类型中传递复杂对象时,此类属性的默认序列化策略在Encoding Objectstyle属性中描述为form

    4.7.14.5 multipart 内容的特殊注意事项

    multipart/form-data 用作将请求主体传输到操作的 Content-Type 很常见。与2.0相比,当使用 multipart 内容时, REQUIRED 使用 schema 来定义操作的输入参数。这支持复杂结构以及支持多种文件上传的机制。

    在传递 multipart 类型时,可以使用边界 MAY 来分隔正在传输的内容部分——因此,为 multipart 定义了以下默认 Content-Type

  • 如果属性是原始类型,或原始值的数组,则默认 Content-Type 为 text/plain
  • 如果属性是复杂类型,或复杂值的数组,则默认 Content-Type 为 application/json
  • 如果属性是 type: string format: binary format: base64 (也称为文件对象),则默认 Content-Type 为 application/octet-stream
  • requestBody:
      content:
        multipart/form-data:
          schema:
            type: object
            properties:
                type: string
                format: uuid
              address:
                # default Content-Type for objects is `application/json`
                type: object
                properties: {}
              profileImage:
                # default Content-Type for string/binary is `application/octet-stream`
                type: string
                format: binary
              children:
                # default Content-Type for arrays is based on the `inner` type (text/plain here)
                type: array
                items:
                  type: string
              addresses:
                # default Content-Type for arrays is based on the `inner` type (object shown, so `application/json` in this example)
                type: array
                items:
                  type: '#/components/schemas/Address'
    

    引入了一个encoding属性,用于控制multipart请求主体部分的序列化。此属性适用于multipartapplication/x-www-form-urlencoded请求主体。

    应用于单个模式属性的单个编码定义。

    contentType 用于编码特定属性的 Content-Type。默认值取决于属性类型:对于 format binary string application/octet-stream ;对于其他原始类型 – text/plain ;对于 object - application/json ;对于 array – 默认值基于内部类型定义。该值可以是特定的媒体类型(例如 application/json )、通配符媒体类型(例如 image/* )或这两种类型的逗号分隔列表。 headers Map[ string , 头部对象 | 引用对象 ] 一个映射,允许提供其他信息作为标头,例如 Content-Disposition Content-Type 单独描述,并且 SHALL 在本节中被忽略。如果请求主体媒体类型不是 multipart ,则此属性 SHALL 被忽略。 style 根据其类型描述特定属性值将如何序列化。有关 style 属性的详细信息,请参阅 Parameter Object 。行为遵循与 query 参数相同的值,包括默认值。如果请求主体媒体类型不是 application/x-www-form-urlencoded ,则此属性 SHALL 被忽略。 explode 如果此值为 true,则类型为 array object 的属性值会为数组的每个值或映射的键值对生成单独的参数。对于其他类型的属性,此属性无效。当 style form 时,默认值为 true 。对于所有其他样式,默认值为 false 。如果请求主体媒体类型不是 application/x-www-form-urlencoded ,则此属性 SHALL 被忽略。 allowReserved 确定参数值 SHOULD 是否允许包含[ RFC3986 ] 第 2.2 节 中定义的保留字符 :/?#[]@!$&'()*+,;= ,而无需进行百分比编码。默认值为 false 。如果请求主体媒体类型不是 application/x-www-form-urlencoded ,则此属性 SHALL 被忽略。

    此对象 可以使用 规范扩展 进行扩展。

    4.7.15.2 Encoding 对象示例
    requestBody:
      content:
        multipart/mixed:
          schema:
            type: object
            properties:
                # default is text/plain
                type: string
                format: uuid
              address:
                # default is application/json
                type: object
                properties: {}
              historyMetadata:
                # need to declare XML format!
                description: metadata in XML format
                type: object
                properties: {}
              profileImage:
                # default is application/octet-stream, need to declare an image type only!
                type: string
                format: binary
          encoding:
            historyMetadata:
              # require XML Content-Type in utf-8 encoding
              contentType: application/xml; charset=utf-8
            profileImage:
              # only accept png/jpeg
              contentType: image/png, image/jpeg
              headers:
                X-Rate-Limit-Limit:
                  description: The number of allowed requests in the current period
                  schema:
                    type: integer
    

    操作的预期响应的容器。该容器将 HTTP 响应代码映射到预期响应。

    文档不一定需要涵盖所有可能的 HTTP 响应代码,因为它们可能事先未知。但是,文档需要涵盖成功操作响应和任何已知错误。

    default MAY 用作规范中未单独涵盖的所有 HTTP 代码的默认响应对象。

    Responses Object MUST 至少包含一个响应代码,并且 SHOULD 是成功操作调用的响应。

    HTTP 状态代码 Response Object | Reference Object 任何 HTTP 状态代码 都可以用作属性名称,但每个代码只有一个属性,以描述该 HTTP 状态代码的预期响应。 Reference Object 可以链接到 OpenAPI Object 的 components/responses 部分中定义的响应。为了在 JSON 和 YAML 之间兼容,此字段 MUST 用引号括起来(例如,“200”)。要定义响应代码范围,此字段 MAY 包含大写通配符 X 。例如, 2XX 表示 [200-299] 之间的所有响应代码。仅允许以下范围定义: 1XX 2XX 3XX 4XX 5XX 。如果使用显式代码定义响应,则该显式代码定义优先于该代码的范围定义。

    此对象 可以使用 规范扩展 进行扩展。

    4.7.16.3 Responses 对象示例

    成功操作的 200 响应和其他响应的默认响应(暗示错误)

    "200" : { "description" : "a pet to be returned" , "content" : { "application/json" : { "schema" : { "$ref" : "#/components/schemas/Pet" "default" : { "description" : "Unexpected error" , "content" : { "application/json" : { "schema" : { "$ref" : "#/components/schemas/ErrorModel"
    '200':
      description: a pet to be returned
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Pet'
    default:
      description: Unexpected error
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorModel'
    

    描述 API 操作的单个响应,包括基于响应的操作的设计时静态 links

    headers Map[ string , 头部对象 | 引用对象 ] 将标头名称映射到其定义。[ RFC7230 ] 第 22 页 指出标头名称不区分大小写。如果使用名称 "Content-Type" 定义响应标头,则 SHALL 被忽略。 content Map[ string , 媒体类型对象 ] 包含潜在响应有效负载描述的映射。键是媒体类型或媒体类型范围,请参阅[ RFC7231 ] 附录 D ,值对其进行描述。对于匹配多个键的响应,仅适用最具体的键。例如,text/plain 覆盖 text/* links Map[ string , 链接对象 | 引用对象 ] 可以从响应中跟随的操作链接的映射。映射的键是链接的简称,遵循 Component Objects 名称的命名约束。

    此对象 可以使用 规范扩展 进行扩展。

    4.7.17.2 Response 对象示例

    复杂类型数组的响应

    "description" : "A complex object array response" , "content" : { "application/json" : { "schema" : { "type" : "array" , "items" : { "$ref" : "#/components/schemas/VeryComplexType"
    description: A complex object array response
    content:
      application/json:
        schema:
          type: array
          items:
            $ref: '#/components/schemas/VeryComplexType'
    

    带有字符串类型的响应

    "description": "A simple string response", "content": { "text/plain": { "schema": { "type": "string"
    description: A simple string response
    content:
      text/plain:
        schema:
          type: string
    

    带有标头的纯文本响应

    "description": "A simple string response", "content": { "text/plain": { "schema": { "type": "string", "example": "whoa!" "headers": { "X-Rate-Limit-Limit": { "description": "The number of allowed requests in the current period", "schema": { "type": "integer" "X-Rate-Limit-Remaining": { "description": "The number of remaining requests in the current period", "schema": { "type": "integer" "X-Rate-Limit-Reset": { "description": "The number of seconds left in the current period", "schema": { "type": "integer"
    description: A simple string response
    content:
      text/plain:
        schema:
          type: string
        example: 'whoa!'
    headers:
      X-Rate-Limit-Limit:
        description: The number of allowed requests in the current period
        schema:
          type: integer
      X-Rate-Limit-Remaining:
        description: The number of remaining requests in the current period
        schema:
          type: integer
      X-Rate-Limit-Reset:
        description: The number of seconds left in the current period
        schema:
          type:
    
    
    
    
        
     integer
    

    没有返回值的响应

    "description": "object created"
    description: object created
    

    与父操作相关的可能带外回调的映射。映射中的每个值都是一个 Path Item Object ,它描述了一组可能由 API 提供者发起的请求以及预期的响应。用于识别路径项对象的键值是一个在运行时计算的表达式,用于识别要用于回调操作的 URL。

    4.7.18.1 模式化字段

    此对象 可以使用 规范扩展 进行扩展。

    4.7.18.2 键表达式

    用于识别 Path Item Object 的键是 运行时表达式 ,它可以在运行时 HTTP 请求/响应的上下文中计算,以识别要用于回调请求的 URL。一个简单的示例可能是 $request.body#/url 。但是,使用 运行时表达式 可以访问完整的 HTTP 消息。这包括访问 JSON 指针[ RFC6901 ]可以引用的正文的任何部分。

    例如,给定以下 HTTP 请求

    POST /subscribe/myevent?queryUrl=http://clientdomain.com/stillrunning HTTP/1.1
    Host: example.org
    Content-Type: application/json
    Content-Length: 187
      "failedUrl" : "http://clientdomain.com/failed",
      "successUrls" : [
        "http://clientdomain.com/fast",
        "http://clientdomain.com/medium",
        "http://clientdomain.com/slow"
    201 Created
    Location: http://example.org/subscription/1
    

    以下示例显示了各种表达式的计算方式,假设回调操作具有名为eventType的路径参数和名为queryUrl的查询参数。

    4.7.18.3 Callback 对象示例

    以下示例使用用户提供的 queryUrl 查询字符串参数来定义回调 URL。这是一个如何使用回调对象来描述与订阅操作一起使用的 WebHook 回调以启用 WebHook 注册的示例。

    myCallback:
      '{$request.query.queryUrl}':
        post:
          requestBody:
            description: Callback payload
            content:
              'application/json':
                schema:
                  $ref: '#/components/schemas/SomePayload'
          responses:
            '200':
              description: callback successfully processed
    

    以下示例显示了一个回调,其中服务器是硬编码的,但查询字符串参数是从请求主体中的idemail属性填充的。

    transactionCallback:
      'http://notificationServer.com?transactionId={$request.body#/id}&email={$request.body#/email}':
        post:
          requestBody:
            description: Callback payload
            content:
              'application/json':
                schema:
                  $ref: '#/components/schemas/SomePayload'
          responses:
            '200':
              description: callback successfully processed
    
    value 嵌入的文字示例。 value 字段和 externalValue 字段是互斥的。要表示 JSON 或 YAML 中无法自然表示的媒体类型的示例,请使用字符串值包含示例,并在必要时进行转义。 externalValue 指向文字示例的 URL。这提供了引用 JSON 或 YAML 文档中难以包含的示例的功能。 value 字段和 externalValue 字段是互斥的。

    此对象 可以使用 规范扩展 进行扩展。

    在所有情况下,示例值都应与其关联值的类型模式兼容。工具实现 MAY 选择自动验证兼容性,并在不兼容时拒绝示例值。

    4.7.19.2 Example 对象示例

    在请求主体中

    requestBody:
      content:
        'application/json':
          schema:
            $ref: '#/components/schemas/Address'
          examples:
              summary: A foo example
              value: {"foo": "bar"}
              summary: A bar example
              value: {"bar": "baz"}
        'application/xml':
          examples:
            xmlExample:
              summary: This is an example in XML
              externalValue: 'http://example.org/examples/address-example.xml'
        'text/plain':
          examples:
            textExample:
              summary: This is a text example
              externalValue: 'http://foo.bar/examples/address-example.txt'
    
    parameters:
      - name: 'zipCode'
        in: 'query'
        schema:
          type: 'string'
          format: 'zip-code'
        examples:
          zip-example:
            $ref: '#/components/examples/zip-example'
    
    responses:
      '200':
        description: your car appointment has been booked
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SuccessResponse'
            examples:
              confirmation-success:
                $ref: '#/components/examples/confirmation-success'