Skip to content

Files

Latest commit

a05b845 · Dec 6, 2020

History

History
7504 lines (5811 loc) · 246 KB

3.0.3_CN2.md

File metadata and controls

7504 lines (5811 loc) · 246 KB

OpenAPI 规范

版本 3.0.3

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 RFC2119 RFC8174 when, and only when, they appear in all capitals, as shown here.

本文档中的关键词 "MUST"、"MUST NOT"、"REQUIRED"、"SHALL"、"SHALL NOT"、"SHOULD"、"SHOULD NOT"、"RECOMMENDED"、"NOT RECOMMENDED"、"MAY"和 "OPTIONAL", 当且仅当它们以全大写字母出现时,应按照 BCP 14 RFC2119 RFC8174 中的描述进行解释。

译者注 中文没有大小写之分, 将使用 加粗 和保留英文的方式来标出这些关键词。

This document is licensed under The Apache License, Version 2.0.

本文档遵循 The Apache License, Version 2.0 许可证.

概述 Introduction

The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic.

OpenAPI 规范 (OAS) ,是一个定义标准的、与具体编程语言无关的RESTful API的规范。 本规范使得人类和计算机都能在“不接触任何程序源代码和文档、不监控网络通信”的情况下理解一个服务的作用。 一个良好定义的 API 可以使得使用者非常轻松地理解并与之交互而不需要了解它的实现逻辑。

An OpenAPI definition can then be used by documentation generation tools to display the API, code generation tools to generate servers and clients in various programming languages, testing tools, and many other use cases.

如果您遵循 OpenAPI 规范来定义您的 API,那么您就可以 用文档生成工具来展示您的 API, 用代码生成工具来自动生成各种编程语言的服务器端和客户端的代码, 用自动测试工具进行测试等等。

目录 Table of Contents

译者注: 关于 Schema 目前没有一个很好的中文翻译, 故本文档所有出现 Schema 的地方都将不做翻译。 读者可以根据自己理解和偏好自行脑译成架构, 结构, 模型, 模式 等等中文术语。

术语 Definitions

OpenAPI文档 OpenAPI Document

A document (or set of documents) that defines or describes an API. An OpenAPI definition uses and conforms to the OpenAPI Specification.

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

路径模板化 Path Templating

Path templating refers to the usage of template expressions, delimited by curly braces ({}), to mark a section of a URL path as replaceable using path parameters.

路径模板化是指使用模板表达式将URL路径的一部分标记为可替换的, 这些可替换的部分称为路径参数。 一个模板表达式代表一个路径参数, 用大括号({})包裹。

Each template expression in the path MUST correspond to a path parameter that is included in the Path Item itself and/or in each of the Path Item's Operations.

路径中的每个模板表达式必须 (MUST) 对应一个路径参数, 该参数包含在路径项本身和(或)路径项的每个操作中。

媒体类型 Media Types

Media type definitions are spread across several resources. The media type definitions SHOULD be in compliance with RFC6838.

媒体类型定义分散于多处。 媒体类型定义应当 (SHOULD) 符合 RFC6838

Some examples of possible media type definitions:

以下是一些媒体类型定义的示例:

  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
HTTP状态码 HTTP Status Codes

The HTTP Status Codes are used to indicate the status of the executed operation. The available status codes are defined by RFC7231 and registered status codes are listed in the IANA Status Code Registry.

HTTP状态码用于表示一次请求的执行状态。 RFC7231 定义了可用的状态码, 可以在 IANA Status Code Registry 找到已经被注册的状态码的列表。

规范 Specification

版本 Versions

The OpenAPI Specification is versioned using Semantic Versioning 2.0.0 (semver) and follows the semver specification.

OpenAPI规范使用 Semantic Versioning 2.0.0 进行版本管理,并遵循semver规范。

The major.minor portion of the semver (for example 3.0) SHALL designate the OAS feature set. Typically, .patch versions address errors in this document, not the feature set. Tooling which supports OAS 3.0 SHOULD be compatible with all OAS 3.0.* versions. The patch version SHOULD NOT be considered by tooling, making no distinction between 3.0.0 and 3.0.1 for example.

semvermajor.minor (magor:主版本号, minor:次版本号)部分(例如3.0)应当( SHALL )被用来标记OAS的功能变动。 通常,.patch (patch:修订号)版本解决的是本文档中的错误,而不是功能变动。 支持 OAS 3.0 的工具应该( SHOULD )与所有 OAS 3.0.* 版本兼容。 工具不需要( ** SHOULD NOT ** )关心补丁版本的变动,例如在 3.0.03.0.1 之间对工具来说应该没有任何区别。

Each new minor version of the OpenAPI Specification SHALL allow any OpenAPI document that is valid against any previous minor version of the Specification, within the same major version, to be updated to the new Specification version with equivalent semantics. Such an update MUST only require changing the openapi property to the new minor version.

OpenAPI规范 的每一个新的次要版本都应该( SHALL )兼容同一主要版本的任何以前的次要版本的规范, 以便更新到具有同等语义的新规范版本。 次要版本的升级必须 ( MUST ) 只需要更改openapi 属性到新的次要版本即可, 不需要修改其他内容。

For example, a valid OpenAPI 3.0.2 document, upon changing its openapi property to 3.1.0, SHALL be a valid OpenAPI 3.1.0 document, semantically equivalent to the original OpenAPI 3.0.2 document. New minor versions of the OpenAPI Specification MUST be written to ensure this form of backward compatibility.

例如,一个有效的 OpenAPI 3.0.2 文档,在将其 openapi 属性更改为 3.1.0 后,将( SHALL )成为一个有效的 OpenAPI 3.1.0 文档,在语义上等同于原来的 OpenAPI 3.0.2 文档。 在制定新的次要版本时, 必须 ( MUST ) 确保这种形式的向后兼容性。

An OpenAPI document compatible with OAS 3.*.* contains a required openapi field which designates the semantic version of the OAS that it uses. (OAS 2.0 documents contain a top-level version field named swagger and value "2.0".)

与 OAS 3.*.* 兼容的OpenAPI文档包含一个必需的 openapi 字段,该字段指定了它所使用的OAS的语义版本。 (OAS 2.0 文档包含一个名为 swagger 和值为 "2.0" 的顶层版本字段。)

格式 Format

An OpenAPI document that conforms to the OpenAPI Specification is itself a JSON object, which may be represented either in JSON or YAML format.

一份符合OpenAPI规范的OpenAPI文档是一个JSON对象,可以使用JSON或YAML格式编写。

For example, if a field has an array value, the JSON array representation will be used:

例如,如果一个字段有一个数组值,将使用JSON数组表示为:

{
   "field": [ 1, 2, 3 ]
}

All field names in the specification are case sensitive. This includes all fields that are used as keys in a map, except where explicitly noted that keys are case insensitive.

规范中的所有字段名都是 区分大小写 的,这包括所有在map中作为键(key)的字段,除非明确指出键 区分大小写。

The schema exposes two types of fields: Fixed fields, which have a declared name, and Patterned fields, which declare a regex pattern for the field name.

schema定义了两种类型的字段: 固定字段(Fixed fields)和模式化字段(Patterned fields)。 固定字段的字段名是确定的,模式字段的字段名需要符合一定的格式(regex pattern)。

Patterned fields MUST have unique names within the containing object.

如果一个对象里有模式化字段(Patterned fields),那么在这个对象里的模式化字段(Patterned fields)的名字必须( MUST )唯一, 不能有重复。

In order to preserve the ability to round-trip between YAML and JSON formats, YAML version 1.2 is RECOMMENDED along with some additional constraints:

为了保持 YAML 和 JSON 格式之间的相互转换能力,推荐使用YAML 1.2 版本以及需要遵守以下一些额外的限制:

Note: While APIs may be defined by OpenAPI documents in either YAML or JSON format, the API request and response bodies and other content are not required to be JSON or YAML.

Note: 虽然API可以由OpenAPI文档以YAML或JSON格式定义,但API请求和响应体和其他内容并不是必须是JSON或YAML, 可以是任何格式。

文档结构 Document Structure

An OpenAPI document MAY be made up of a single document or be divided into multiple, connected parts at the discretion of the user. In the latter case, $ref fields MUST be used in the specification to reference those parts as follows from the JSON Schema definitions.

一个OpenAPI文档可以( MAY )由一个单一的文档组成,也可以由用户自行决定分为多个相互关联的部分(拆分成多个文档)。 在后一种情况下,必须在规范中使用$ref字段来引用那些来自 JSON Schema 定义的部分。

It is RECOMMENDED that the root OpenAPI document be named: openapi.json or openapi.yaml.

建议( RECOMMENDED )将 OpenAPI 根文档命名为:openapi.jsonopenapi.yaml

数据类型 Data Types

Primitive data types in the OAS are based on the types supported by the JSON Schema Specification Wright Draft 00. Note that integer as a type is also supported and is defined as a JSON number without a fraction or exponent part. null is not supported as a type (see nullable for an alternative solution). Models are defined using the Schema Object, which is an extended subset of JSON Schema Specification Wright Draft 00.

OAS中的原始数据类型基于JSON Schema Specification Wright Draft 00定义的类型。 整数也作为一种类型来支持,并且被定义为是没有分数或指数部分的JSON数字。 null 不是数据类型(参见nullable以获得替代解决方案)。 模型(Models)使用Schema Object来定义,它是JSON Schema Specification Wright Draft 00的扩展子集。

Primitives have an optional modifier property: format. OAS uses several known formats to define in fine detail the data type being used. However, to support documentation needs, the format property is an open string-valued property, and can have any value. Formats such as "email", "uuid", and so on, MAY be used even though undefined by this specification. Types that are not accompanied by a format property follow the type definition in the JSON Schema. Tools that do not recognize a specific format MAY default back to the type alone, as if the format is not specified.

原始类型都有一个可选的修饰符属性:format。 OAS 使用几种已知的格式来指明数据类型的具体格式。 然而,为了支持文档需求,format 属性是一个开放的字符串值属性,可以是任何值。 格式如 "email", "uuid" 等,即使本规范没有定义,也可以( MAY )使用。 没有附带 format 属性的类型遵循 JSON Schema 中的类型定义。 工具如果遇到无法识别的特定格式, 可以按默认的类型来处理,就像没有指定格式一样。

The formats defined by the OAS are:

OAS已定义的格式有:

type format Comments
integer int32 signed 32 bits
integer int64 signed 64 bits (a.k.a long)
number float
number double
string
string byte base64 encoded characters
string binary any sequence of octets
boolean
string date As defined by full-date - RFC3339
string date-time As defined by date-time - RFC3339
string password A hint to UIs to obscure input.

富文本格式 Rich Text Formatting

Throughout the specification description fields are noted as supporting CommonMark markdown formatting. Where OpenAPI tooling renders rich text it MUST support, at a minimum, markdown syntax as described by CommonMark 0.27. Tooling MAY choose to ignore some CommonMark features to address security concerns.

在整个规范中,description 字段都被注明为支持CommonMark markdown格式。 当OpenAPI工具渲染富文本时,它必须至少支持 CommonMark 0.27 所描述的markdown语法。 工具可以( MAY )选择忽略一些CommonMark的功能来解决安全问题。

相对引用 Relative References in URLs

Unless specified otherwise, all properties that are URLs MAY be relative references as defined by RFC3986. Relative references are resolved using the URLs defined in the Server Object as a Base URI.

除非另有规定,否则所有作为 URL 的属性都可以(MAY)是 RFC3986 定义的相对引用。 相对引用使用 Server Object 中定义的URL作为基础URI进行解析。

Relative references used in $ref are processed as per JSON Reference, using the URL of the current document as the base URI. See also the Reference Object.

$ref 中使用的相对引用按照 JSON Reference 处理,使用当前文档的URL作为基础URI。也请参见Reference Object

结构 Schema

In the following description, if a field is not explicitly REQUIRED or described with a MUST or SHALL, it can be considered OPTIONAL.

在下面的描述中,如果一个字段没有明确的 REQUIRED 或用 MUST 或 SHALL 来描述,它可以被认为是可选的( OPTIONAL )。

OpenAPI对象 OpenAPI Object

This is the root document object of the OpenAPI document.

这个是 OpenAPI文档 的根对象。

固定字段 Fixed Fields

Field Name Type Description
openapi string REQUIRED. This string MUST be the semantic version number of the OpenAPI Specification version that the OpenAPI document uses. The openapi field SHOULD be used by tooling specifications and clients to interpret the OpenAPI document. This is not related to the API info.version string.
info Info Object REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required.
servers [Server Object] An array of Server Objects, which provide connectivity information to a target server. If the servers property is not provided, or is an empty array, the default value would be a Server Object with a url value of /.
paths Paths Object REQUIRED. The available paths and operations for the API.
components Components Object An 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. To make security optional, an empty security requirement ({}) can be included in the array.
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.
externalDocs External Documentation Object Additional external documentation.

字段名 类型 描述
openapi string 必填. 这个字符串必须 (MUST) 符合 OpenAPI规范版本 提到的 语义版本号 的版本号。openapi 字段应该 (SHOULD) 被工具和客户端用来解释OpenAPI文档。这个值和info.version 没有 关联。
info Info对象 必填.此字段提供API相关的元数据信息。元数据可 (MAY) 由工具根据需要使用。
servers [Server对象] 这是一个Server对象数组,它记录有目标服务器的连接信息。如果没有提供servers属性或者是一个空数组,那么默认为是url值为/Server 对象
paths Paths对象 必填. API提供的访问路径和操作。
components Components对象 规范定义的各种Schema对象。
security [安全对象] 这个是关于哪些安全机制可以在整个API中使用的声明。值列表中包括可以使用的其他安全需求对象。一个请求只有最少满足其中一个安全需求对象时才能授权。个别操作可以覆盖这个定义。为了使安全机制成为可选的,可以在数组中包含一个空的安全需求({})。
tags [Tag对象] 规范所使用的标签清单,包括附加元数据。标签的顺序可以被转换工具用来决定API的顺序。不是所有被Operation 对象用到的标签都必须被声明。没有被声明的标签可能被工具按自己的逻辑处理,列表中的每个标签名都应该是唯一的。
externalDocs 外部文档对象 额外的外部文档信息, 这个对象可能会被规范扩展扩展。

Info对象 Info Object

The object provides metadata about the API. The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience.

该对象提供了关于API的元数据。如果需要的话,这些元数据可以 (MAY) 被客户使用,也可以 (MAY) 在编辑或文档生成工具中显示,以方便客户使用。

固定字段 Fixed Fields

Field Name Type Description
title string REQUIRED. The title of the API.
description string A short description of the API. CommonMark syntax MAY be used for rich text representation.
termsOfService string A URL to the Terms of Service for the API. MUST be in the format of a URL.
contact Contact Object The contact information for the exposed API.
license License Object The license information for the exposed API.
version string REQUIRED. The version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the API implementation version).

字段名 类型 描述
title string 必填. API的名称。
description string 对API的简短描述。 可以 (MAY) 用 CommonMark syntax 来呈现富文本。
termsOfService string 指向服务条款的URL地址,必须 (MUST) 是URL地址格式。
contact Contact Object API的联系信息。
license License Object API的证书信息。
version string 必填. API的版本信息 (注意:这个版本是指被本OpenAPI文档所描述的API的版本, 跟openapi属性、开放API规范版本没有任何关系).

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

Info对象例子 Info Object Example
{
  "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"
}
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
{
  "title": "宠物商店APP例子",
  "description": "这是一个宠物商店APP例子的服务端。",
  "termsOfService": "http://example.com/terms/",
  "contact": {
    "name": "API支持",
    "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"
}
title: 宠物商店APP例子
description: 这是一个宠物商店APP例子的服务端。
termsOfService: http://example.com/terms/
contact:
  name: API 支持
  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

Contact对象 Contact Object

Contact information for the exposed API.

API的联系信息

固定字段 Fixed Fields

Field Name Type Description
name string The identifying name of the contact person/organization.
url string The URL pointing to the contact information. MUST be in the format of a URL.
email string The email address of the contact person/organization. MUST be in the format of an email address.

字段名 类型 描述
name string 联系人或组织的名称。
url string 指向联系人信息的URL地址,必须 (MUST) 是URL地址格式。
email string 联系人或组织的email地址,必须 (MUST) 是email地址格式。

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

Contact对象例子 Contact Object Example
{
  "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
{
  "name": "API支持",
  "url": "http://www.example.com/support",
  "email": "support@example.com"
}
name: API支持,
url: http://www.example.com/support
email: support@example.com

License对象 License Object

License information for the exposed API.

API的证书信息。

固定字段 Fixed Fields

Field Name Type Description
name string REQUIRED. The license name used for the API.
url string A URL to the license used for the API. MUST be in the format of a URL.

字段名 类型 描述
name string 必填. API的证书名。
url string 指向API所使用的证书的URL地址,必须 (MUST) 是URL地址格式。

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

License对象例子 License Object Example
{
  "name": "Apache 2.0",
  "url": "https://www.apache.org/licenses/LICENSE-2.0.html"
}
name: Apache 2.0
url: https://www.apache.org/licenses/LICENSE-2.0.html

Server对象 Server Object

An object representing a Server.

表示一个服务器的对象。

固定字段 Fixed Fields

Field Name Type Description
url string REQUIRED. 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}.
description string An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation.
variables Map[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.

字段名 类型 描述
url string 必填. 指向目标主机的URL地址。这个URL地址支持服务器变量而且可以 (MAY) 是相对路径。如果是相对路径则表示主机URL是相对于本OpenAPI文档所在的路径的。当一个变量被命名为类似{brackets}时需要替换此变量。
description string 描述URL指定的主机的可选字符串。可以 (MAY) 使用CommonMark 语法编写富文本。
variables Map[string, Server Variable Object] 一组变量名和其值之间的映射,用于替换服务器URL地址模板内的参数。

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

Server对象例子 Server Object Example

A single server would be described as:

单个服务器例子:

{
  "url": "https://development.gigantic-server.com/v1",
  "description": "Development server"
}
url: https://development.gigantic-server.com/v1
description: Development server
{
  "url": "https://development.gigantic-server.com/v1",
  "description": "开发服务器"
}
url: https://development.gigantic-server.com/v1
description: 开发服务器

The following shows how multiple servers can be described, for example, at the OpenAPI Object's 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://development.gigantic-server.com/v1",
      "description": "开发服务器"
    },
    {
      "url": "https://staging.gigantic-server.com/v1",
      "description": "预演服务器"
    },
    {
      "url": "https://api.gigantic-server.com/v1",
      "description": "产品服务器"
    }
  ]
}
servers:
- url: https://development.gigantic-server.com/v1
  description: 开发服务器
- url: https://staging.gigantic-server.com/v1
  description: 预演服务器
- url: https://api.gigantic-server.com/v1
  description: 产品服务器

The following shows how variables can be used for a server configuration:

URL模板和变量使用例子:

{
  "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
{
  "servers": [
    {
      "url": "https://{username}.gigantic-server.com:{port}/{basePath}",
      "description": "产品API服务器",
      "variables": {
        "username": {
          "default": "demo",
          "description": "此变量由`gigantic-server.com`的服务提供者指定, 默认值是`demo`"
        },
        "port": {
          "enum": [
            "8443",
            "443"
          ],
          "default": "8443"
        },
        "basePath": {
          "default": "v2"
        }
      }
    }
  ]
}
servers:
- url: https://{username}.gigantic-server.com:{port}/{basePath}
  description: 产品API服务器
  variables:
    username:
      # 注意! 没有指定枚举值表示它是个开放的值
      default: demo
      description: 此变量由`gigantic-server.com`的服务提供者指定, 默认值是`demo`
    port:
      enum:
        - '8443'
        - '443'
      default: '8443'
    basePath:
      # 没有罗列枚举值, 表示这是一个开放值, 意味着有机会使用服务提供者分配的特殊基本路径,默认为`v2`。
      default: v2

Server Variable对象 Server Variable Object

An object representing a Server Variable for server URL template substitution.

代表一个服务器变量的对象,用于服务器URL模板替换。

固定字段 Fixed Fields

Field Name Type Description
enum [string] An enumeration of string values to be used if the substitution options are from a limited set. The array SHOULD NOT be empty.
default string REQUIRED. The default value to use for substitution, which SHALL be sent if an alternate value is not supplied. Note this behavior is different than the Schema Object's treatment of default values, because in those cases parameter values are optional. If the enum is defined, the value SHOULD exist in the enum's values.
description string An optional description for the server variable. CommonMark syntax MAY be used for rich text representation.

字段名 类型 描述
enum [string] 一个字符串值的枚举,当可替换选项只能设置为固定的某些值时使用。数组不能 (SHOULD NOT)为空。
default string 必填. 用于替换的默认值,当可替换的值没有被使用者指定时使用,这个值必须由使用者提供。注意这种行为与 Schema Object's 对默认值的处理不同,因为在那些情况下参数值是可选的。如果定义了 enum ,那么这个值应该(SHOULD)存在于枚举的值中。
description string 服务器变量的可选描述。可以 (MAY) 使用CommonMark 语法编写富文本。

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

Components对象 Components Object

Holds a set of reusable objects for different aspects of the OAS. All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object.

为OAS的不同方面定义了一组可重复使用的对象。 在Components对象中定义的所有对象都不会对API产生直接的影响,除非它们明确地被Components对象之外的属性引用。

固定字段 Fixed Fields

Field Name Type Description
schemas Map[string, Schema Object | Reference Object] An object to hold reusable Schema Objects.
responses Map[string, Response Object | Reference Object] An object to hold reusable Response Objects.
parameters Map[string, Parameter Object | Reference Object] An object to hold reusable Parameter Objects.
examples Map[string, Example Object | Reference Object] An object to hold reusable Example Objects.
requestBodies Map[string, Request Body Object | Reference Object] An object to hold reusable Request Body Objects.
headers Map[string, Header Object | Reference Object] An object to hold reusable Header Objects.
securitySchemes Map[string, Security Scheme Object | Reference Object] An object to hold reusable Security Scheme Objects.
links Map[string, Link Object | Reference Object] An object to hold reusable Link Objects.
callbacks Map[string, Callback Object | Reference Object] An object to hold reusable Callback Objects.

字段名 类型 描述
schemas Map[string, Schema Object | Reference Object] 用于定义可重复使用的 Schema Objects.
responses Map[string, Response Object | Reference Object] 用于定义可重复使用的 Response Objects.
parameters Map[string, Parameter Object | Reference Object] 用于定义可重复使用的 Parameter Objects.
examples Map[string, Example Object | Reference Object] 用于定义可重复使用的 Example Objects.
requestBodies Map[string, Request Body Object | Reference Object] 用于定义可重复使用的 Request Body Objects.
headers Map[string, Header Object | Reference Object] 用于定义可重复使用的 Header Objects.
securitySchemes Map[string, Security Scheme Object | Reference Object] 用于定义可重复使用的 Security Scheme Objects.
links Map[string, Link Object | Reference Object] 用于定义可重复使用的 Link Objects.
callbacks Map[string, Callback Object | Reference Object] 用于定义可重复使用的 Callback Objects.

All the fixed fields declared above are objects that MUST use keys that match the regular expression: ^[a-zA-Z0-9\.\-_]+$.

Field Name Examples:

上面声明的所有固定字段的key都必须(MUST)符合以下正则表达式: ^[a-zA-Z0-9\.\-_]+$

譬如:

User
User_1
User_Name
user-name
my.org.User
Components对象例子 Components Object Example
"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"
          }
        }
      }
    }
  }
}
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
"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": "跳过多少个items, 相当于SQL中的offset",
      "required": true,
      "schema": {
        "type": "integer",
        "format": "int32"
      }
    },
    "limitParam": {
      "name": "limit",
      "in": "query",
      "description": "最多返回多少条记录, 相当于SQL的limit",
      "required": true,
      "schema" : {
        "type": "integer",
        "format": "int32"
      }
    }
  },
  "responses": {
    "NotFound": {
      "description": "找不到实体。"
    },
    "IllegalInput": {
      "description": "非法的输入。"
    },
    "GeneralError": {
      "description": "一般错误",
      "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": "修改你的宠物信息",
            "read:pets": "读取你的重复信息"
          }
        }
      }
    }
  }
}
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: 跳过多少个items, 相当于SQL中的offset
      required: true
      schema:
        type: integer
        format: int32
    limitParam:
      name: limit
      in: query
      description: 最多返回多少条记录, 相当于SQL的limit
      required: true
      schema:
        type: integer
        format: int32
  responses:
    NotFound:
      description: 找不到实体。
    IllegalInput:
      description: 非法的输入。
    GeneralError:
      description: 一般错误
      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: 修改你的宠物信息
            read:pets: 读取你的重复信息

Paths对象 Paths Object

Holds the relative paths to the individual endpoints and their operations. The path is appended to the URL from the Server Object in order to construct the full URL.
The Paths MAY be empty, due to ACL constraints.

保存了各个端点(endpoints)及其操作(operations)的相对路径。 该路径会追加到 Server Object 的URL上从而形成完整的访问URL。 由于 ACL 限制 ,路径可能(MAY)为空。

模式化字段 Patterned Fields

Field Pattern Type Description
/{path} Path Item Object A relative path to an individual endpoint. The field name MUST begin with a forward slash (/). The path is appended (no relative URL resolution) to the expanded URL from the Server Object's url field in order to construct the full URL. Path templating is allowed. When matching URLs, concrete (non-templated) paths would be matched before their templated counterparts. Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical. In case of ambiguous matching, it's up to the tooling to decide which one to use.

字段模式 类型 描述
/{path} Path Item Object 到单个端点(endpoint)的相对路径。字段名必须(MUST)以斜线(/)开头。为了构建完整的URL,路径追加到Server Objecturl 字段的扩展URL上(没有相对URL解析)。支持Path templating。当匹配URL时,具体的(非模板化的)路径将在其模板化的对应路径之前进行匹配。具有相同层次结构但不同模板名称的模板化路径必须不(MUST NOT)存在,因为它们是相同的。在匹配不明确的情况下,由工具来决定使用哪一个。

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

路径模板匹配 Path Templating Matching

Assuming the following paths, the concrete definition, /pets/mine, will be matched first if used:

假设使用以下路径,如果使用具体的定义(非模式化),/pets/mine,将首先匹配。

  /pets/{petId}
  /pets/mine

The following paths are considered identical and invalid:

以下路径模板会被认为不合法:

  /pets/{petId}
  /pets/{name}

The following may lead to ambiguous resolution:

以下路径模板会被认为不合法:

  /{entity}/me
  /books/{id}
Paths对象例子 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"
                }
              }
            }
          }
        }
      }
    }
  }
}
/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": {
    "get": {
      "description": "返回用户当前访问的系统的所有宠物。",
      "responses": {
        "200": {          
          "description": "宠物列表",
          "content": {
            "application/json": {
              "schema": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/pet"
                }
              }
            }
          }
        }
      }
    }
  }
}
/pets:
  get:
    description: 返回用户当前访问的系统的所有宠物。
    responses:
      '200':
        description: 宠物列表
        content:
          application/json:
            schema:
              type: array
              items:
                $ref: '#/components/schemas/pet'

Path Item对象 Path Item Object

Describes the operations available on a single path. A Path Item MAY be empty, due to ACL constraints. The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available.

描述单个路径上可用的操作。由于ACL的限制,路径项可以(MAY)是空字符串。路径本身仍然会暴露给文档浏览者,但他们不会知道哪些操作和参数是可用的。

固定字段 Fixed Fields

Field Name Type Description
$ref string Allows for an external definition of this path item. The referenced structure MUST be in the format of a Path Item Object. In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined.
summary string An optional, string summary, intended to apply to all operations in this path.
description string An optional, string description, intended to apply to all operations in this path. CommonMark syntax MAY be used for rich text representation.
get Operation Object A definition of a GET operation on this path.
put Operation Object A definition of a PUT operation on this path.
post Operation Object A definition of a POST operation on this path.
delete Operation Object A definition of a DELETE operation on this path.
options Operation Object A definition of a OPTIONS operation on this path.
head Operation Object A definition of a HEAD operation on this path.
patch Operation Object A definition of a PATCH operation on this path.
trace Operation Object A definition of a TRACE operation on this path.
servers [Server Object] An alternative server array to service all operations in this path.
parameters [Parameter Object | Reference Object] A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's components/parameters.

字段名 类型 描述
$ref string 允许对该路径项进行外部定义,引用的结构必须是Path Item Object的格式。被引用的结构必须是路径项对象的格式。如果路径项对象字段同时出现在定义的对象和引用的对象中,则行为未定义。
summary string 一段适用于这个路径下所有操作的简要描述,可选。
description string 一段适用于这个路径下所有操作的详细描述,可选。可以 (MAY) 使用CommonMark 语法编写富文本。
get Operation Object 定义这个路径下的GET操作。
put Operation Object 定义这个路径下的PUT操作。
post Operation Object 定义这个路径下的POST操作。
delete Operation Object 定义这个路径下的DELETE操作。
options Operation Object 定义这个路径下的OPTIONS操作。
head Operation Object 定义这个路径下的HEAD操作。
patch Operation Object 定义这个路径下的PATCH操作。
trace Operation Object 定义这个路径下的TRACE操作。
servers [Server Object] 一组适用于这个路径下所有操作的服务器信息, 可以覆盖server对象的设置。
parameters [Parameter Object | Reference Object] 定义适用于该路径下所有操作的参数。这些参数可以在操作层被覆盖,但无法在操作层删除。该列表不得(MUST NOT)包含重复的参数。一个唯一的参数由 namelocation 的组合来定义。列表可以使用 Reference Object 链接到在OpenAPI对象的components/parameters中定义的参数。

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

Path Item对象例子 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"
    }
  ]
}
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
{
  "get": {
    "description": "根据ID返回宠物",
    "summary": "根据查找宠物",
    "operationId": "getPetsById",
    "responses": {
      "200": {
        "description": "宠物响应",
        "content": {
          "*/*": {
            "schema": {
              "type": "array",
              "items": {
                "$ref": "#/components/schemas/Pet"
              }
            }
          }
        }
      },
      "default": {
        "description": "错误信息",
        "content": {
          "text/html": {
            "schema": {
              "$ref": "#/components/schemas/ErrorModel"
            }
          }
        }
      }
    }
  },
  "parameters": [
    {
      "name": "id",
      "in": "path",
      "description": "宠物ID",
      "required": true,
      "schema": {
        "type": "array",
        "items": {
          "type": "string"
        }
      },
      "style": "simple"
    }
  ]
}
get:
  description: 根据ID返回宠物
  summary: 根据查找宠物
  operationId: getPetsById
  responses:
    '200':
      description: 宠物响应
      content:
        '*/*' :
          schema:
            type: array
            items:
              $ref: '#/components/schemas/Pet'
    default:
      description: 错误信息
      content:
        'text/html':
          schema:
            $ref: '#/components/schemas/ErrorModel'
parameters:
- name: id
  in: path
  description: 宠物ID
  required: true
  schema:
    type: array
    items:
      type: string  
  style: simple

Operation对象 Operation Object

Describes a single API operation on a path.

描述一个路径下的某个API操作。

固定字段 Fixed Fields

Field Name Type Description
tags [string] A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier.
summary string A short summary of what the operation does.
description string A verbose explanation of the operation behavior. CommonMark syntax MAY be used for rich text representation.
externalDocs External Documentation Object Additional external documentation for this operation.
operationId string Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is case-sensitive. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions.
parameters [Parameter Object | Reference Object] A list of parameters that are applicable for this operation. If a parameter is already defined at the Path Item, the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's components/parameters.
requestBody Request Body Object | Reference Object The request body applicable for this operation. The requestBody is only supported in HTTP methods where the HTTP 1.1 specification RFC7231 has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague, requestBody SHALL be ignored by consumers.
responses Responses Object REQUIRED. The list of possible responses as they are returned from executing this operation.
callbacks Map[string, Callback Object | Reference Object] A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a Callback Object that describes a request that may be initiated by the API provider and the expected responses.
deprecated boolean Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is false.
security [Security Requirement Object] A declaration of which security mechanisms can be used for this operation. 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. To make security optional, an empty security requirement ({}) can be included in the array. This definition overrides any declared top-level security. To remove a top-level security declaration, an empty array can be used.
servers [Server Object] An alternative server array to service this operation. If an alternative server object is specified at the Path Item Object or Root level, it will be overridden by this value.

字段名 类型 描述
tags [string] 用于控制API文档的标签列表,标签可以用于对操作进行分组。
summary string 对此操作的简短描述。
description string 对此操作行为的详细解释。可以 (MAY) 使用CommonMark 语法编写富文本。
externalDocs External Documentation Object 附加的外部文档。
operationId string 用于标识此操作的唯一字符串,这个id在此API包含的所有操作中必须(MUST)是唯一的。操作ID是大小写敏感的。相关的工具和库可能(MAY)会使用此operationId来唯一的标识一个操作,因此建议(RECOMMENDED)在命名时符合一般的编程命名习惯。
parameters [Parameter Object | Reference Object] 此操作的参数列表。如果一个同名的参数已经存在于 Path Item,那么这里的定义会覆盖它但是不能移除上面的定义。这个列表不允许(MUST NOT)包含重复的参数,参数的唯一性由 namelocation 的组合来确定。这个列表可以使用 Reference 对象 来引用定义于 OpenAPI 对象 components/parameters 的参数。
requestBody Request Body Object | Reference Object 可用于此操作的请求体。requestBody 只能被用于HTTP 1.1 规范 RFC7231 中明确定义了包含请求体的请求方法,在其他没有明确定义的请求方法中,requestBody的消费者应该(SHALL)忽略requestBody
responses Responses Object 必填. 定义执行此操作后的可能的响应值列表。
callbacks Map[string, Callback Object | Reference Object] 一组相对于父操作的可能出现的回调映射,键是回调对象(Callback Object)的唯一标识符。值是一个回调对象Callback Object,它描述了可能由API提供者发起的请求和预期的响应。
deprecated boolean 声明此操作已经被废弃,使用者应该(SHOULD)尽量避免使用此操作,默认的值是 false
security [Security Requirement Object] 声明哪种安全机制可用于此操作。这个列表可以包含多种可用于此操作的安全需求对象(security requirement objects),但是在认证一个请求时应该仅使用其中一种。可以在数组中声明一个空的对象 ({}) 来使得安全需求变成是可选的。这里的定义会覆盖任何在顶层 security 中的安全声明,因此可以声明一个空数组来变相的移除顶层的安全声明。
servers [Server Object] 一个可用于此操作的额外的 server 数组,这里的定义会覆盖 Path Item 对象 或 顶层的定义。

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

Operation 对象例子 Operation Object Example
{
  "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
{
  "tags": [
    "pet"
  ],
  "summary": "以表单形式提交数据, 更新宠物信息",
  "operationId": "updatePetWithForm",
  "parameters": [
    {
      "name": "petId",
      "in": "path",
      "description": "需要更新的宠物的ID",
      "required": true,
      "schema": {
        "type": "string"
      }
    }
  ],
  "requestBody": {
    "content": {
      "application/x-www-form-urlencoded": {
        "schema": {
          "type": "object",
          "properties": {
            "name": { 
              "description": "更新后的宠物名称",
              "type": "string"
            },
            "status": {
              "description": "更新后的宠物状态",
              "type": "string"
            }
          },
          "required": ["status"] 
        }
      }
    }
  },
  "responses": {
    "200": {
      "description": "宠物信息已更新",
      "content": {
        "application/json": {},
        "application/xml": {}
      }
    },
    "405": {
      "description": "不支持此HTTP方法",
      "content": {
        "application/json": {},
        "application/xml": {}
      }
    }
  },
  "security": [
    {
      "petstore_auth": [
        "write:pets",
        "read:pets"
      ]
    }
  ]
}
tags:
- pet
summary: 以表单形式提交数据, 更新宠物信息
operationId: updatePetWithForm
parameters:
- name: petId
  in: path
  description: 需要更新的宠物的ID
  required: true
  schema:
    type: string
requestBody:
  content:
    'application/x-www-form-urlencoded':
      schema:
       properties:
          name: 
            description: 更新后的宠物名称
            type: string
          status:
            description: 更新后的宠物状态
            type: string
       required:
         - status
responses:
  '200':
    description: 宠物信息已更新
    content: 
      'application/json': {}
      'application/xml': {}
  '405':
    description: 不支持此HTTP方法
    content: 
      'application/json': {}
      'application/xml': {}
security:
- petstore_auth:
  - write:pets
  - read:pets

External Documentation 对象 External Documentation Object

Allows referencing an external resource for extended documentation.

可以引用一个外部资源作为扩展说明文档。

固定字段 Fixed Fields

Field Name Type Description
description string A short description of the target documentation. CommonMark syntax MAY be used for rich text representation.
url string REQUIRED. The URL for the target documentation. Value MUST be in the format of a URL.

字段名 类型 描述
description string 对外部文档的简短描述。可以 (MAY) 使用CommonMark 语法编写富文本。
url string 必填. 外部文档的URL。 它的值必须(MUST)是一个URL格式。

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

External Documentation对象例子 External Documentation Object Example
{
  "description": "Find more info here",
  "url": "https://example.com"
}
description: Find more info here
url: https://example.com
{
  "description": "更多信息请访问此网址",
  "url": "https://example.com"
}
description: 更多信息请访问此网址
url: https://example.com

Parameter 对象 Parameter Object

Describes a single operation parameter.

描述一个操作参数。

A unique parameter is defined by a combination of a name and location.

一个参数的唯一性由 namelocation 的组合来确定。

Parameter 位置 Parameter Locations

There are four possible parameter locations specified by the in field:

  • path - Used together with Path Templating, where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in /items/{itemId}, the path parameter is itemId.
  • query - Parameters that are appended to the URL. For example, in /items?id=###, the query parameter is id.
  • header - Custom headers that are expected as part of the request. Note that RFC7230 states header names are case insensitive.
  • cookie - Used to pass a specific cookie value to the API.

in字段的值是参数的位置, 有4种值:

  • path - 路径参数, 与 Path Templating 一起使用,当参数的值是操作的URL的一部分时使用,但是不包含主机地址或基础路径。比如在路径 /items/{itemId} 中,路径参数是 itemId
  • query - 查询参数, 追加在URL地址之后的参数,比如 /items?id=### 中,查询参数是 id
  • header - 请求头参数, 请求中使用的自定义请求头,注意在 RFC7230 中规定,请求头的命名是不区分大小写的。
  • cookie - 用于传递特定的cookie值。

固定字段 Fixed Fields

Field Name Type Description
name string REQUIRED. The name of the parameter. Parameter names are case sensitive.
  • If in is "path", the name field MUST correspond to a template expression occurring within the path field in the Paths Object. See Path Templating for further information.
  • If in is "header" and the name field is "Accept", "Content-Type" or "Authorization", the parameter definition SHALL be ignored.
  • For all other cases, the name corresponds to the parameter name used by the in property.
in string REQUIRED. The location of the parameter. Possible values are "query", "header", "path" or "cookie".
description string A brief description of the parameter. This could contain examples of use. CommonMark syntax MAY be used for rich text representation.
required boolean Determines whether this parameter is mandatory. If the parameter location is "path", this property is REQUIRED and its value MUST be true. Otherwise, the property MAY be included and its default value is false.
deprecated boolean Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is false.
allowEmptyValue boolean Sets the ability to pass empty-valued parameters. This is valid only for query parameters and allows sending a parameter with an empty value. Default value is false. If style is used, and if behavior is n/a (cannot be serialized), the value of allowEmptyValue SHALL be ignored. Use of this property is NOT RECOMMENDED, as it is likely to be removed in a later revision.

字段名 类型 描述
name string 必填. 参数的名称。参数名是区分大小写的。
  • 如果 in 的值是 "path",那么 name 字段的值必须(MUST)与其关联的 Paths 对象path 字段的定义对应,查看 Path Templating 了解更多信息。
  • 如果 in 的值是 "header" 而且name字段的值是"Accept", "Content-Type""Authorization"之一,那么此参数定义应该被忽略。
  • 除此之外的情况,name表示 in 属性的名字.
in string 必填. 参数的位置,可能的值有 "query", "header", "path" 或 "cookie"。
description string 对此参数的简要描述,这里可以包含使用示例。可以 (MAY) 使用CommonMark 语法编写富文本。
required boolean 标明此参数是否是必填参数。如果 参数位置 的值是 path,那么这个参数一定是 必填 的因此这里的值必须是true。其他的则视情况而定。此字段的默认值是false
deprecated boolean 标明一个参数是已废弃的而且应该(SHOULD)尽快移除对它的使用。此字段的默认值是false
allowEmptyValue boolean 设置参数值是否允许为空字符串,这只在参数值为query时有效,默认值是false。如果同时指定了style属性且值为n/a(无法被序列化),那么此字段 allowEmptyValue应该(SHALL)被忽略。这个属性不建议(NOT RECOMMENDED)使用, 因为后续版本可能会建它移除。

The rules for serialization of the parameter are specified in one of two ways. For simpler scenarios, a schema and style can describe the structure and syntax of the parameter.

序列化参数的规则有两种。 对于简单的场景,可以用 schemastyle 描述参数的结构和语法。

Field Name Type Description
style string Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of in): for query - form; for path - simple; for header - simple; for cookie - form.
explode boolean When this is true, parameter values of type array or object generate separate parameters for each value of the array or key-value pair of the map. For other types of parameters this property has no effect. When style is form, the default value is true. For all other styles, the default value is false.
allowReserved boolean Determines whether the parameter value SHOULD allow reserved characters, as defined by RFC3986 :/?#[]@!$&'()*+,;= to be included without percent-encoding. This property only applies to parameters with an in value of query. The default value is false.
schema Schema Object | Reference Object The schema defining the type used for the parameter.
example Any Example of the parameter's potential value. The example SHOULD match the specified schema and encoding properties if present. The example field is mutually exclusive of the examples field. Furthermore, if referencing a schema that contains an example, the example value SHALL override the example provided by the schema. To represent examples of media types that cannot naturally be represented in JSON or YAML, a string value can contain the example with escaping where necessary.
examples Map[ string, Example Object | Reference Object]

Examples of the parameter's potential value. Each example SHOULD contain a value in the correct format as specified in the parameter encoding. The examples field is mutually exclusive of the example field. Furthermore, if referencing a schema that contains an example, the examples value SHALL override the example provided by the schema.

字段名 类型 描述
style string 描述根据参数值类型的不同如何序列化参数。默认值为(基于in字段的值):query 对应 formpath 对应 simple; header 对应 simple; cookie 对应 form
explode boolean 当这个值为true时,参数值类型为array时, 将数组的每一个元素拆解为独立的参数, 当参数值类型为object时, 将对象的每一个键值对拆解为独立的参数。对于其他类型的参数,这个字段没有任何影响。当 styleform时,这里的默认值是 true,对于其他 style 值类型,默认值是false
allowReserved boolean 决定此参数的值是否(SHOULD)允许使用 RFC3986定义的保留字符 :/?#[]@!$&'()*+,;=。 这个属性仅用于in的值是query时。此字段的默认值是false
schema Schema 对象 | Reference 对象 参数值的数据结构(schema)的定义。
example Any 参数值的示例。如果该属性定义了 schema 或 encoding , 那么值需要(SHOULD)符合这个定义。example属性与examples属性互斥,而且如果引用一个包含示例的schema,那么这里定义的示例应该(SHALL) 覆盖 schema中的示例。如果用JSON 或者 YAML无法表示参数值时, 可以用一个编码后的字符串来编写这个示例。
examples Map[ string, Example 对象 | Reference 对象] 参数值的示例。用于不同媒体类型对应的示例。每个示例应该包含一个对应于指定编码格式的格式正确的值,这个examples映射内包含的对象应该不同于example内的值(example属性与examples属性互斥)。而且如果引用一个包含示例的schema,那么这里定义的示例应该(SHALL) 覆盖 schema中的示例。

For more complex scenarios, the content property can define the media type and schema of the parameter. A parameter MUST contain either a schema property, or a content property, but not both. When example or examples are provided in conjunction with the schema object, the example MUST follow the prescribed serialization strategy for the parameter.

对于更复杂的场景,content属性可以定义参数的媒体类型和对应的结构(schema)。 一个参数必须(MUST)且只能包含schemacontent属性中的一个。 当exampleexamplesschema对象有定义时,示例必须(MUST)符合参数的序列化策略。

Field Name Type Description
content Map[string, Media Type Object] A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry.

字段名 | 类型 | 描述 ---|:---:|--- content | Map[`string`, [Media Type Object](#mediaTypeObject)] | 一个定义参数如何呈现的键值对映射。键是媒体类型,值是对应媒体类型的描述,此键值对只能(**MUST**)包含一组键值对。

样式值 Style Values

In order to support common ways of serializing simple parameters, a set of style values are defined.

为了支持常见的通用的简单参数序列化, 规范已经定义好了一组style类型。

style type in Comments
matrix primitive, array, object path Path-style parameters defined by RFC6570
label primitive, array, object path Label style parameters defined by RFC6570
form primitive, array, object query, cookie Form style parameters defined by RFC6570. This option replaces collectionFormat with a csv (when explode is false) or multi (when explode is true) value from OpenAPI 2.0.
simple array path, header Simple style parameters defined by RFC6570. This option replaces collectionFormat with a csv value from OpenAPI 2.0.
spaceDelimited array query Space separated array values. This option replaces collectionFormat equal to ssv from OpenAPI 2.0.
pipeDelimited array query Pipe separated array values. This option replaces collectionFormat equal to pipes from OpenAPI 2.0.
deepObject object query Provides a simple way of rendering nested objects using form parameters.

样式 类型 in 描述
matrix primitive, array, object path Path 样式的参数,参见 RFC6570
label primitive, array, object path Label 样式的参数,参见 RFC6570
form primitive, array, object query, cookie Form 样式的参数,参见 RFC6570. 此选项替换定义于OpenAPI 2.0中collectionFormat等于 csv (当 explode值为 false)或multi (当 explode值为 true)的情况。
simple array path, header Simple 样式的参数,参见 RFC6570. 此选项替换定义于OpenAPI 2.0 中 collectionFormat等于csv的情况。
spaceDelimited array query 空格分隔的数组值。此选项替换定义于OpenAPI 2.0 中 collectionFormat equal to ssv的情况。
pipeDelimited array query 管道符`
deepObject object query 提供一种简单的方法来表示 form 参数中的嵌套对象值.

样式示例 Style Examples

Assume a parameter named color has one of the following values:

假设color参数包含如下之一的值:

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

The following table shows examples of rendering differences for each value.

下面这个表展示了各个不同类型值之间的例子。

style explode empty string array object
matrix false ;color ;color=blue ;color=blue,black,brown ;color=R,100,G,200,B,150
matrix true ;color ;color=blue ;color=blue;color=black;color=brown ;R=100;G=200;B=150
label false . .blue .blue.black.brown .R.100.G.200.B.150
label true . .blue .blue.black.brown .R=100.G=200.B=150
form false color= color=blue color=blue,black,brown color=R,100,G,200,B,150
form true color= color=blue color=blue&color=black&color=brown R=100&G=200&B=150
simple false n/a blue blue,black,brown R,100,G,200,B,150
simple true n/a blue blue,black,brown R=100,G=200,B=150
spaceDelimited false n/a n/a blue%20black%20brown R%20100%20G%20200%20B%20150
pipeDelimited false n/a n/a blue|black|brown R|100|G|200|B|150
deepObject true n/a n/a n/a color[R]=100&color[G]=200&color[B]=150

样式 元素是否拆分成独立参数 空字符串值 字符串类型 数组类型 对象类型
matrix false ;color ;color=blue ;color=blue,black,brown ;color=R,100,G,200,B,150
matrix true ;color ;color=blue ;color=blue;color=black;color=brown ;R=100;G=200;B=150
label false . .blue .blue.black.brown .R.100.G.200.B.150
label true . .blue .blue.black.brown .R=100.G=200.B=150
form false color= color=blue color=blue,black,brown color=R,100,G,200,B,150
form true color= color=blue color=blue&color=black&color=brown R=100&G=200&B=150
simple false n/a blue blue,black,brown R,100,G,200,B,150
simple true n/a blue blue,black,brown R=100,G=200,B=150
spaceDelimited false n/a n/a blue%20black%20brown R%20100%20G%20200%20B%20150
pipeDelimited false n/a n/a blue|black|brown R|100|G|200|B|150
deepObject true n/a n/a n/a color[R]=100&color[G]=200&color[B]=150

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

Parameter对象例子 Parameter Object Examples

A header parameter with an array of 64 bit integer numbers:

一个数组元素为64位整数的请求头参数:

{
  "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: token
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": "通过HTTP header提交的token参数",
  "required": true,
  "schema": {
    "type": "array",
    "items": {
      "type": "integer",
      "format": "int64"
    }
  },
  "style": "simple"
}
name: token
in: header
description: 通过HTTP header提交的token参数
required: true
schema:
  type: array
  items:
    type: integer
    format: int64
style: simple

A path parameter of a string value:

一个值类型为字符串的路径参数:

{
  "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": "username",
  "in": "path",
  "description": "用户名",
  "required": true,
  "schema": {
    "type": "string"
  }
}
name: username
in: path
description: 用户名
required: true
schema:
  type: string

An optional query parameter of a string value, allowing multiple values by repeating the query parameter:

一个值类型为字符串的可选查询参数,允许通过通过重复参数来传递多个值:

{
  "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
{
  "name": "id",
  "in": "query",
  "description": "对象ID",
  "required": false,
  "schema": {
    "type": "array",
    "items": {
      "type": "string"
    }
  },
  "style": "form",
  "explode": true
}
name: id
in: query
description: 对象ID
required: false
schema:
  type: array
  items:
    type: string
style: form
explode: true

A free-form query parameter, allowing undefined parameters of a specific type:

一个任意格式的查询参数,允许使用指定类型的未定义参数:

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

A complex parameter using content to define serialization:

使用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:
        lat:
          type: number
        long:
          type: number
{
  "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:
        lat:
          type: number
        long:
          type: number

Request Body对象 Request Body Object

Describes a single request body.

描述单个请求消息体。

固定字段 Fixed Fields

Field Name Type Description
description string A brief description of the request body. This could contain examples of use. CommonMark syntax MAY be used for rich text representation.
content Map[string, Media Type Object] REQUIRED. The content of the request body. The key is a media type or media type range and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/*
required boolean Determines if the request body is required in the request. Defaults to false.

字段名 类型 描述
description string 对请求体的简要描述,可以包含使用示例,可以 (MAY) 使用CommonMark 语法编写富文本。
content Map[string, Media Type Object] 必填. 请求体的内容。 键是一个媒体类型或者媒体类型范围, 值是内容的定义。当一个请求上来时如果匹配的键有多个, 也只会选择一个匹配度最高的键来处理这个请求。譬如, text/* 会使用text/plain代替。
required boolean 指定请求体是不是是否必填,默认值是false

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

Request Body 例子 Request Body Examples

A request body with a referenced model definition.

请求消息体参数是一个引用的例子:

{
  "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": "添加用户",
  "content": {
    "application/json": {
      "schema": {
        "$ref": "#/components/schemas/User"
      },
      "examples": {
          "user" : {
            "summary": "用户例子(JSON格式)", 
            "externalValue": "http://foo.bar/examples/user-example.json"
          } 
        }
    },
    "application/xml": {
      "schema": {
        "$ref": "#/components/schemas/User"
      },
      "examples": {
          "user" : {
            "summary": "用户例子(XML格式)",
            "externalValue": "http://foo.bar/examples/user-example.xml"
          }
        }
    },
    "text/plain": {
      "examples": {
        "user" : {
            "summary": "用户例子(纯文本格式)",
            "externalValue": "http://foo.bar/examples/user-example.txt" 
        }
      } 
    },
    "*/*": {
      "examples": {
        "user" : {
            "summary": "用户例子(其他格式)",
            "externalValue": "http://foo.bar/examples/user-example.whatever"
        }
      }
    }
  }
}
description: 添加用户
content: 
  'application/json':
    schema:
      $ref: '#/components/schemas/User'
    examples:
      user:
        summary: 用户例子(JSON格式)
        externalValue: 'http://foo.bar/examples/user-example.json'
  'application/xml':
    schema:
      $ref: '#/components/schemas/User'
    examples:
      user:
        summary: 用户例子(XML格式)
        externalValue: 'http://foo.bar/examples/user-example.xml'
  'text/plain':
    examples:
      user:
        summary: 用户例子(纯文本格式)
        externalValue: 'http://foo.bar/examples/user-example.txt'
  '*/*':
    examples:
      user: 
        summary: 用户例子(其他格式)
        externalValue: 'http://foo.bar/examples/user-example.whatever'

A body parameter that is an array of string values:

请求消息体参数是一个字符串数组的例子:

{
  "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
{
  "description": "批量添加用户",
  "content": {
    "text/plain": {
      "schema": {
        "type": "array",
        "items": {
          "type": "string"
        }
      }
    }
  }
}
description: 批量添加用户
required: true
content:
  text/plain:
    schema:
      type: array
      items:
        type: string

Media Type对象 Media Type Object

Each Media Type Object provides schema and examples for the media type identified by its key.

每种媒体类型都有一个唯一的key作为标识, 每个媒体类型对象定义了它的结构(schema)和提供了相应的示例。

固定字段 Fixed Fields

Field Name Type Description
schema Schema Object | Reference Object The schema defining the content of the request, response, or parameter.
example Any Example of the media type. The example object SHOULD be in the correct format as specified by the media type. The example field is mutually exclusive of the examples field. Furthermore, if referencing a schema which contains an example, the example value SHALL override the example provided by the schema.
examples Map[ string, Example Object | Reference Object] Examples of the media type. Each example object SHOULD match the media type and specified schema if present. The examples field is mutually exclusive of the example field. Furthermore, if referencing a schema which contains an example, the examples value SHALL override the example provided by the schema.
encoding Map[string, Encoding Object] A map between a property name and its encoding information. The key, being the property name, MUST exist in the schema as a property. The encoding object SHALL only apply to requestBody objects when the media type is multipart or application/x-www-form-urlencoded.

字段名 类型 描述
schema Schema Object | Reference Object 定义此媒体类型的结构(schema), 包括请求,响应和参数等内容。
example Any 媒体类型的示例。示例对象应该(SHOULD)符合此媒体类型的格式, example属性与examples属性互斥,而且如果引用一个包含示例的schema,那么这里定义的示例应该(SHALL) 覆盖 schema中的示例。
examples Map[ string, Example Object | Reference Object] 媒体类型的示例,每个媒体对象的值都应该(SHOULD)符合它对应的媒体类型的格式要求。example属性与examples属性互斥,而且如果引用一个包含示例的schema,那么这里定义的示例应该(SHALL) 覆盖 schema中的示例。
encoding Map[string, Encoding Object] 属性名与编码信息的映射。每个属性名必须(MUST)存在于schema属性的key中,当媒体类型是multipartapplication/x-www-form-urlencoded时,编码对象信息(SHALL)仅适用于requestBody

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

Media Type例子 Media Type Examples
{
  "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:
    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": {
      "cat" : {
        "summary": "这是一只猫的例子",
        "value": 
          {
            "name": "Fluffy",
            "petType": "Cat",
            "color": "White",
            "gender": "male",
            "breed": "Persian"
          }
      },
      "dog": {
        "summary": "这是一只狗的例子, 给它起了一个猫的名字",
        "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:
    cat:
      summary: 这是一只猫的例子
      value:
        name: Fluffy
        petType: Cat
        color: White
        gender: male
        breed: Persian
    dog:
      summary: 这是一只狗的例子, 给它起了一个猫的名字
      value:
        name: Puma
        petType: Dog
        color: Black
        gender: Female
        breed: Mixed
    frog:
      $ref: "#/components/examples/frog-example"
对文件上传的考虑 Considerations for File Uploads

In contrast with the 2.0 specification, file input/output content in OpenAPI is described with the same semantics as any other schema type. Specifically:

相对于2.0的规范,在OpenAPI规范中file内容的上传与下载与其他类型一样使用相同的语法来描述。特别是:

# content transferred with base64 encoding
schema:
  type: string
  format: base64
# content transferred in binary (octet-stream):
schema:
  type: string
  format: binary
# 通过base64编码进行传输
schema:
  type: string
  format: base64
# 通过binary(二进制数据流)编码进行传输:
schema:
  type: string
  format: binary

These examples apply to either input payloads of file uploads or response payloads.

这些示例同时适用于文件上传和下载。

A requestBody for submitting a file in a POST operation may look like the following example:

一个使用POST操作提交文件的requestBody看起来像下面这样:

requestBody:
  content:
    application/octet-stream:
      schema:
        # a binary file of any type
        type: string
        format: binary
requestBody:
  content:
    application/octet-stream:
      schema:
        # 任何类型的二进制文件
        type: string
        format: binary

In addition, specific media types MAY be specified:

此外,可以指定明确的媒体类型:

# 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        
# 指定多种媒体类型例子:
requestBody:
  content:
      # 一个png或jpeg二进制文件
    'image/jpeg':
      schema:
        type: string
        format: binary
    'image/png':
      schema:
        type: string
        format: binary        

To upload multiple files, a multipart media type MUST be used:

为了同时上传多个文件,必须指定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
requestBody:
  content:
    multipart/form-data:
      schema:
        properties:
          # 属性名 'file' 会用在所有上传的文件上
          file:
            type: array
            items:
              type: string
              format: binary
x-www-form-urlencoded 请求体的支持 Support for x-www-form-urlencoded Request Bodies

To submit content using form url encoding via RFC1866, the following definition may be used:

可以使用下面定义的格式来提交form url编码 RFC1866 的内容:

requestBody:
  content:
    application/x-www-form-urlencoded:
      schema:
        type: object
        properties:
          id:
            type: string
            format: uuid
          address:
            # complex types are stringified to support RFC 1866
            type: object
            properties: {}
requestBody:
  content:
    application/x-www-form-urlencoded:
      schema:
        type: object
        properties:
          id:
            type: string
            format: uuid
          address:
            # 复杂类型需要先按照 RFC 1866 序列化成字符串
            type: object
            properties: {}

In this example, the contents in the requestBody MUST be stringified per RFC1866 when passed to the server. In addition, the address field complex object will be stringified.

在这个示例中,在内容被传送到服务器之前,requestBody中的内容必须(MUST)使用RFC1866中定义的方式字符串化。此外address字段的复杂对象将会被字符串化。

When passing complex objects in the application/x-www-form-urlencoded content type, the default serialization strategy of such properties is described in the Encoding Object's style property as form.

当使用application/x-www-form-urlencoded格式传送复杂对象时, 在Encoding Objectstyle 属性中定义了默认的序列化策略为form.

multipart内容的特别思考 Special Considerations for multipart Content

It is common to use multipart/form-data as a Content-Type when transferring request bodies to operations. In contrast to 2.0, a schema is REQUIRED to define the input parameters to the operation when using multipart content. This supports complex structures as well as supporting mechanisms for multiple file uploads.

使用multipart/form-data作为Content-Type来传送请求体是很常见的做法。相对于2.0版本的规范,当定义multipart内容的输入参数时必须指定schema属性。这不但支持复杂的结构而且支持多文件上传机制。

When passing in multipart types, boundaries MAY be used to separate sections of the content being transferred — thus, the following default Content-Types are defined for multipart:

当使用multipart类型时,可以使用boundaries来分隔传送的内容,因此multipart定义了以下默认的Content-Type

  • If the property is a primitive, or an array of primitive values, the default Content-Type is text/plain
  • If the property is complex, or an array of complex values, the default Content-Type is application/json
  • If the property is a type: string with format: binary or format: base64 (aka a file object), the default Content-Type is application/octet-stream

  • 如果属性是一个原始值或者是一个原始值的数组,那么默认的Content-Type是 text/plain
  • 如果属性是复杂对象或者复杂对象的数组,那么默认的Content-Type是application/json
  • 如果属性是type: stringformat: binaryformat: base64(也就是文件对象)的组合,那么默认的Content-Type是 application/octet-stream

Examples:

示例:

requestBody:
  content:
    multipart/form-data:
      schema:
        type: object
        properties:
          id:
            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'
requestBody:
  content:
    multipart/form-data:
      schema:
        type: object
        properties:
          id:
            type: string
            format: uuid
          address:
            # 属性是复杂对象或者复杂对象的数组,那么默认的Content-Type是`application/json`
            type: object
            properties: {}
          profileImage:
            # 属性是`type: string`与`format: binary`或`format: base64`(也就是文件对象)的组合,那么默认的Content-Type是 `application/octet-stream`
            type: string
            format: binary
          children:
            # 属性是一个原始值(此处是string)或者是一个原始值的数组,那么默认的Content-Type是 `text/plain`
            type: array
            items:
              type: string
          addresses:
            # 因为Address是一个复杂对象, 所以这里默认的Content-Type也是`application/json`
            type: array
            items:
              type: '#/components/schemas/Address'

An encoding attribute is introduced to give you control over the serialization of parts of multipart request bodies.
This attribute is only applicable to multipart and application/x-www-form-urlencoded request bodies.

这里介绍一下用来控制 multipart请求体 序列化的encoding属性,这个属性只适用于multipartapplication/x-www-form-urlencoded类型的请求体。

Encoding对象 Encoding Object

A single encoding definition applied to a single schema property.

用于结构(schema)属性的编码定义。

固定字段 Fixed Fields

Field Name Type Description
contentType string The Content-Type for encoding a specific property. Default value depends on the property type: for string with format being binaryapplication/octet-stream; for other primitive types – text/plain; for object - application/json; for array – the default is defined based on the inner type. The value can be a specific media type (e.g. application/json), a wildcard media type (e.g. image/*), or a comma-separated list of the two types.
headers Map[string, Header Object | Reference Object] A map allowing additional information to be provided as headers, for example Content-Disposition. Content-Type is described separately and SHALL be ignored in this section. This property SHALL be ignored if the request body media type is not a multipart.
style string Describes how a specific property value will be serialized depending on its type. See Parameter Object for details on the style property. The behavior follows the same values as query parameters, including default values. This property SHALL be ignored if the request body media type is not application/x-www-form-urlencoded.
explode boolean When this is true, property values of type array or object generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties this property has no effect. When style is form, the default value is true. For all other styles, the default value is false. This property SHALL be ignored if the request body media type is not application/x-www-form-urlencoded.
allowReserved boolean Determines whether the parameter value SHOULD allow reserved characters, as defined by RFC3986 :/?#[]@!$&'()*+,;= to be included without percent-encoding. The default value is false. This property SHALL be ignored if the request body media type is not application/x-www-form-urlencoded.

字段名 类型 描述
contentType string 对指定属性的 Content-Type的编码。默认值取决于属性的类型:binary格式的string默认值是application/octet-stream;其他原始值的默认值是text/plainobject的默认值是application/json;对于array值类型的默认值取决于数组内元素的类型,默认值可以是明确的媒体类型(比如application/json), 或者通配符类型的媒体类型(比如image/*), 又或者是用分号分隔的两者的组合。
headers Map[string, Header Object | Reference Object] 提供附加信息的请求头键值对映射,譬如Content-DispositionContent-Type有独立的属性可以设置所以如果在这里设置应该(SHALL)忽略。如果请求体的媒体类型不是multipart,这个属性将会被忽略。
style string 描述一个属性如何序列化(根据它的类型)。查看 Parameter 对象style 属性可以得到更多详细信息。这个属性的行为与query参数相同,包括默认值的定义。如果请求体的媒体类型不是application/x-www-form-urlencoded,这个属性应该(SHALL)忽略。
explode boolean 当这个值为true时,参数值类型为array时, 将数组的每一个元素拆解为独立的参数, 当参数值类型为object时, 将对象的每一个键值对拆解为独立的参数。对于其他类型的参数,这个字段没有任何影响。当 styleform时,这里的默认值是 true,对于其他 style 值类型,默认值是false。如果请求体的媒体类型不是application/x-www-form-urlencoded这个属性会被忽略。
allowReserved boolean 决定此参数的值是否(SHOULD)允许使用 RFC3986定义的保留字符 :/?#[]@!$&'()*+,;=。 这个属性仅用于in的值是query时。此字段的默认值是false。如果请求体的媒体类型不是application/x-www-form-urlencoded这个属性会被忽略。

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

Encoding对象例子 Encoding Object Example
requestBody:
  content:
    multipart/mixed:
      schema:
        type: object
        properties:
          id:
            # 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
requestBody:
  content:
    multipart/mixed:
      schema:
        type: object
        properties:
          id:
            # 默认是 text/plain
            type: string
            format: uuid
          address:
            # 默认是 application/json
            type: object
            properties: {}
          historyMetadata:
            # 需要定义成XML媒体类型!
            description: XML格式的元数据
            type: object
            properties: {}
          profileImage:
            # 默认是 application/octet-stream, 需要定义一个图片类型
            type: string
            format: binary
      encoding:
        historyMetadata:
          # 使用utf-8字符串编码的XML媒体类型
          contentType: application/xml; charset=utf-8
        profileImage:
          # 只支持 png/jpeg
          contentType: image/png, image/jpeg
          headers:
            X-Rate-Limit-Limit:
              description: 当前周期允许的请求速率
              schema:
                type: integer

Responses对象 Responses Object

A container for the expected responses of an operation. The container maps a HTTP response code to the expected response.

Responses对象是一个以响应码为键, 以Response对象为值的映射, 描述了一个操作的一些可能的响应。

The documentation is not necessarily expected to cover all possible HTTP response codes because they may not be known in advance. However, documentation is expected to cover a successful operation response and any known errors.

一份API文档不必包含所有可能响应码,因为有些状态码无法提前预知。 尽管如此,一份文档还是应当包含所有成功的响应和任何已知的错误响应。

The default MAY be used as a default response object for all HTTP codes that are not covered individually by the specification.

default属性可以(MAY)用来定义一个默认响应, 表示其他未被明确定义的响应码都是返回这个结构。

The Responses Object MUST contain at least one response code, and it SHOULD be the response for a successful operation call.

一个Responses 对象必须(MUST)至少包含一个响应码,而且应该(SHOULD)是成功的响应。

固定字段 Fixed Fields

Field Name Type Description
default Response Object | Reference Object The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses. A Reference Object can link to a response that the OpenAPI Object's components/responses section defines.

字段名 类型 描述
default Response Object | Reference Object 用于描述未被明确声明的HTTP响应码的响应。使用这个字段来覆盖未声明的响应。一个 Reference 对象 可以引用定义于 OpenAPI 对象 components/responses 的响应对象。

模式化字段 Patterned Fields

Field Pattern Type Description
HTTP Status Code Response Object | Reference Object Any HTTP status code can be used as the property name, but only one property per code, to describe the expected response for that HTTP status code. A Reference Object can link to a response that is defined in the OpenAPI Object's components/responses section. This field MUST be enclosed in quotation marks (for example, "200") for compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase wildcard character X. For example, 2XX represents all response codes between [200-299]. Only the following range definitions are allowed: 1XX, 2XX, 3XX, 4XX, and 5XX. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code.

字段名 类型 描述
HTTP Status Code Response Object | Reference Object 任何 HTTP status code 都可以被用作属性名, 但是每一个状态码只能出现一次,用于描述此状态码的响应。一个 Reference 对象 可以引用定义于 OpenAPI 对象 components/responses 的响应对象。这个字段名必须(MUST)包含在双引号中 (例如 "200") 以兼容 JSON 和 YAML。这个字段可以(MAY)包含大写的通配字符X来定义响应码的范围。例如,2XX 代表所有位于 [200-299] 范围内的响应码。只允许使用以下范围定义:1XX, 2XX, 3XX, 4XX, 和 5XX。如果同时包含范围定义与明确定义的响应,那么明确定义的响应有更高的优先级。

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

Responses对象例子 Responses Object Example

A 200 response for a successful operation and a default response for others (implying an error):

一个代表操作成功的 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'
{
  "200": {
    "description": "返回一只宠物",
    "content": {
      "application/json": {
        "schema": {
          "$ref": "#/components/schemas/Pet"
        }
      }
    }
  },
  "default": {
    "description": "其他错误",
    "content": {
      "application/json": {
        "schema": {
          "$ref": "#/components/schemas/ErrorModel"
        }
      }
    }
  }
}
'200':
  description: 返回一只宠物
  content: 
    application/json:
      schema:
        $ref: '#/components/schemas/Pet'
default:
  description: 其他错误
  content:
    application/json:
      schema:
        $ref: '#/components/schemas/ErrorModel'

Response 对象 Response Object

Describes a single response from an API Operation, including design-time, static links to operations based on the response.

描述API操作的单个响应,包括设计时间、基于不同响应也包括到相应操作的静态links

固定字段 Fixed Fields

Field Name Type Description
description string REQUIRED. A short description of the response. CommonMark syntax MAY be used for rich text representation.
headers Map[string, Header Object | Reference Object] Maps a header name to its definition. RFC7230 states header names are case insensitive. If a response header is defined with the name "Content-Type", it SHALL be ignored.
content Map[string, Media Type Object] A map containing descriptions of potential response payloads. The key is a media type or media type range and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/*
links Map[string, Link Object | Reference Object] A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for Component Objects.

Field Name Type Description
description string 必填. 对响应的简短描述。可以 (MAY) 使用CommonMark 语法编写富文本。
headers Map[string, Header Object | Reference Object] 映射HTTP头名称到其定义。RFC7230 规定了HTTP头名称不区分大小写。"Content-Type"HTTP响应头会(SHALL)被忽略(因为它是在content里定义的)。
content Map[string, Media Type Object] 一个包含描述预期响应内容的映射。使用 media type 或 media type range 作为键,以响应的描述作为值。当一个响应匹配多个键时,只有最明确的键生效。比如:text/plain 会覆盖 text/*
links Map[string, Link Object | Reference Object] 用于描述下一步可以执行什么操作的映射, 键是这个连接的一个简短命名, 需要遵循Component Objects的命名规则。

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

Response 对象例子 Response Object Examples

Response of an array of a complex type:

一个包含复杂类型的数组格式的响应:

{
  "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": "一个复杂对象数组的响应",
  "content": {
    "application/json": {
      "schema": {
        "type": "array",
        "items": {
          "$ref": "#/components/schemas/VeryComplexType"
        }
      }
    }
  }
}
description: 一个复杂对象数组的响应
content: 
  application/json:
    schema: 
      type: array
      items:
        $ref: '#/components/schemas/VeryComplexType'

Response with a string type:

字符串类型的响应:

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

}
description: A simple string response
content:
  text/plain:
    schema:
      type: string
{
  "description": "一个简单的字符串响应",
  "content": {
    "text/plain": {
      "schema": {
        "type": "string"
      }
    }
  }

}
description: 一个简单的字符串响应
content:
  text/plain:
    schema:
      type: string

Plain text response with headers:

带HTTP头的普通文本类型的响应:

{
  "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": "一个简单的字符串响应",
  "content": {
    "text/plain": {
      "schema": {
        "type": "string",
        "example": "whoa!"
      }
    }
  },
  "headers": {
    "X-Rate-Limit-Limit": {
      "description": "一个周期内的调用频率限制",
      "schema": {
        "type": "integer"
      }
    },
    "X-Rate-Limit-Remaining": {
      "description": "当前周期的剩余调用次数",
      "schema": {
        "type": "integer"
      }
    },
    "X-Rate-Limit-Reset": {
      "description": "当前周期的剩余的秒数",
      "schema": {
        "type": "integer"
      }
    }
  }
}
description: 一个简单的字符串响应
content:
  text/plain:
    schema:
      type: string
    example: 'whoa!'
headers:
  X-Rate-Limit-Limit:
    description: 一个周期内的调用频率限制
    schema:
      type: integer
  X-Rate-Limit-Remaining:
    description: 当前周期的剩余调用次数
    schema:
      type: integer
  X-Rate-Limit-Reset:
    description: 当前周期的剩余的秒数
    schema:
      type: integer

Response with no return value:

没有返回值的响应:

{
  "description": "object created"
}
description: object created
{
  "description": "对象创建成功"
}
description: 对象创建成功

Callback 对象 Callback Object

A map of possible out-of band callbacks related to the parent operation. Each value in the map is a Path Item Object that describes a set of requests that may be initiated by the API provider and the expected responses. The key value used to identify the path item object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation.

与父操作相关的可能的回调的映射. 映射中的每个值都是一个Path Item对象,它描述了一组可能由API提供者发起的请求和预期的响应. 用于标识Path Item对象的键值是一个表达式,实际值在运行时生成,它标识了用于回调操作的URL。

模式化字段 Patterned Fields

Field Pattern Type Description
{expression} Path Item Object A Path Item Object used to define a callback request and expected responses. A complete example is available.

字段名 类型 描述
{expression} Path Item Object 一个用于定义回调请求和预期响应的 Path Item 对象。 完整例子请戳这里.

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

键表达式 Key Expression

The key that identifies the Path Item Object is a runtime expression that can be evaluated in the context of a runtime HTTP request/response to identify the URL to be used for the callback request. A simple example might be $request.body#/url. However, using a runtime expression the complete HTTP message can be accessed. This includes accessing any part of a body that a JSON Pointer RFC6901 can reference.

用于标识 Path Item Object 的键是一个 runtime expression,此表达式会在运行时的HTTP请求/响应上下文中被计算,计算结果用于表示回调请求的URL。 一个简单的例子是 $request.body#/url

For example, given the following HTTP request:

比如有如下 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

The following examples show how the various expressions evaluate, assuming the callback operation has a path parameter named eventType and a query parameter named queryUrl.

下方示例展示了各种表达式是如何被计算,这里假设回调操作有一个名为 eventType 的路径参数和一个名为 queryUrl 的查询参数。

Expression Value
$url http://example.org/subscribe/myevent?queryUrl=http://clientdomain.com/stillrunning
$method POST
$request.path.eventType myevent
$request.query.queryUrl http://clientdomain.com/stillrunning
$request.header.content-Type application/json
$request.body#/failedUrl http://clientdomain.com/failed
$request.body#/successUrls/2 http://clientdomain.com/medium
$response.header.Location http://example.org/subscription/1

表达式 生成的值
$url http://example.org/subscribe/myevent?queryUrl=http://clientdomain.com/stillrunning
$method POST
$request.path.eventType myevent
$request.query.queryUrl http://clientdomain.com/stillrunning
$request.header.content-Type application/json
$request.body#/failedUrl http://clientdomain.com/failed
$request.body#/successUrls/2 http://clientdomain.com/medium
$response.header.Location http://example.org/subscription/1

Callback对象例子 Callback Object Examples

The following example uses the user provided queryUrl query string parameter to define the callback URL.
This is an example of how to use a callback object to describe a WebHook callback that goes with the subscription operation to enable registering for the WebHook.

下面的例子演示了使用客户端提供的queryUrl查询字符串(query string)参数来作为回调地址。 这是一个如何使用回调对象来描述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
myCallback:
  '{$request.query.queryUrl}':
    post:
      requestBody:
        description: 回调内容
        content: 
          'application/json':
            schema:
              $ref: '#/components/schemas/SomePayload'
      responses:
        '200':
          description: 回调处理成功

The following example shows a callback where the server is hard-coded, but the query string parameters are populated from the id and email property in the request body.

下面的例子展示了一个回调,在这个回调中,服务器地址是硬编码的,但查询字符串参数是由请求体中的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
transactionCallback:
  'http://notificationServer.com?transactionId={$request.body#/id}&email={$request.body#/email}':
    post:
      requestBody:
        description: 回调内容
        content: 
          'application/json':
            schema:
              $ref: '#/components/schemas/SomePayload'
      responses:
        '200':
          description: 回调处理成功

Example 对象 Example Object

固定字段 Fixed Fields

Field Pattern Type Description
summary string Short description for the example.
description string Long description for the example. CommonMark syntax MAY be used for rich text representation.
value Any Embedded literal example. The value field and externalValue field are mutually exclusive. To represent examples of media types that cannot naturally represented in JSON or YAML, use a string value to contain the example, escaping where necessary.
externalValue string A URL that points to the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. The value field and externalValue field are mutually exclusive.

字段名 类型 描述
summary string example 的简要描述。
description string example 的详细描述。可以 (MAY) 使用CommonMark 语法编写富文本。
value Any example的值。valueexternalValue 是互斥的, 不能同时设置。如果媒体类型的例子不方便用JSON和YAML描述, 可以用一个字符串来编写这个例子, 必要时需要编码一些字符。
externalValue string 一个URL, 指向example的值。通过这种方式可以提供更好的兼容性, 以便在内容不便放入到JSON和YAML中的时候使用。valueexternalValue 是互斥的, 不能同时设置。

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

In all cases, the example value is expected to be compatible with the type schema of its associated value. Tooling implementations MAY choose to validate compatibility automatically, and reject the example value(s) if incompatible.

在所有情况下,示例值都应该与它的关联值的类型模式兼容。 工具实现可以(MAY)自动验证兼容性,如果不兼容,则拒绝示例值。

Example 对象例子 Example Object Examples

In a request body:

请求消息体中的Example:

requestBody:
  content:
    'application/json':
      schema:
        $ref: '#/components/schemas/Address'
      examples: 
        foo:
          summary: A foo example
          value: {"foo": "bar"}
        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'
requestBody:
  content:
    'application/json':
      schema:
        $ref: '#/components/schemas/Address'
      examples: 
        foo:
          summary: foo 例子
          value: {"foo": "bar"}
        bar:
          summary: bar 例子
          value: {"bar": "baz"}
    'application/xml':
      examples: 
        xmlExample:
          summary: 这是一个XML格式的例子。
          externalValue: 'http://example.org/examples/address-example.xml'
    'text/plain':
      examples:
        textExample: 
          summary: 这是一个纯文本格式的例子。
          externalValue: 'http://foo.bar/examples/address-example.txt'

In a parameter:

请求参数中的例子:

parameters:
  - name: 'zipCode'
    in: 'query'
    schema:
      type: 'string'
      format: 'zip-code'
    examples:
      zip-example: 
        $ref: '#/components/examples/zip-example'

In a response:

请求响应中的例子:

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'
responses:
  '200':
    description: 您的汽车预约已成功预订
    content: 
      application/json:
        schema:
          $ref: '#/components/schemas/SuccessResponse'
        examples:
          confirmation-success:
            $ref: '#/components/examples/confirmation-success'

Link 对象 Link Object

The Link object represents a possible design-time link for a response. The presence of a link does not guarantee the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations.

Link object代表一个设计阶段就可以确定的响应链接。 链接的存在并不保证调用者能够成功调用它,而是提供了这个响应和其他操作之间的已知关系和遍历机制。

Unlike dynamic links (i.e. links provided in the response payload), the OAS linking mechanism does not require link information in the runtime response.

动态 链接(即在响应内容中自带的链接)不同,OAS链接机制不需要运行时响应中的链接信息。

For computing links, and providing instructions to execute them, a runtime expression is used for accessing values in an operation and using them as parameters while invoking the linked operation.

为了计算链接,并提供执行链接的指令,运行时表达式用于访问操作中的值,并在调用链接操作时将其作为参数使用。

固定字段 Fixed Fields

Field Pattern Type Description
operationRef string A relative or absolute URI reference to an OAS operation. This field is mutually exclusive of the operationId field, and MUST point to an Operation Object. Relative operationRef values MAY be used to locate an existing Operation Object in the OpenAPI definition.
operationId string The name of an existing, resolvable OAS operation, as defined with a unique operationId. This field is mutually exclusive of the operationRef field.
parameters Map[string, Any | {expression}] A map representing parameters to pass to an operation as specified with operationId or identified via operationRef. The key is the parameter name to be used, whereas the value can be a constant or an expression to be evaluated and passed to the linked operation. The parameter name can be qualified using the parameter location [{in}.]{name} for operations that use the same parameter name in different locations (e.g. path.id).
requestBody Any | {expression} A literal value or {expression} to use as a request body when calling the target operation.
description string A description of the link. CommonMark syntax MAY be used for rich text representation.
server Server Object A server object to be used by the target operation.

字段名 类型 描述
operationRef string 一个OAS操作的相对或绝对URI引用。这个字段与operationId字段互斥,并且必须(MUST)指向一个操作对象。相对的operationRef值可以(MAY)用来定位OpenAPI定义中现有的操作对象。
operationId string 一个现有的、可解析的OAS操作的名称,operationId是一个OAS操作的ID, 在整个OpenAPI文档中都是唯一的。该字段与operationRef字段互斥。
parameters Map[string, Any | {expression}] 一个映射,表示要传递给操作的参数,这个操作由operationId指定或通过operationRef确定。键是要使用的参数名,而值可以是一个常量或一个表达式,这个值会被计算并提交给目标操作。对于在不同位置使用相同参数名的操作(如path.id),可以使用参数位置[{in}.]{name}来限定参数名。
requestBody Any | {expression} 调用目标操作时作为请求体的字面值或{表达式}
description string 链接对象的描述。可以 (MAY) 使用CommonMark 语法编写富文本。
server Server Object 目标操作对应的Server对象。

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

A linked operation MUST be identified using either an operationRef or operationId. In the case of an operationId, it MUST be unique and resolved in the scope of the OAS document. Because of the potential for name clashes, the operationRef syntax is preferred for specifications with external references.

链接的操作必须使用 "operationRef "或 "operationId "来识别。 如果是operationId,它必须是唯一的,并在OAS文档的范围内解决。 由于有可能发生名称冲突,对于有外部引用的规范,最好使用operationRef语法。

例子 Examples

Computing a link from a request operation where the $request.path.id is used to pass a request parameter to the linked operation.

计算来自请求操作的一个链接,其中$request.path.id用于向目标操作传递一个请求参数。

paths:
  /users/{id}:
    parameters:
    - name: id
      in: path
      required: true
      description: the user identifier, as userId 
      schema:
        type: string
    get:
      responses:
        '200':
          description: the user being returned
          content:
            application/json:
              schema:
                type: object
                properties:
                  uuid: # the unique user id
                    type: string
                    format: uuid
          links:
            address:
              # the target link operationId
              operationId: getUserAddress
              parameters:
                # get the `id` field from the request path parameter named `id`
                userId: $request.path.id
  # the path item of the linked operation
  /users/{userid}/address:
    parameters:
    - name: userid
      in: path
      required: true
      description: the user identifier, as userId 
      schema:
        type: string
    # linked operation
    get:
      operationId: getUserAddress
      responses:
        '200':
          description: the user's address
paths:
  /users/{id}:
    parameters:
    - name: id
      in: path
      required: true
      description: 用户的标识, 譬如 userId 
      schema:
        type: string
    get:
      responses:
        '200':
          description: 返回的用户
          content:
            application/json:
              schema:
                type: object
                properties:
                  uuid: # 唯一的用户ID
                    type: string
                    format: uuid
          links:
            address:
              # 目标操作的ID
              operationId: getUserAddress
              parameters:
                # 通过请求里的路径参数`id`获取用户ID
                userId: $request.path.id
  # 目标操作所在的路径
  /users/{userid}/address:
    parameters:
    - name: userid
      in: path
      required: true
      description: 用户的标识, 譬如 userId 
      schema:
        type: string
    # 目标操作
    get:
      operationId: getUserAddress
      responses:
        '200':
          description: 用户地址

When a runtime expression fails to evaluate, no parameter value is passed to the target operation.

当计算运行时表达式的值失败时,没有参数值传递给目标操作。

Values from the response body can be used to drive a linked operation.

来自响应体的值可以用来驱动目标操作。

links:
  address:
    operationId: getUserAddressByUUID
    parameters:
      # get the `uuid` field from the `uuid` field in the response body
      userUuid: $response.body#/uuid
links:
  address:
    operationId: getUserAddressByUUID
    parameters:
      # 从响应消息体提取`uuid`作为参数`userUuid`的实际值
      userUuid: $response.body#/uuid

Clients follow all links at their discretion. Neither permissions, nor the capability to make a successful call to that link, is guaranteed solely by the existence of a relationship.

客户自行决定是否跟随所有链接。 既没有权限,也没有能力对该链接进行成功的调用。 仅以关系的存在为保证。

OperationRef 例子 OperationRef Examples

As references to operationId MAY NOT be possible (the operationId is an optional field in an Operation Object), references MAY also be made through a relative operationRef:

由于operationId是操作对象中的一个可选字段, 对 operationId 的引用有时候是行不通(MAY NOT)的,因此也可以通过相对的 "operationRef "进行引用。

links:
  UserRepositories:
    # returns array of '#/components/schemas/repository'
    operationRef: '#/paths/~12.0~1repositories~1{username}/get'
    parameters:
      username: $response.body#/username
links:
  UserRepositories:
    # 返回 '#/components/schemas/repository' 数组。
    operationRef: '#/paths/~12.0~1repositories~1{username}/get'
    parameters:
      username: $response.body#/username

or an absolute operationRef:

operationRef使用绝对路径的引用例子:

links:
  UserRepositories:
    # returns array of '#/components/schemas/repository'
    operationRef: 'https://na2.gigantic-server.com/#/paths/~12.0~1repositories~1{username}/get'
    parameters:
      username: $response.body#/username
links:
  UserRepositories:
    # 返回 '#/components/schemas/repository' 数组
    operationRef: 'https://na2.gigantic-server.com/#/paths/~12.0~1repositories~1{username}/get'
    parameters:
      username: $response.body#/username

Note that in the use of operationRef, the escaped forward-slash is necessary when using JSON references.

请注意,在使用 "operationRef "时,当使用JSON引用时,必须使用转义的前斜线。

运行时表达式 Runtime Expressions

Runtime expressions allow defining values based on information that will only be available within the HTTP message in an actual API call. This mechanism is used by Link Objects and Callback Objects.

运行时表达式可以根据实际API调用中在HTTP消息里携带的信息来定义值。 这个机制用于Link ObjectsCallback Objects

The runtime expression is defined by the following ABNF syntax

运行时表达式的语法的定义遵循ABNF

      expression = ( "$url" / "$method" / "$statusCode" / "$request." source / "$response." source )
      source = ( header-reference / query-reference / path-reference / body-reference )
      header-reference = "header." token
      query-reference = "query." name  
      path-reference = "path." name
      body-reference = "body" ["#" json-pointer ]
      json-pointer    = *( "/" reference-token )
      reference-token = *( unescaped / escaped )
      unescaped       = %x00-2E / %x30-7D / %x7F-10FFFF
         ; %x2F ('/') and %x7E ('~') are excluded from 'unescaped'
      escaped         = "~" ( "0" / "1" )
        ; representing '~' and '/', respectively
      name = *( CHAR )
      token = 1*tchar
      tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." /
        "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA

Here, json-pointer is taken from RFC 6901, char from RFC 7159 and token from RFC 7230.

json-pointer 来自 RFC 6901, char 来自 RFC 7159 , token 来自 RFC 7230.

The name identifier is case-sensitive, whereas token is not.

name是区分大小写的, 而token则是不区分大小写。

The table below provides examples of runtime expressions and examples of their use in a value:

下表列出了一些运行时表达式的例子:

例子 Examples

Source Location example expression notes
HTTP Method $method The allowable values for the $method will be those for the HTTP operation.
Requested media type $request.header.accept
Request parameter $request.path.id Request parameters MUST be declared in the parameters section of the parent operation or they cannot be evaluated. This includes request headers.
Request body property $request.body#/user/uuid In operations which accept payloads, references may be made to portions of the requestBody or the entire body.
Request URL $url
Response value $response.body#/status In operations which return payloads, references may be made to portions of the response body or the entire body.
Response header $response.header.Server Single header values only are available

源位置 运行时表达式 备注
HTTP Method $method $method的允许值将是HTTP操作的值。
Requested media type $request.header.accept 单个请求消息头("accept")的值
Request parameter $request.path.id 请求参数必须(MUST)在父操作的parameters 章节有定义,否则不能用于计算。这包括请求头。
Request body property $request.body#/user/uuid 在有请求消息体的操作中,可以引用 requestBody 的部分或整个消息体。
Request URL $url 请求URL
Response value $response.body#/status 在返回有效载荷的操作中,可以对响应体的部分或整个体进行引用。
Response header $response.header.Server 单个响应消息头("Server")的值

Runtime expressions preserve the type of the referenced value. Expressions can be embedded into string values by surrounding the expression with {} curly braces.

运行时表达式会保留引用值的类型。 表达式可以通过在表达式周围加上{}大括号嵌入到字符串值中。

Header 对象 Header Object

The Header Object follows the structure of the Parameter Object with the following changes:

Header 对象除了以下改动之外与 Parameter 对象 一致:

  1. name MUST NOT be specified, it is given in the corresponding headers map.
  2. in MUST NOT be specified, it is implicitly in header.
  3. All traits that are affected by the location MUST be applicable to a location of header (for example, style).

  1. name 不能(MUST NOT)被指定,它在相应的 headers 映射中被指定。
  2. in 不能(MUST NOT)被指定,它隐含在 header 中。
  3. 所有被 location 影响的特性必须(MUST)适合 header 中的一个 location,(比如 style)。

Header 对象例子 Header Object Example

A simple header of type integer:

一个类型为 integer 的简单 header:

{
  "description": "The number of allowed requests in the current period",
  "schema": {
    "type": "integer"
  }
}
description: The number of allowed requests in the current period
schema:
  type: integer
{
  "description": "一个周期内允许的最大请求次数",
  "schema": {
    "type": "integer"
  }
}
description: 一个周期内允许的最大请求次数
schema:
  type: integer

Tag 对象 Tag Object

Adds metadata to a single tag that is used by the Operation Object. It is not mandatory to have a Tag Object per tag defined in the Operation Object instances.

为操作对象使用的单个标签添加元数据。 操作对象实例中定义的每个标签不一定要有一个标签对象。

固定字段 Fixed Fields

Field Name Type Description
name string REQUIRED. The name of the tag.
description string A short description for the tag. CommonMark syntax MAY be used for rich text representation.
externalDocs External Documentation Object Additional external documentation for this tag.

字段名 类型 描述
name string 必填. 标签名
description string 标签的描述。可以 (MAY) 使用CommonMark 语法编写富文本。
externalDocs External Documentation Object 标签的外部说明文档。

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

Tag对象例子 Tag Object Example

A simple header of type integer:

一个类型为 integer 的简单 header:

{
	"name": "pet",
	"description": "Pets operations"
}
name: pet
description: Pets operations
{
	"name": "pet",
	"description": "宠物相关操作"
}
name: pet
description: 宠物相关操作

Reference 对象 Reference Object

A simple object to allow referencing other components in the specification, internally and externally.

The Reference Object is defined by JSON Reference and follows the same structure, behavior and rules.

For this specification, reference resolution is accomplished as defined by the JSON Reference specification and not by the JSON Schema specification.

Reference是一个很简单的对象,可以通过它引用规范中的内部和外部定义的其他组件。

引用对象由 JSON Reference 定义,并遵循相同的结构、行为和规则。

对于本规范来说,引用解析是按照 JSON Reference 规范而不是 JSON Schema 规范的定义来完成的。

固定字段 Fixed Fields

Field Name Type Description
$ref string REQUIRED. The reference string.

字段名 类型 描述
$ref string 必填. 引用字符串。

This object cannot be extended with additional properties and any properties added SHALL be ignored.

此对象不能被扩展,任何附加的属性都应该(SHALL)忽略。

Reference 对象示例 Reference Object Example
{
	"$ref": "#/components/schemas/Pet"
}
$ref: '#/components/schemas/Pet'
关联外部文档示例 Relative Schema Document Example
{
  "$ref": "Pet.json"
}
$ref: Pet.yaml
关联外部文档的一部分示例 Relative Documents With Embedded Schema Example
{
  "$ref": "definitions.json#/Pet"
}
$ref: definitions.yaml#/Pet

Schema 对象 Schema Object

The Schema Object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. This object is an extended subset of the JSON Schema Specification Wright Draft 00.

Schema Object 用于定义输入和输出的数据类型。 这些类型可以是对象,但也可以是原始值和数组。 这个对象是 JSON Schema Specification Wright Draft 00 扩展后的子集.

For more information about the properties, see JSON Schema Core and JSON Schema Validation. Unless stated otherwise, the property definitions follow the JSON Schema.

关于property的的更多信息请查看 JSON Schema CoreJSON Schema Validation。 除非另有说明,否则 properties 定义遵循JSON Schema。

属性 Properties

The following properties are taken directly from the JSON Schema definition and follow the same specifications:

以下 属性 是直接从 JSON Schema 提取出来的,而且遵循同样的规范:

  • title
  • multipleOf
  • maximum
  • exclusiveMaximum
  • minimum
  • exclusiveMinimum
  • maxLength
  • minLength
  • pattern (This string SHOULD be a valid regular expression, according to the Ecma-262 Edition 5.1 regular expression dialect)
  • maxItems
  • minItems
  • uniqueItems
  • maxProperties
  • minProperties
  • required
  • enum

  • title
  • multipleOf
  • maximum
  • exclusiveMaximum
  • minimum
  • exclusiveMinimum
  • maxLength
  • minLength
  • pattern (这个字符串应该(SHOULD)是一个合法的正则表达式, 需要遵循 Ecma-262 Edition 5.1 regular expression 的语法)
  • maxItems
  • minItems
  • uniqueItems
  • maxProperties
  • minProperties
  • required
  • enum

The following properties are taken from the JSON Schema definition but their definitions were adjusted to the OpenAPI Specification.

以下 属性 是从 JSON Schema 提取出来的,但是做了一些调整以适应 OpenAPI 规范。

  • type - Value MUST be a string. Multiple types via an array are not supported.
  • allOf - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
  • oneOf - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
  • anyOf - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
  • not - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
  • items - Value MUST be an object and not an array. Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema. items MUST be present if the type is array.
  • properties - Property definitions MUST be a Schema Object and not a standard JSON Schema (inline or referenced).
  • additionalProperties - Value can be boolean or object. Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema. Consistent with JSON Schema, additionalProperties defaults to true.
  • description - CommonMark syntax MAY be used for rich text representation.
  • format - See Data Type Formats for further details. While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats.
  • default - The default value represents what would be assumed by the consumer of the input as the value of the schema if one is not provided. Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object defined at the same level. For example, if type is string, then default can be "foo" but cannot be 1.

  • type - 值必须(MUST)是一个字符串,不支持以数组形式定义多个值。
  • allOf - 内联 或 引用的 schema 必须是一个 Schema Object 且不是一个标准的 JSON Schema。
  • oneOf - 内联 或 引用的 schema 必须是一个 Schema Object 且不是一个标准的 JSON Schema。
  • anyOf - 内联 或 引用的 schema 必须是一个 Schema Object 且不是一个标准的 JSON Schema。
  • not - 内联 或 引用的 schema 必须是一个 Schema Object 且不是一个标准的 JSON Schema。
  • items - 值必须是一个对象且不是一个数组。内联 或 引用的 schema 必须是一个 Schema Object且不是一个标准的 JSON Schem。如果 type 的值是 array, items 必须有。
  • properties - 属性定义必须是一个 Schema Object 且不是一个标准的 JSON Schema (内嵌 或 引用).
  • additionalProperties - 值可以是 布尔类型 或 一个对象. 内嵌 或 引用的 schema 必须是一个 Schema Object 且不是一个标准的 JSON Schema。
  • description - 可以 (MAY) 使用CommonMark 语法编写富文本。
  • format - 更多细节请查看 Data Type Formats 。在可以通过 JSON Schema 定义格式的同时,OAS 还额外提供了一些预定义的格式。
  • default - 如果客户端没有传, 则用这里的值作为参数的默认值。与JSON Schema不同,缺省值必须符合同级Schema对象所定义的类型,例如,如果typestring,那么default可以是string,如果typestring,那么default可以是"foo",但不能是1

Alternatively, any time a Schema Object can be used, a Reference Object can be used in its place. This allows referencing definitions instead of defining them inline.

另外,任何可以使用 Schema Object 的地方都可以使用 Reference Object 替代。 通过引用一个定义来避免重复定义。

Additional properties defined by the JSON Schema specification that are not mentioned here are strictly unsupported.

未在此处提及的 JSON Schema 规范中定义的其他属性将不被支持。

Other than the JSON Schema subset fields, the following fields MAY be used for further schema documentation:

除JSON Schema子集字段外,以下字段也可用于Schema定义:

固定字段 Fixed Fields

Field Name Type Description
nullable boolean A true value adds "null" to the allowed type specified by the type keyword, only if type is explicitly defined within the same Schema Object. Other Schema Object constraints retain their defined behavior, and therefore may disallow the use of null as a value. A false value leaves the specified or default type unmodified. The default value is false.
discriminator Discriminator Object Adds support for polymorphism. The discriminator is an object name that is used to differentiate between other schemas which may satisfy the payload description. See Composition and Inheritance for more details.
readOnly boolean Relevant only for Schema "properties" definitions. Declares the property as "read only". This means that it MAY be sent as part of a response but SHOULD NOT be sent as part of the request. If the property is marked as readOnly being true and is in the required list, the required will take effect on the response only. A property MUST NOT be marked as both readOnly and writeOnly being true. Default value is false.
writeOnly boolean Relevant only for Schema "properties" definitions. Declares the property as "write only". Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response. If the property is marked as writeOnly being true and is in the required list, the required will take effect on the request only. A property MUST NOT be marked as both readOnly and writeOnly being true. Default value is false.
xml XML Object This MAY be used only on properties schemas. It has no effect on root schemas. Adds additional metadata to describe the XML representation of this property.
externalDocs External Documentation Object Additional external documentation for this schema.
example Any A free-form property to include an example of an instance for this schema. To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary.
deprecated boolean Specifies that a schema is deprecated and SHOULD be transitioned out of usage. Default value is false.

字段名 类型 描述
nullable boolean 只有当 type 在同一Schema对象中被明确定义时,true 值才会在 type 关键字指定的允许类型中添加 "null"。其他的Schema对象约束条件保留了他们定义的行为,因此可能不允许使用null作为一个值。false值会使指定的或默认的type不可修改。默认值是false
discriminator Discriminator Object 增加对多态性的支持。判别器是一个对象名称,用于区分可能满足有效载荷描述的其他模式。详见组成和继承
readOnly boolean 仅与 Schema "properties" 定义有关。 声明此属性是 "只读" 的。这意味着它可以(MAY)作为 响应 的一部分但不应该(SHOULD NOT)作为 请求 的一部分被发送。如果一个 property 的 readOnly 被标记为 true 且在 required 列表中,required 将只作用于 响应。一个 属性 的 readOnlywriteOnly 不允许同时被标记为 true。默认值是 false
writeOnly boolean 仅与 Schema "properties" 定义有关。声明此 属性 为 "只写"。所以它可以(MAY)作为 请求 的一部分而不应该(SHOULD NOT)作为 响应 的一部分被发送。如果一个 属性 的 writeOnly 被标记为 true 且在 required 列表中,required 将只作用于 请求。一个 属性 的 readOnlywriteOnly 不能同时被标记为 true。默认值是 false
xml XML Object 只能用于属性的schema, 用在根schema是没有效果的。用于为XML格式添加元数据信息。
externalDocs External Documentation Object 此 schema 附加的外部文档。
example Any 一个用于示范此 schema实例的示例,可以是任意格式。为了表达无法用 JSON 或 YAML 格式呈现的示例,可以使用 string 类型的值,但是在必要的地方需要使用字符转义。
deprecated boolean 表示一个 schema 是废弃的,应该逐渐放弃使用。默认值是 false.

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

组合和继承(多态) Composition and Inheritance (Polymorphism)

The OpenAPI Specification allows combining and extending model definitions using the allOf property of JSON Schema, in effect offering model composition. allOf takes an array of object definitions that are validated independently but together compose a single object.

OpenAPI规范允许使用JSON Schema的 allOf 属性组合和扩展模型定义,提供了模型组合的能力。 allOf是一个对象定义的数组,这些对象定义是独立的,但共同组成一个对象。

While composition offers model extensibility, it does not imply a hierarchy between the models. To support polymorphism, the OpenAPI Specification adds the discriminator field. When used, the discriminator will be the name of the property that decides which schema definition validates the structure of the model. As such, the discriminator field MUST be a required field. There are two ways to define the value of a discriminator for an inheriting instance.

  • Use the schema name.
  • Override the schema name by overriding the property with a new value. If a new value exists, this takes precedence over the schema name. As such, inline schema definitions, which do not have a given id, cannot be used in polymorphism.

虽然组合提供了模型的可扩展性,但它并不意味着模型之间的层次结构。 为了支持多态性,OpenAPI规范增加了discriminator字段。 当使用时,discriminator将是决定根据哪个属性判断使用哪个模式定义来验证模型的结构。 因此,discriminator字段必须(MUST)是一个必填字段。 有两种方法来定义继承实例的判别器的值。

  • 使用模式名。
  • 通过用一个新的值覆盖该属性来覆盖模式名。如果存在新的值,则优先于模式名。 因此,没有给定id的内联模式定义,不能在多态中使用。

XML建模 XML Modeling

The xml property allows extra definitions when translating the JSON definition to XML. The XML Object contains additional information about the available options.

xml 属性允许在将JSON定义翻译成XML时进行额外的定义。 XML 对象 包含了关于可用选项的额外信息。

Schema 对象例子 Schema Object Examples
原始类型例子 Primitive Sample
{
  "type": "string",
  "format": "email"
}
type: string
format: email
简单模型 Simple Model
{
  "type": "object",
  "required": [
    "name"
  ],
  "properties": {
    "name": {
      "type": "string"
    },
    "address": {
      "$ref": "#/components/schemas/Address"
    },
    "age": {
      "type": "integer",
      "format": "int32",
      "minimum": 0
    }
  }
}
type: object
required:
- name
properties:
  name:
    type: string
  address:
    $ref: '#/components/schemas/Address'
  age:
    type: integer
    format: int32
    minimum: 0
包含有子对象(Map/Dictionary)的模型 Model with Map/Dictionary Properties

For a simple string to string mapping:

字符串和字符串的映射例子:

{
  "type": "object",
  "additionalProperties": {
    "type": "string"
  }
}
type: object
additionalProperties:
  type: string

For a string to model mapping:

字符串和子对象的映射例子:

{
  "type": "object",
  "additionalProperties": {
    "$ref": "#/components/schemas/ComplexModel"
  }
}
type: object
additionalProperties:
  $ref: '#/components/schemas/ComplexModel'
带有例子的模型的例子 Model with Example
{
  "type": "object",
  "properties": {
    "id": {
      "type": "integer",
      "format": "int64"
    },
    "name": {
      "type": "string"
    }
  },
  "required": [
    "name"
  ],
  "example": {
    "name": "Puma",
    "id": 1
  }
}
type: object
properties:
  id:
    type: integer
    format: int64
  name:
    type: string
required:
- name
example:
  name: Puma
  id: 1
带有组合的模型的例子 Models with Composition
{
  "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"
              }
            }
          }
        ]
      }
    }
  }
}
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
支持多态的模型的例子 Models with Polymorphism Support
{
  "components": {
    "schemas": {
      "Pet": {
        "type": "object",
        "discriminator": {
          "propertyName": "petType"
        },
        "properties": {
          "name": {
            "type": "string"
          },
          "petType": {
            "type": "string"
          }
        },
        "required": [
          "name",
          "petType"
        ]
      },
      "Cat": {
        "description": "A representation of a cat. Note that `Cat` will be used as the discriminator value.",
        "allOf": [
          {
            "$ref": "#/components/schemas/Pet"
          },
          {
            "type": "object",
            "properties": {
              "huntingSkill": {
                "type": "string",
                "description": "The measured skill for hunting",
                "default": "lazy",
                "enum": [
                  "clueless",
                  "lazy",
                  "adventurous",
                  "aggressive"
                ]
              }
            },
            "required": [
              "huntingSkill"
            ]
          }
        ]
      },
      "Dog": {
        "description": "A representation of a dog. Note that `Dog` will be used as the discriminator value.",
        "allOf": [
          {
            "$ref": "#/components/schemas/Pet"
          },
          {
            "type": "object",
            "properties": {
              "packSize": {
                "type": "integer",
                "format": "int32",
                "description": "the size of the pack the dog is from",
                "default": 0,
                "minimum": 0
              }
            },
            "required": [
              "packSize"
            ]
          }
        ]
      }
    }
  }
}
components:
  schemas:
    Pet:
      type: object
      discriminator:
        propertyName: petType
      properties:
        name:
          type: string
        petType:
          type: string
      required:
      - name
      - petType
    Cat:  ## "Cat" will be used as the discriminator value
      description: A representation of a cat
      allOf:
      - $ref: '#/components/schemas/Pet'
      - type: object
        properties:
          huntingSkill:
            type: string
            description: The measured skill for hunting
            enum:
            - clueless
            - lazy
            - adventurous
            - aggressive
        required:
        - huntingSkill
    Dog:  ## "Dog" will be used as the discriminator value
      description: A representation of a dog
      allOf:
      - $ref: '#/components/schemas/Pet'
      - type: object
        properties:
          packSize:
            type: integer
            format: int32
            description: the size of the pack the dog is from
            default: 0
            minimum: 0
        required:
        - packSize
{
  "components": {
    "schemas": {
      "Pet": {
        "type": "object",
        "discriminator": {
          "propertyName": "petType"
        },
        "properties": {
          "name": {
            "type": "string"
          },
          "petType": {
            "type": "string"
          }
        },
        "required": [
          "name",
          "petType"
        ]
      },
      "Cat": {
        "description": "代表一只猫。请注意,`Cat` 将被用作判别值。",
        "allOf": [
          {
            "$ref": "#/components/schemas/Pet"
          },
          {
            "type": "object",
            "properties": {
              "huntingSkill": {
                "type": "string",
                "description": "狩猎技能的度量值",
                "default": "lazy",
                "enum": [
                  "clueless",
                  "lazy",
                  "adventurous",
                  "aggressive"
                ]
              }
            },
            "required": [
              "huntingSkill"
            ]
          }
        ]
      },
      "Dog": {
        "description": "代表一只狗。请注意,`Dog` 将被用作判别值。",
        "allOf": [
          {
            "$ref": "#/components/schemas/Pet"
          },
          {
            "type": "object",
            "properties": {
              "packSize": {
                "type": "integer",
                "format": "int32",
                "description": "犬群的大小",
                "default": 0,
                "minimum": 0
              }
            },
            "required": [
              "packSize"
            ]
          }
        ]
      }
    }
  }
}
components:
  schemas:
    Pet:
      type: object
      discriminator:
        propertyName: petType
      properties:
        name:
          type: string
        petType:
          type: string
      required:
      - name
      - petType
    Cat:  ## `Cat` 将被用作判别值。
      description: 代表一只猫。
      allOf:
      - $ref: '#/components/schemas/Pet'
      - type: object
        properties:
          huntingSkill:
            type: string
            description: 狩猎技能的度量值
            enum:
            - clueless
            - lazy
            - adventurous
            - aggressive
        required:
        - huntingSkill
    Dog:  ## `Dog` 将被用作判别值。
      description: 代表一只狗。
      allOf:
      - $ref: '#/components/schemas/Pet'
      - type: object
        properties:
          packSize:
            type: integer
            format: int32
            description: 犬群的大小
            default: 0
            minimum: 0
        required:
        - packSize

Discriminator 对象 Discriminator Object

When request bodies or response payloads may be one of a number of different schemas, a discriminator object can be used to aid in serialization, deserialization, and validation.
The discriminator is a specific object in a schema which is used to inform the consumer of the specification of an alternative schema based on the value associated with it.

Discriminator的含义是判别,鉴别。 当请求消息体或响应消息体可能是若干不同模式(schema)之一时,可以使用 discriminator 对象来帮助序列化、反序列化和验证。 鉴别器是模式中的一个特定对象,用于根据与之相关的值向消费者通报替代成不同的模式(schema)。

When using the discriminator, inline schemas will not be considered.

当使用 discriminator 时,_内嵌式_模式(schema)会被忽略。

固定字段 Fixed Fields

Field Name Type Description
propertyName string REQUIRED. The name of the property in the payload that will hold the discriminator value.
mapping Map[string, string] An object to hold mappings between payload values and schema names or references.

字段名 类型 描述
propertyName string 必填. 在 消息体 中表示 discriminator 值的属性的名称。
mapping Map[string, string] 一个映射 消息体 中的值和 schema 名称或引用的对象。

The discriminator object is legal only when using one of the composite keywords oneOf, anyOf, allOf.

discriminator 属性仅在与 oneOf, anyOf, allOf 这几个复合关键字之一一起使用时才合法.

In OAS 3.0, a response payload MAY be described to be exactly one of any number of types:

在 OAS 3.0 中,一个 响应消息体 仅可以(MAY)使用一种类型来描述:

MyResponseType:
  oneOf:
  - $ref: '#/components/schemas/Cat'
  - $ref: '#/components/schemas/Dog'
  - $ref: '#/components/schemas/Lizard'

which means the payload MUST, by validation, match exactly one of the schemas described by Cat, Dog, or Lizard.
In this case, a discriminator MAY act as a "hint" to shortcut validation and selection of the matching schema which may be a costly operation, depending on the complexity of the schema. We can then describe exactly which field tells us which schema to use:

也就是说 payload 必须 且只能满足 CatDogLizzard schemas 中的一个。 在这种情况下,判别器可以作为一个 "提示",以缩短验证和选择匹配模式的时间,这可能是一个昂贵的操作,取决于模式的复杂性。 然后,我们可以准确地描述哪个字段告诉我们要使用哪个模式。

MyResponseType:
  oneOf:
  - $ref: '#/components/schemas/Cat'
  - $ref: '#/components/schemas/Dog'
  - $ref: '#/components/schemas/Lizard'
  discriminator:
    propertyName: petType

The expectation now is that a property with name petType MUST be present in the response payload, and the value will correspond to the name of a schema defined in the OAS document.
Thus the response payload:

现在的期望是在响应有效载荷中必须有一个名为petType的属性。 和值将对应于OAS文档中定义的模式名称。 因此,响应有效载荷。

{
  "id": 12345,
  "petType": "Cat"
}

Will indicate that the Cat schema be used in conjunction with this payload.

将表明 Cat 模式将与该有效载荷一起使用。

In scenarios where the value of the discriminator field does not match the schema name or implicit mapping is not possible, an optional mapping definition MAY be used:

在判别器字段的值与模式名称不匹配或隐式映射不可能的情况下,可以(MAY)使用一个可选的 "映射 "定义。

MyResponseType:
  oneOf:
  - $ref: '#/components/schemas/Cat'
  - $ref: '#/components/schemas/Dog'
  - $ref: '#/components/schemas/Lizard'
  - $ref: 'https://gigantic-server.com/schemas/Monster/schema.json'
  discriminator:
    propertyName: petType
    mapping:
      dog: '#/components/schemas/Dog'
      monster: 'https://gigantic-server.com/schemas/Monster/schema.json'

Here the discriminator value of dog will map to the schema #/components/schemas/Dog, rather than the default (implicit) value of Dog.
If the discriminator value does not match an implicit or explicit mapping, no schema can be determined and validation SHOULD fail. Mapping keys MUST be string values, but tooling MAY convert response values to strings for comparison.

dog 的判别器 将映射到模式 #/components/schemas/Dog,而不是默认(隐式)的 Dog 值。 如果判别器的 不匹配隐式或显式映射,则无法确定模式,验证也会失败。 映射键必须(MUST)是字符串值,但工具可以(MAY)将响应值转换为字符串进行比较。

When used in conjunction with the anyOf construct, the use of the discriminator can avoid ambiguity where multiple schemas may satisfy a single payload.

当与 anyOf 结构结合使用时,辨别器的使用可以避免在多个模式可能满足单一有效载荷的情况下出现歧义。

In both the oneOf and anyOf use cases, all possible schemas MUST be listed explicitly.
To avoid redundancy, the discriminator MAY be added to a parent schema definition, and all schemas comprising the parent schema in an allOf construct may be used as an alternate schema.

oneOfanyOf 两种用例中,所有可能的模式都必须明确列出。 为了避免冗余,可(MAY)将判别器添加到父模式定义中,并且在 allOf 结构中包含父模式的所有模式都可作为替代模式使用。

For example:

例如:

components:
  schemas:
    Pet:
      type: object
      required:
      - petType
      properties:
        petType:
          type: string
      discriminator:
        propertyName: petType
        mapping:
          dog: Dog
    Cat:
      allOf:
      - $ref: '#/components/schemas/Pet'
      - type: object
        # all other properties specific to a `Cat`
        properties:
          name:
            type: string
    Dog:
      allOf:
      - $ref: '#/components/schemas/Pet'
      - type: object
        # all other properties specific to a `Dog`
        properties:
          bark:
            type: string
    Lizard:
      allOf:
      - $ref: '#/components/schemas/Pet'
      - type: object
        # all other properties specific to a `Lizard`
        properties:
          lovesRocks:
            type: boolean

a payload like this:

消息体类似这样:

{
  "petType": "Cat",
  "name": "misty"
}

will indicate that the Cat schema be used. Likewise this schema:

会匹配到Cat模式, 而

{
  "petType": "dog",
  "bark": "soft"
}

will map to Dog because of the definition in the mappings element.

则会匹配到Dog模式, 因为在 mappings 属性中指定了映射关系。

XML 对象 XML Object

A metadata object that allows for more fine-tuned XML model definitions.

一个为了可以更好的定义XML模型而设计的元数据对象。

When using arrays, XML element names are not inferred (for singular/plural forms) and the name property SHOULD be used to add that information. See examples for expected behavior.

当使用数组时,不会推测 XML 元素的名称(单数或复数形式),所以应该(SHOULD)添加 name 属性来提供此信息。 相关内容请直接查看后续的例子章节。

固定字段 Fixed Fields

Field Name Type Description
name string Replaces the name of the element/attribute used for the described schema property. When defined within items, it will affect the name of the individual XML elements within the list. When defined alongside type being array (outside the items), it will affect the wrapping element and only if wrapped is true. If wrapped is false, it will be ignored.
namespace string The URI of the namespace definition. Value MUST be in the form of an absolute URI.
prefix string The prefix to be used for the name.
attribute boolean Declares whether the property definition translates to an attribute instead of an element. Default value is false.
wrapped boolean MAY be used only for an array definition. Signifies whether the array is wrapped (for example, <books><book/><book/></books>) or unwrapped (<book/><book/>). Default value is false. The definition takes effect only when defined alongside type being array (outside the items).

字段名 类型 描述
name string 替换用于描述元素/属性的结构属性(schema property)的名称。当在 items 内定义时将会影响处于此列表中的每个元素的名称。当定义于 items 之上时将会影响它所包裹的元素且仅当 wrappedtrue 时,如果 wrappedfalse 时它将会被忽略。
namespace string 命名空间定义的 URI。其值必须是绝对 URI。
prefix string 用于 name 的前缀。
attribute boolean 声明此特性定义会被转换为一个属性而不是一个元素。默认值是 false
wrapped boolean 只可(MAY)用于数组定义。表示数组是否被包裹(比如, <books><book/><book/></books>)或未被包裹(<book/><book/>)。默认值是 false。此定义只在 typearray(位于 items 之上) 时生效。

This object MAY be extended with Specification Extensions.

这个对象是个可扩展对象, 可以 (MAY) 按照 Specification Extensions 中的说明进行扩展。

XML 对象例子 XML Object Examples

The examples of the XML object definitions are included inside a property definition of a Schema Object with a sample of the XML representation of it.

XML 对象定义的示例被包括在一个 Schema 对象 的属性定义并带有一个样例 XML 来呈现它。

没有XML节点 No XML Element

Basic string property:

基础字符串属性:

{
    "animals": {
        "type": "string"
    }
}
animals:
  type: string
<animals>...</animals>

Basic string array property (wrapped is false by default):

基础字符串数组属性 (wrapped 默认是 false):

{
    "animals": {
        "type": "array",
        "items": {
            "type": "string"
        }
    }
}
animals:
  type: array
  items:
    type: string
<animals>...</animals>
<animals>...</animals>
<animals>...</animals>
XML 名称替换 XML Name Replacement
{
  "animals": {
    "type": "string",
    "xml": {
      "name": "animal"
    }
  }
}
animals:
  type: string
  xml:
    name: animal
<animal>...</animal>
XML 属性,前缀和命名空间 XML Attribute, Prefix and Namespace

In this example, a full model definition is shown.

在此示例中展示了一个完整的模型定义。

{
  "Person": {
    "type": "object",
    "properties": {
      "id": {
        "type": "integer",
        "format": "int32",
        "xml": {
          "attribute": true
        }
      },
      "name": {
        "type": "string",
        "xml": {
          "namespace": "http://example.com/schema/sample",
          "prefix": "sample"
        }
      }
    }
  }
}
Person:
  type: object
  properties:
    id:
      type: integer
      format: int32
      xml:
        attribute: true
    name:
      type: string
      xml:
        namespace: http://example.com/schema/sample
        prefix: sample
<Person id="123">
    <sample:name xmlns:sample="http://example.com/schema/sample">example</sample:name>
</Person>
XML 数组 XML Arrays

Changing the element names:

改变元素的名称:

{
  "animals": {
    "type": "array",
    "items": {
      "type": "string",
      "xml": {
        "name": "animal"
      }
    }
  }
}
animals:
  type: array
  items:
    type: string
    xml:
      name: animal
<animal>value</animal>
<animal>value</animal>

The external name property has no effect on the XML:

外部的 name 属性在 XML 上不产生效果:

{
  "animals": {
    "type": "array",
    "items": {
      "type": "string",
      "xml": {
        "name": "animal"
      }
    },
    "xml": {
      "name": "aliens"
    }
  }
}
animals:
  type: array
  items:
    type: string
    xml:
      name: animal
  xml:
    name: aliens
<animal>value</animal>
<animal>value</animal>

Even when the array is wrapped, if a name is not explicitly defined, the same name will be used both internally and externally:

尽管数组是被包裹的,如果没有明确定义一个名称,那么同样地名称会被用于内部和外部:

{
  "animals": {
    "type": "array",
    "items": {
      "type": "string"
    },
    "xml": {
      "wrapped": true
    }
  }
}
animals:
  type: array
  items:
    type: string
  xml:
    wrapped: true
<animals>
  <animals>value</animals>
  <animals>value</animals>
</animals>

To overcome the naming problem in the example above, the following definition can be used:

为了解决上面示例的命名问题,可以使用下面的定义:

{
  "animals": {
    "type": "array",
    "items": {
      "type": "string",
      "xml": {
        "name": "animal"
      }
    },
    "xml": {
      "wrapped": true
    }
  }
}
animals:
  type: array
  items:
    type: string
    xml:
      name: animal
  xml:
    wrapped: true
<animals>
  <animal>value</animal>
  <animal>value</animal>
</animals>

Affecting both internal and external names:

影响内部和外部名称:

{
  "animals": {
    "type": "array",
    "items": {
      "type": "string",
      "xml": {
        "name": "animal"
      }
    },
    "xml": {
      "name": "aliens",
      "wrapped": true
    }
  }
}
animals:
  type: array
  items:
    type: string
    xml:
      name: animal
  xml:
    name: aliens
    wrapped: true
<aliens>
  <animal>value</animal>
  <animal>value</animal>
</aliens>

If we change the external element but not the internal ones:

如果我们只想改变外部元素而不是内部元素的标签名:

{
  "animals": {
    "type": "array",
    "items": {
      "type": "string"
    },
    "xml": {
      "name": "aliens",
      "wrapped": true
    }
  }
}
animals:
  type: array
  items:
    type: string
  xml:
    name: aliens
    wrapped: true
<aliens>
  <aliens>value</aliens>
  <aliens>value</aliens>
</aliens>

Security Scheme 对象 Security Scheme Object

Defines a security scheme that can be used by the operations. Supported schemes are HTTP authentication, an API key (either as a header, a cookie parameter or as a query parameter), OAuth2's common flows (implicit, password, client credentials and authorization code) as defined in RFC6749, and OpenID Connect Discovery.

定义一个用于 操作(operations) 的 security scheme。 被支持的 schemes 有 HTTP 认证, 一个 API key(作为 header , cookie 或 query parameter), 定义于RFC6749 的 Oauth2 常用流程(implicit、password、client credentials 和 authorization code) 和 OpenID Connect Discovery

固定字段 Fixed Fields

Field Name Type Applies To Description
type string Any REQUIRED. The type of the security scheme. Valid values are "apiKey", "http", "oauth2", "openIdConnect".
description string Any A short description for security scheme. CommonMark syntax MAY be used for rich text representation.
name string apiKey REQUIRED. The name of the header, query or cookie parameter to be used.
in string apiKey REQUIRED. The location of the API key. Valid values are "query", "header" or "cookie".
scheme string http REQUIRED. The name of the HTTP Authorization scheme to be used in the Authorization header as defined in RFC7235. The values used SHOULD be registered in the IANA Authentication Scheme registry.
bearerFormat string http ("bearer") A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes.
flows OAuth Flows Object oauth2 REQUIRED. An object containing configuration information for the flow types supported.
openIdConnectUrl string openIdConnect REQUIRED. OpenId Connect URL to discover OAuth2 configuration values. This MUST be in the form of a URL.

字段名 类型 适用于 描述
type string Any 必填. security scheme 的类型。有效值包括 "apiKey", "http", "oauth2", "openIdConnect".
description string Any 对 security scheme 的简短描述. CommonMark syntax可以被用来呈现富文本格式.
name string apiKey 必填. 用于 header、 query 或 cookie 的参数名字。
in string apiKey 必填. API key 的位置。有效值包括 "query""header""cookie".
scheme string http 必填. 用于 RFC7235定义的认证头 的 HTTP Auahorization scheme 的名字.
bearerFormat string http ("bearer") 用于提示客户端所使用的bearer token的格式。Bearer token 通常通过一个认证服务器生成,所以这个字段最主要的目的是用来记录这个信息。
flows OAuth Flows Object oauth2 必填. 一个包含所支持的 flow types 的配置信息的对象。
openIdConnectUrl string openIdConnect 必填. 用于发现 OAuth2 配置值的OpenId Connect URL,必须是 URL 形式。

This object MAY be extended with Specification Extensions.

这个对象可能会被规范扩展扩展。

Security Scheme 对象例子 Security Scheme Object Example
HTTP Basic 认证例子 Basic Authentication Sample
{
  "type": "http",
  "scheme": "basic"
}
type: http
scheme: basic
API Key 例子 API Key Sample
{
  "type": "apiKey",
  "name": "api_key",
  "in": "header"
}
type: apiKey
name: api_key
in: header
JWT 例子 JWT Bearer Sample
{
  "type": "http",
  "scheme": "bearer",
  "bearerFormat": "JWT"
}
type: http
scheme: bearer
bearerFormat: JWT
Implicit OAuth2 例子 Implicit OAuth2 Sample
{
  "type": "oauth2",
  "flows": {
    "implicit": {
      "authorizationUrl": "https://example.com/api/oauth/dialog",
      "scopes": {
        "write:pets": "modify pets in your account",
        "read:pets": "read your pets"
      }
    }
  }
}
type: oauth2
flows: 
  implicit:
    authorizationUrl: https://example.com/api/oauth/dialog
    scopes:
      write:pets: modify pets in your account
      read:pets: read your pets
{
  "type": "oauth2",
  "flows": {
    "implicit": {
      "authorizationUrl": "https://example.com/api/oauth/dialog",
      "scopes": {
        "write:pets": "修改你账户里的宠物信息",
        "read:pets": "获取你账户里的宠物信息"
      }
    }
  }
}
type: oauth2
flows: 
  implicit:
    authorizationUrl: https://example.com/api/oauth/dialog
    scopes:
      write:pets: 修改你账户里的宠物信息
      read:pets: 获取你账户里的宠物信息

OAuth Flows 对象 OAuth Flows Object

Allows configuration of the supported OAuth Flows.

用于配置受支持的OAuth Flows。

固定字段 Fixed Fields

Field Name Type Description
implicit OAuth Flow Object Configuration for the OAuth Implicit flow
password OAuth Flow Object Configuration for the OAuth Resource Owner Password flow
clientCredentials OAuth Flow Object Configuration for the OAuth Client Credentials flow. Previously called application in OpenAPI 2.0.
authorizationCode OAuth Flow Object Configuration for the OAuth Authorization Code flow. Previously called accessCode in OpenAPI 2.0.

字段名 类型 描述
implicit OAuth Flow Object OAuth Implicit flow 的配置
password OAuth Flow Object OAuth Resource Owner Password flow 的配置
clientCredentials OAuth Flow Object OAuth Client Credentials flow 的配置。在 OpenAPI 2.0 中曾被称作 application
authorizationCode OAuth Flow Object OAuth Authorization Code flow 的配置。在 OpenAPI 2.0 中曾被称作 accessCode

This object MAY be extended with Specification Extensions.

这个对象可能会被规范扩展扩展。

OAuth Flow 对象 OAuth Flow Object

Configuration details for a supported OAuth Flow

支持的 OAuth Flow 的配置详情。

固定字段 Fixed Fields

Field Name Type Applies To Description
authorizationUrl string oauth2 ("implicit", "authorizationCode") REQUIRED. The authorization URL to be used for this flow. This MUST be in the form of a URL.
tokenUrl string oauth2 ("password", "clientCredentials", "authorizationCode") REQUIRED. The token URL to be used for this flow. This MUST be in the form of a URL.
refreshUrl string oauth2 The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL.
scopes Map[string, string] oauth2 REQUIRED. The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. The map MAY be empty.

字段名 类型 适用于 描述
authorizationUrl string oauth2 ("implicit", "authorizationCode") 必填。用于此流程的 认证 URL。必须是 URL 形式。
tokenUrl string oauth2 ("password", "clientCredentials", "authorizationCode") 必填。用于此流程的 token URL。必须是 URL 形式。
refreshUrl string oauth2 用于获取 refresh tokens 的 URL,必须是 URL 形式。
scopes Map[string, string] oauth2 必填。可用于 OAuth2 security scheme 的 scope。scope 名称与其简短描述的映射。

This object MAY be extended with Specification Extensions.

这个对象可能会被规范扩展扩展。

OAuth Flow 对象例子 OAuth Flow Object Examples
{
  "type": "oauth2",
  "flows": {
    "implicit": {
      "authorizationUrl": "https://example.com/api/oauth/dialog",
      "scopes": {
        "write:pets": "modify pets in your account",
        "read:pets": "read your pets"
      }
    },
    "authorizationCode": {
      "authorizationUrl": "https://example.com/api/oauth/dialog",
      "tokenUrl": "https://example.com/api/oauth/token",
      "scopes": {
        "write:pets": "modify pets in your account",
        "read:pets": "read your pets"
      }
    }
  }
}
type: oauth2
flows: 
  implicit:
    authorizationUrl: https://example.com/api/oauth/dialog
    scopes:
      write:pets: modify pets in your account
      read:pets: read your pets
  authorizationCode:
    authorizationUrl: https://example.com/api/oauth/dialog
    tokenUrl: https://example.com/api/oauth/token
    scopes:
      write:pets: modify pets in your account
      read:pets: read your pets 
{
  "type": "oauth2",
  "flows": {
    "implicit": {
      "authorizationUrl": "https://example.com/api/oauth/dialog",
      "scopes": {
        "write:pets": "修改你账户里的宠物信息",
        "read:pets": "获取你账户里的宠物信息"
      }
    },
    "authorizationCode": {
      "authorizationUrl": "https://example.com/api/oauth/dialog",
      "tokenUrl": "https://example.com/api/oauth/token",
      "scopes": {
        "write:pets": "修改你账户里的宠物信息",
        "read:pets": "获取你账户里的宠物信息"
      }
    }
  }
}
type: oauth2
flows: 
  implicit:
    authorizationUrl: https://example.com/api/oauth/dialog
    scopes:
      write:pets: 修改你账户里的宠物信息
      read:pets: 获取你账户里的宠物信息
  authorizationCode:
    authorizationUrl: https://example.com/api/oauth/dialog
    tokenUrl: https://example.com/api/oauth/token
    scopes:
      write:pets: 修改你账户里的宠物信息
      read:pets: 获取你账户里的宠物信息

Security Requirement 对象 Security Requirement Object

Lists the required security schemes to execute this operation. The name used for each property MUST correspond to a security scheme declared in the Security Schemes under the Components Object.

列出执行某 操作 所需的 security schemes。 每个属性的名字都必须(MUST)与 Components ObjectSecurity Schemes 声明的 security scheme 相符。

Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a request to be authorized. This enables support for scenarios where multiple query parameters or HTTP headers are required to convey security information.

包含多个 schemes 的 Security Requirement 对象中的所有 scheme 都必须(MUST)要满足授权请求。 通过这种方式就能够支持需要使用多个 URL上的查询参数 或 HTTP消息头 来传递安全信息的情景。

When a list of Security Requirement Objects is defined on the OpenAPI Object or Operation Object, only one of the Security Requirement Objects in the list needs to be satisfied to authorize the request.

Open API 对象 或 [Operation 对象] (#operationObject) 包含一组 Security Requirement 对象时,请求只需要满足其中一个即可。

模式化字段 Patterned Fields

Field Pattern Type Description
{name} [string] Each name MUST correspond to a security scheme which is declared in the Security Schemes under the Components Object. If the security scheme is of type "oauth2" or "openIdConnect", then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope. For other security scheme types, the array MUST be empty.

字段名模式 类型 描述
{name} [string] 每个名称都必须对应于 Components 对象 下的 Security Schemes 的一个 security scheme。如果此 security scheme 是 "oauth2""openIdConnect" 类型,那么其值是用于执行的一组 scope names。对于其他 security scheme 类型。此数组必须是空的。

Security Requirement Object ExamplesSecurity Requirement 对象例子 Security Requirement Object Examples
非 OAuth2 Security Requirement Non-OAuth2 Security Requirement
{
  "api_key": []
}
api_key: []
OAuth2 Security RequirementOAuth2 Security Requirement Non-OAuth2 Security Requirement
{
  "petstore_auth": [
    "write:pets",
    "read:pets"
  ]
}
petstore_auth:
- write:pets
- read:pets
可选 OAuth2 SecurityOptional OAuth2 Security Non-OAuth2 Security Requirement

Optional OAuth2 security as would be defined in an OpenAPI Object or an Operation Object:

OpenAPI对象操作对象中定义的可选OAuth2安全性。

{
  "security": [
    {},
    {
      "petstore_auth": [
        "write:pets",
        "read:pets"
      ]
    }
  ]
}
security:
  - {}
  - petstore_auth:
    - write:pets
    - read:pets

扩展规范 Specification Extensions

While the OpenAPI Specification tries to accommodate most use cases, additional data can be added to extend the specification at certain points.

尽管 OpenAPI 规范 尝试包含大部分的使用场景,在需要时仍然可以通过额外数据来扩展此规范。

The extensions properties are implemented as patterned fields that are always prefixed by "x-".

扩展属性作为模式化字段实现,总是以"x-"为前缀。

Field Pattern Type Description
^x- Any Allows extensions to the OpenAPI Schema. The field name MUST begin with x-, for example, x-internal-id. The value can be null, a primitive, an array or an object. Can have any valid JSON format value.

字段名模式 类型 描述
^x- Any 允许对OpenAPI Schema进行扩展。字段名必须以x-开头,例如x-internal-id。值可以是null,一个基元,一个数组或一个对象。可以包含任意有效的JSON格式值。

The extensions may or may not be supported by the available tooling, but those may be extended as well to add requested support (if tools are internal or open-sourced).

现有的工具可能支持或不支持这些扩展,但也可以扩展这些扩展以增加所要求的支持(如果工具是内部的或开源的)。

过滤敏感信息 Security Filtering

Some objects in the OpenAPI Specification MAY be declared and remain empty, or be completely removed, even though they are inherently the core of the API documentation.

OpenAPI规范中的一些对象可以(MAY)被声明并保持为空,或者被完全删除,即使它们本质上是API文档的核心。

The reasoning is to allow an additional layer of access control over the documentation. While not part of the specification itself, certain libraries MAY choose to allow access to parts of the documentation based on some form of authentication/authorization.

这样做的原因是为了允许对文档进行额外的访问控制。 虽然不是规范本身的一部分,但某些库可以选择允许基于某种形式的认证/授权来访问文档的一部分。

Two examples of this:

  1. The Paths Object MAY be empty. It may be counterintuitive, but this may tell the viewer that they got to the right place, but can't access any documentation. They'd still have access to the Info Object which may contain additional information regarding authentication.
  2. The Path Item Object MAY be empty. In this case, the viewer will be aware that the path exists, but will not be able to see any of its operations or parameters. This is different from hiding the path itself from the Paths Object, because the user will be aware of its existence. This allows the documentation provider to finely control what the viewer can see.

以下是两个例子。

  1. Paths 对象可能(MAY)是空的。这可能是反直觉的,但这可能会告诉浏览者他们到了正确的地方,但不能访问任何文档。他们仍然可以Info 对象,其中可能包含有关认证的附加信息。
  2. Path Item 对象 可能(MAY)是空的。在这种情况下,浏览者将知道路径的存在,但无法看到它的任何操作或参数。这与在 Paths 对象 中隐藏路径本身是不同的,因为用户将知道它的存在。这使得文档提供者可以精细地控制浏览者可以看到的内容。

附录A: 版本历史 Appendix A: Revision History

Version Date Notes
3.0.3 2020-02-20 Patch release of the OpenAPI Specification 3.0.3
3.0.2 2018-10-08 Patch release of the OpenAPI Specification 3.0.2
3.0.1 2017-12-06 Patch release of the OpenAPI Specification 3.0.1
3.0.0 2017-07-26 Release of the OpenAPI Specification 3.0.0
3.0.0-rc2 2017-06-16 rc2 of the 3.0 specification
3.0.0-rc1 2017-04-27 rc1 of the 3.0 specification
3.0.0-rc0 2017-02-28 Implementer's Draft of the 3.0 specification
2.0 2015-12-31 Donation of Swagger 2.0 to the OpenAPI Initiative
2.0 2014-09-08 Release of Swagger 2.0
1.2 2014-03-14 Initial release of the formal document.
1.1 2012-08-22 Release of Swagger 1.1
1.0 2011-08-10 First release of the Swagger Specification
版本 日期 备注
3.0.3 2020-02-20 OpenAPI规范的3.0.3补丁发布。
3.0.2 2018-10-08 OpenAPI规范的3.0.2补丁发布。
3.0.1 2017-12-06 OpenAPI规范的3.0.1补丁发布。
3.0.0 2017-07-26 OpenAPI 规范 3.0.0 发布
3.0.0-rc2 2017-06-16 3.0规范的rc2
3.0.0-rc1 2017-04-27 3.0规范的rc1
3.0.0-rc0 2017-02-28 3.0规范的实施者草案
2.0 2015-12-31 向OpenAPI倡议捐赠Swagger 2.0。
2.0 2014-09-08 Swagger 2.0 发布
1.2 2014-03-14 正式文件的首次发布。
1.1 2012-08-22 Swagger 1.1 发布
1.0 2011-08-10 第一个Swagger规范发布