OpenAPI 规范
版本 3.0.3
本文档中的关键词 “必须 (MUST)”、“禁止 (MUST NOT)”、“需要 (REQUIRED)”、“应当 (SHALL)”、“不得 (SHALL NOT)”、“应该 (SHOULD)”、“不应该 (SHOULD NOT)”、“推荐 (RECOMMENDED)”、“不推荐 (NOT RECOMMENDED)”、“可以 (MAY)” 和 “可选 (OPTIONAL)” 按照 BCP 14 RFC2119 RFC8174 中的描述进行解释,当且仅当它们全部以大写字母出现时,如本文所示。
本文档在 Apache 许可证 2.0 版 下获得许可。
简介
OpenAPI 规范 (OAS) 定义了一个标准、与语言无关的 RESTful API 接口,它允许人类和计算机在无需访问源代码、文档或通过网络流量检查的情况下,发现和理解服务的功能。如果定义正确,消费者可以以最少的实现逻辑理解远程服务并与之交互。
OpenAPI 定义随后可被文档生成工具用于显示 API,代码生成工具用于生成各种编程语言的服务器和客户端,以及测试工具和许多其他用例。
目录
定义
OpenAPI 文档
定义或描述 API 的文档(或一组文档)。OpenAPI 定义使用并符合 OpenAPI 规范。
路径模板
路径模板是指使用花括号 ({}) 分隔的模板表达式来标记 URL 路径的一部分,该部分可以使用路径参数替换。
路径中的每个模板表达式必须对应于 路径项本身和/或每个路径项的操作中包含的路径参数。
媒体类型定义分布在多个资源中。媒体类型定义应符合 RFC6838。
一些可能的媒体类型定义的示例
text/plain; charset=utf-8
application/json
application/vnd.github+json
application/vnd.github.v3+json
application/vnd.github.v3.raw+json
application/vnd.github.v3.text+json
application/vnd.github.v3.html+json
application/vnd.github.v3.full+json
application/vnd.github.v3.diff
application/vnd.github.v3.patch
HTTP 状态码
HTTP 状态码用于指示已执行操作的状态。可用的状态码由 RFC7231 定义,注册的状态码在 IANA 状态码注册表中列出。
规范
版本
OpenAPI 规范使用 语义版本 2.0.0 (semver) 进行版本控制,并遵循 semver 规范。
semver 的 major
.minor
部分(例如 3.0
)应指定 OAS 功能集。通常,.patch
版本解决的是本文档中的错误,而不是功能集。支持 OAS 3.0 的工具应与所有 OAS 3.0.* 版本兼容。工具不应考虑补丁版本,例如,在 3.0.0
和 3.0.1
之间不应进行区分。
OpenAPI 规范的每个新的次要版本应允许针对同一主要版本内的任何先前次要版本的规范有效的任何 OpenAPI 文档,通过更新到新的规范版本而具有等效的语义。此类更新必须仅要求将 openapi
属性更改为新的次要版本。
例如,一个有效的 OpenAPI 3.0.2 文档,在将其 openapi
属性更改为 3.1.0
后,应是一个有效的 OpenAPI 3.1.0 文档,在语义上与原始 OpenAPI 3.0.2 文档等效。必须编写 OpenAPI 规范的新次要版本,以确保这种形式的向后兼容性。
与 OAS 3.*.* 兼容的 OpenAPI 文档包含一个必需的 openapi
字段,该字段指定了它使用的 OAS 的语义版本。(OAS 2.0 文档包含一个名为 swagger
的顶级版本字段,其值为 "2.0"
。)
符合 OpenAPI 规范的 OpenAPI 文档本身是一个 JSON 对象,可以用 JSON 或 YAML 格式表示。
例如,如果字段具有数组值,则将使用 JSON 数组表示形式
{
"field": [ 1, 2, 3 ]
}
规范中的所有字段名称都区分大小写。这包括所有用作映射中的键的字段,除非明确指出键不区分大小写。
该模式公开两种类型的字段:固定字段(具有声明的名称)和模式字段(为字段名称声明正则表达式模式)。
模式字段必须在包含的对象中具有唯一的名称。
为了保持 YAML 和 JSON 格式之间的往返转换能力,建议使用 YAML 版本 1.2 以及一些其他约束
注意:虽然 API 可以通过 YAML 或 JSON 格式的 OpenAPI 文档定义,但 API 请求和响应主体以及其他内容不一定需要是 JSON 或 YAML。
文档结构
OpenAPI 文档可以由单个文档组成,也可以由用户自行决定分为多个连接的部分。在后一种情况下,必须在规范中使用 $ref
字段来引用这些部分,如下所示,来自 JSON 模式定义。
建议将根 OpenAPI 文档命名为:openapi.json
或 openapi.yaml
。
数据类型
OAS 中的原始数据类型基于 JSON 模式规范 Wright 草案 00 支持的类型。请注意,也支持 integer
作为类型,并定义为不带分数或指数部分的 JSON 数字。null
不支持作为类型(有关替代解决方案,请参见 nullable
)。使用 模式对象定义模型,该对象是 JSON 模式规范 Wright 草案 00 的扩展子集。
原始类型具有可选的修饰符属性:format
。OAS 使用几种已知格式来详细定义正在使用的数据类型。但是,为了支持文档需求,format
属性是一个开放的 string
值属性,可以具有任何值。即使本规范未定义,也可以使用诸如 "email"
、"uuid"
等格式。没有 format
属性的类型遵循 JSON 模式中的类型定义。不识别特定 format
的工具可能会默认回退到仅使用 type
,就像未指定 format
一样。
OAS 定义的格式是
类型 |
格式 |
注释 |
整数 |
int32 |
有符号 32 位 |
整数 |
int64 |
有符号 64 位(又名长整型) |
数字 |
浮点数 |
|
数字 |
双精度数 |
|
字符串 |
|
|
字符串 |
字节 |
base64 编码的字符 |
字符串 |
二进制 |
任意字节序列 |
布尔值 |
|
|
字符串 |
日期 |
按照 full-date 定义 - RFC3339 |
字符串 |
日期时间 |
按照 date-time 定义 - RFC3339 |
字符串 |
密码 |
给 UI 提供隐藏输入的提示。 |
富文本格式
在整个规范中,description
字段都注明支持 CommonMark markdown 格式。如果 OpenAPI 工具渲染富文本,则它必须至少支持 CommonMark 0.27 描述的 markdown 语法。工具可以选择忽略某些 CommonMark 功能以解决安全问题。
URL 中的相对引用
除非另有说明,否则所有作为 URL 的属性都可以是 RFC3986 定义的相对引用。相对引用使用 Server Object
中定义的 URL 作为基本 URI 来解析。
在 $ref
中使用的相对引用按照 JSON Reference 进行处理,使用当前文档的 URL 作为基本 URI。另请参阅 Reference Object。
模式
在以下描述中,如果一个字段没有明确地必需 (REQUIRED) 或者使用 MUST 或 SHALL 描述,则可以将其视为可选 (OPTIONAL)。
OpenAPI 对象
这是 OpenAPI 文档的根文档对象。
固定字段
字段名称 |
类型 |
描述 |
openapi |
字符串 |
必需 (REQUIRED)。此字符串必须是 OpenAPI 文档使用的 OpenAPI 规范版本的 语义版本号。 工具规范和客户端应使用 openapi 字段来解释 OpenAPI 文档。 这与 API 的 info.version 字符串无关。 |
info |
信息对象 |
必需 (REQUIRED)。提供有关 API 的元数据。 工具可以根据需要使用元数据。 |
servers |
[Server Object] |
服务器对象数组,提供到目标服务器的连接信息。如果未提供 servers 属性或为空数组,则默认值将是一个 Server Object,其 url 值为 / 。 |
paths |
路径对象 |
必需 (REQUIRED)。API 的可用路径和操作。 |
components |
组件对象 |
用于保存规范的各种模式的元素。 |
security |
[Security Requirement Object] |
声明可以在整个 API 中使用的安全机制。值列表包括可以使用的替代安全需求对象。只需要满足一个安全需求对象即可授权请求。单个操作可以覆盖此定义。要使安全成为可选的,可以在数组中包含一个空安全需求 ({} )。 |
tags |
[Tag Object] |
规范使用的带有附加元数据的标签列表。标签的顺序可以用于反映解析工具对它们的排序。并非 Operation Object 使用的所有标签都必须声明。未声明的标签可以随机组织或基于工具的逻辑组织。列表中的每个标签名称必须是唯一的。 |
externalDocs |
外部文档对象 |
其他外部文档。 |
此对象可以使用 Specification Extensions 进行扩展。
信息对象
该对象提供有关 API 的元数据。 如果需要,客户端可以使用元数据,并且可以在编辑或文档生成工具中方便地显示。
固定字段
字段名称 |
类型 |
描述 |
title |
字符串 |
必需 (REQUIRED)。API 的标题。 |
description |
字符串 |
API 的简短描述。 CommonMark 语法 可以用于富文本表示。 |
termsOfService |
字符串 |
API 服务条款的 URL。 必须是 URL 格式。 |
contact |
联系人对象 |
公开 API 的联系信息。 |
license |
许可证对象 |
公开 API 的许可证信息。 |
version |
字符串 |
必需 (REQUIRED)。OpenAPI 文档的版本(与 OpenAPI 规范版本或 API 实现版本不同)。 |
此对象可以使用 Specification Extensions 进行扩展。
Info 对象示例
{
"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": "[email protected]"
},
"license": {
"name": "Apache 2.0",
"url": "https://apache.ac.cn/licenses/LICENSE-2.0.html"
},
"version": "1.0.1"
}
title: Sample Pet Store App
description: This is a sample server for a pet store.
termsOfService: http://example.com/terms/
contact:
name: API Support
url: http://www.example.com/support
email: [email protected]
license:
name: Apache 2.0
url: https://apache.ac.cn/licenses/LICENSE-2.0.html
version: 1.0.1
公开 API 的联系信息。
固定字段
字段名称 |
类型 |
描述 |
name |
字符串 |
联系人/组织的标识名称。 |
url |
字符串 |
指向联系信息的 URL。 必须是 URL 格式。 |
email |
字符串 |
联系人/组织的电子邮件地址。 必须是电子邮件地址格式。 |
此对象可以使用 Specification Extensions 进行扩展。
{
"name": "API Support",
"url": "http://www.example.com/support",
"email": "[email protected]"
}
name: API Support
url: http://www.example.com/support
email: [email protected]
许可证对象
公开 API 的许可证信息。
固定字段
字段名称 |
类型 |
描述 |
name |
字符串 |
必需 (REQUIRED)。API 使用的许可证名称。 |
url |
字符串 |
API 使用的许可证的 URL。 必须是 URL 格式。 |
此对象可以使用 Specification Extensions 进行扩展。
License 对象示例
{
"name": "Apache 2.0",
"url": "https://apache.ac.cn/licenses/LICENSE-2.0.html"
}
name: Apache 2.0
url: https://apache.ac.cn/licenses/LICENSE-2.0.html
服务器对象
表示服务器的对象。
固定字段
字段名称 |
类型 |
描述 |
url |
字符串 |
必需 (REQUIRED)。目标主机的 URL。此 URL 支持服务器变量,并且可以是相对的,以指示主机位置相对于 OpenAPI 文档的服务位置。当在 { 括号} 中命名变量时,将进行变量替换。 |
description |
字符串 |
描述由 URL 指定的主机的可选字符串。 CommonMark 语法 可以用于富文本表示。 |
variables |
Map[string , Server Variable Object] |
变量名称及其值之间的映射。该值用于服务器 URL 模板中的替换。 |
此对象可以使用 Specification Extensions 进行扩展。
Server 对象示例
单个服务器可以描述为
{
"url": "https://development.gigantic-server.com/v1",
"description": "Development server"
}
url: https://development.gigantic-server.com/v1
description: Development server
以下显示了如何描述多个服务器,例如,在 OpenAPI 对象的 servers
中
{
"servers": [
{
"url": "https://development.gigantic-server.com/v1",
"description": "Development server"
},
{
"url": "https://staging.gigantic-server.com/v1",
"description": "Staging server"
},
{
"url": "https://api.gigantic-server.com/v1",
"description": "Production server"
}
]
}
servers:
- url: https://development.gigantic-server.com/v1
description: Development server
- url: https://staging.gigantic-server.com/v1
description: Staging server
- url: https://api.gigantic-server.com/v1
description: Production server
以下显示了如何将变量用于服务器配置
{
"servers": [
{
"url": "https://{username}.gigantic-server.com:{port}/{basePath}",
"description": "The production API server",
"variables": {
"username": {
"default": "demo",
"description": "this value is assigned by the service provider, in this example `gigantic-server.com`"
},
"port": {
"enum": [
"8443",
"443"
],
"default": "8443"
},
"basePath": {
"default": "v2"
}
}
}
]
}
servers:
- url: https://{username}.gigantic-server.com:{port}/{basePath}
description: The production API server
variables:
username:
# note! no enum here means it is an open value
default: demo
description: this value is assigned by the service provider, in this example `gigantic-server.com`
port:
enum:
- '8443'
- '443'
default: '8443'
basePath:
# open meaning there is the opportunity to use special base paths as assigned by the provider, default is `v2`
default: v2
服务器变量对象
表示服务器 URL 模板替换的服务器变量的对象。
固定字段
字段名称 |
类型 |
描述 |
enum |
[string ] |
如果替换选项来自有限的集合,则要使用的字符串值枚举。数组不应为空。 |
default |
字符串 |
必需 (REQUIRED)。用于替换的默认值,如果未提供替代值,则应发送该值。请注意,此行为与 Schema Object 处理默认值的方式不同,因为在这些情况下,参数值是可选的。如果定义了 enum ,则该值应存在于枚举的值中。 |
description |
字符串 |
服务器变量的可选描述。 CommonMark 语法 可以用于富文本表示。 |
此对象可以使用 Specification Extensions 进行扩展。
组件对象
为 OAS 的不同方面保存一组可重用的对象。除非明确引用组件对象外部的属性,否则组件对象中定义的所有对象都不会对 API 产生任何影响。
固定字段
此对象可以使用 Specification Extensions 进行扩展。
上面声明的所有固定字段都是对象,这些对象必须使用与正则表达式匹配的键:^[a-zA-Z0-9\.\-_]+$
。
字段名称示例
User
User_1
User_Name
user-name
my.org.User
Components 对象示例
"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
路径对象
保存到各个端点及其操作的相对路径。路径将附加到 Server Object
中的 URL,以构建完整的 URL。由于 ACL 约束,路径可能为空。
模式字段
字段模式 |
类型 |
描述 |
/{path} |
路径项对象 |
到单个端点的相对路径。字段名称必须以正斜杠 (/ ) 开头。路径会附加(无相对 URL 解析)到 Server Object 的 url 字段中扩展的 URL,以构建完整的 URL。允许使用 路径模板。在匹配 URL 时,具体的(非模板化)路径将优先于其模板化的对应项进行匹配。具有相同层次结构但模板名称不同的模板化路径不得存在,因为它们是相同的。如果匹配模棱两可,则由工具决定使用哪个。 |
此对象可以使用 Specification Extensions 进行扩展。
路径模板匹配
假设有以下路径,则如果使用具体的定义 /pets/mine
,它将首先匹配
/pets/{petId}
/pets/mine
以下路径被认为是相同的且无效
/pets/{petId}
/pets/{name}
以下情况可能导致歧义解析
/{entity}/me
/books/{id}
路径对象示例
{
"/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'
路径项对象
描述在单个路径上可用的操作。由于ACL约束,路径项可能为空。路径本身仍然会暴露给文档查看器,但他们不会知道哪些操作和参数可用。
固定字段
字段名称 |
类型 |
描述 |
$ref |
字符串 |
允许为此路径项进行外部定义。引用的结构必须是路径项对象的格式。如果路径项对象的字段同时出现在已定义的对象和引用的对象中,则行为是未定义的。 |
summary |
字符串 |
一个可选的字符串摘要,旨在应用于此路径中的所有操作。 |
description |
字符串 |
一个可选的字符串描述,旨在应用于此路径中的所有操作。可以使用CommonMark语法进行富文本表示。 |
get |
操作对象 |
此路径上 GET 操作的定义。 |
put |
操作对象 |
此路径上 PUT 操作的定义。 |
post |
操作对象 |
此路径上 POST 操作的定义。 |
delete |
操作对象 |
此路径上 DELETE 操作的定义。 |
options |
操作对象 |
此路径上 OPTIONS 操作的定义。 |
head |
操作对象 |
此路径上 HEAD 操作的定义。 |
patch |
操作对象 |
此路径上 PATCH 操作的定义。 |
trace |
操作对象 |
此路径上 TRACE 操作的定义。 |
servers |
[Server Object] |
用于服务此路径中所有操作的替代 server 数组。 |
parameters |
[参数对象 | 引用对象] |
适用于此路径下描述的所有操作的参数列表。这些参数可以在操作级别被覆盖,但不能在那里删除。该列表不得包含重复的参数。唯一参数由 名称和位置的组合定义。该列表可以使用引用对象链接到 OpenAPI 对象组件/参数中定义的参数。 |
此对象可以使用 Specification Extensions 进行扩展。
路径项对象示例
{
"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
操作对象
描述路径上的单个 API 操作。
固定字段
字段名称 |
类型 |
描述 |
tags |
[string ] |
用于 API 文档控制的标签列表。标签可用于按资源或任何其他限定符对操作进行逻辑分组。 |
summary |
字符串 |
对操作的功能进行简短的总结。 |
description |
字符串 |
对操作行为的详细解释。可以使用CommonMark 语法进行富文本表示。 |
externalDocs |
外部文档对象 |
此操作的其他外部文档。 |
operationId |
字符串 |
用于标识操作的唯一字符串。id 在 API 中描述的所有操作中必须是唯一的。 operationId 值区分大小写。工具和库可以使用 operationId 来唯一标识操作,因此,建议遵循常见的编程命名约定。 |
parameters |
[参数对象 | 引用对象] |
适用于此操作的参数列表。如果参数已在路径项中定义,则新定义将覆盖它,但永远无法删除它。该列表不得包含重复的参数。唯一参数由 名称和位置的组合定义。该列表可以使用引用对象链接到 OpenAPI 对象组件/参数中定义的参数。 |
requestBody |
请求体对象 | 引用对象 |
适用于此操作的请求体。只有在 HTTP 1.1 规范RFC7231明确定义了请求体的语义的 HTTP 方法中才支持 requestBody 。在 HTTP 规范模糊的其他情况下,requestBody 应被使用者忽略。 |
responses |
响应对象 |
必需。执行此操作后返回的可能响应列表。 |
callbacks |
Map[string , Callback Object | Reference Object] |
与父操作相关的可能的带外回调映射。键是回调对象的唯一标识符。映射中的每个值都是一个回调对象,描述了 API 提供者可能发起的请求以及预期的响应。 |
deprecated |
布尔值 |
声明此操作已弃用。使用者应避免使用已声明的操作。默认值为 false 。 |
security |
[Security Requirement Object] |
声明可以为此操作使用哪些安全机制。该值列表包括可使用的替代安全需求对象。只需满足一个安全需求对象即可授权请求。要使安全成为可选的,可以在数组中包含一个空的安全需求({} )。此定义会覆盖任何声明的顶级security 。要删除顶级安全声明,可以使用空数组。 |
servers |
[Server Object] |
用于服务此操作的替代 server 数组。如果在路径项对象或根级别指定了替代 server 对象,它将被此值覆盖。 |
此对象可以使用 Specification Extensions 进行扩展。
操作对象示例
{
"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
外部文档对象
允许引用外部资源以获取扩展文档。
固定字段
字段名称 |
类型 |
描述 |
description |
字符串 |
目标文档的简短描述。可以使用CommonMark 语法进行富文本表示。 |
url |
字符串 |
必需。目标文档的 URL。值必须是 URL 格式。 |
此对象可以使用 Specification Extensions 进行扩展。
外部文档对象示例
{
"description": "Find more info here",
"url": "https://example.com"
}
description: Find more info here
url: https://example.com
参数对象
描述单个操作参数。
唯一参数由名称和位置的组合定义。
参数位置
in
字段指定了四个可能的参数位置
- path - 与路径模板一起使用,其中参数值实际上是操作 URL 的一部分。这不包括 API 的主机或基本路径。例如,在
/items/{itemId}
中,路径参数为 itemId
。
- query - 附加到 URL 的参数。例如,在
/items?id=###
中,查询参数为 id
。
- header - 作为请求的一部分的自定义标头。请注意,RFC7230指出标头名称不区分大小写。
- cookie - 用于将特定的 cookie 值传递给 API。
固定字段
字段名称 |
类型 |
描述 |
name |
字符串 |
必需。参数的名称。参数名称区分大小写。- 如果
in 是 "path" ,则 name 字段必须与路径字段中路径对象内出现的模板表达式相对应。有关详细信息,请参阅路径模板。 - 如果
in 是 "header" 且 name 字段是 "Accept" 、"Content-Type" 或 "Authorization" ,则应忽略参数定义。 - 对于所有其他情况,
name 对应于in 属性使用的参数名称。
|
in |
字符串 |
必需。参数的位置。可能的值为 "query" 、"header" 、"path" 或 "cookie" 。 |
description |
字符串 |
参数的简短描述。其中可以包含使用示例。可以使用CommonMark 语法进行富文本表示。 |
required |
布尔值 |
确定此参数是否是强制性的。如果参数位置是 "path" ,则此属性是必需的,并且其值必须是 true 。否则,可以包含该属性,其默认值为 false 。 |
deprecated |
布尔值 |
指定参数已弃用,应逐步淘汰。默认值为 false 。 |
allowEmptyValue |
布尔值 |
设置传递空值参数的能力。这仅对 query 参数有效,并允许发送空值的参数。默认值为 false 。如果使用了style ,并且行为是 n/a (无法序列化),则应忽略 allowEmptyValue 的值。不建议使用此属性,因为它很可能会在以后的版本中删除。 |
参数序列化的规则通过两种方式之一指定。对于更简单的场景,schema
和 style
可以描述参数的结构和语法。
字段名称 |
类型 |
描述 |
style |
字符串 |
描述如何根据参数值的类型对参数值进行序列化。默认值(基于 in 的值):对于 query - form ;对于 path - simple ;对于 header - simple ;对于 cookie - form 。 |
explode |
布尔值 |
当此值为 true 时,类型为 array 或 object 的参数值会为数组的每个值或映射的键值对生成单独的参数。对于其他类型的参数,此属性不起作用。当style 为 form 时,默认值为 true 。对于所有其他样式,默认值为 false 。 |
allowReserved |
布尔值 |
确定参数值是否应该允许保留字符,如RFC3986 :/?#[]@!$&'()*+,;= 中定义的那样,无需进行百分比编码即可包含。此属性仅适用于 in 值为 query 的参数。默认值为 false 。 |
schema |
模式对象 | 引用对象 |
定义参数所使用类型的模式。 |
示例 |
任意 |
参数的潜在值示例。如果存在,示例应该与指定的模式和编码属性匹配。example 字段与 examples 字段互斥。此外,如果引用包含示例的 schema ,则 example 值应该覆盖模式提供的示例。要表示不能自然地以 JSON 或 YAML 表示的媒体类型的示例,字符串值可以包含必要时进行转义的示例。 |
示例集 |
Map[ string , 示例对象 | 引用对象] |
参数的潜在值示例集。每个示例都应该包含一个与参数编码中指定的正确格式的值。examples 字段与 example 字段互斥。此外,如果引用包含示例的 schema ,则 examples 值应该覆盖模式提供的示例。 |
对于更复杂的情况,content
属性可以定义参数的媒体类型和模式。一个参数必须包含 schema
属性或 content
属性,但不能同时包含两者。当 example
或 examples
与 schema
对象一起提供时,示例必须遵循参数的规定的序列化策略。
字段名称 |
类型 |
描述 |
内容 |
Map[string , 媒体类型对象] |
一个包含参数表示形式的映射。键是媒体类型,值描述它。映射必须只包含一个条目。 |
样式值
为了支持序列化简单参数的常见方法,定义了一组 style
值。
样式 |
类型 |
位置 |
注释 |
matrix |
primitive 、array 、object |
path |
由 RFC6570 定义的路径样式参数 |
label |
primitive 、array 、object |
path |
由 RFC6570 定义的标签样式参数 |
form |
primitive 、array 、object |
query 、cookie |
由 RFC6570 定义的表单样式参数。此选项将 collectionFormat 替换为 OpenAPI 2.0 中的 csv (当 explode 为 false 时)或 multi (当 explode 为 true 时)值。 |
simple |
array |
path 、header |
由 RFC6570 定义的简单样式参数。此选项将 collectionFormat 替换为 OpenAPI 2.0 中的 csv 值。 |
spaceDelimited |
array |
query |
空格分隔的数组值。此选项将 collectionFormat 替换为 OpenAPI 2.0 中的 ssv 值。 |
pipeDelimited |
array |
query |
管道符分隔的数组值。此选项将 collectionFormat 替换为 OpenAPI 2.0 中的 pipes 值。 |
deepObject |
object |
query |
提供一种使用表单参数呈现嵌套对象的简单方法。 |
样式示例
假设一个名为 color
的参数具有以下值之一
string -> "blue"
array -> ["blue","black","brown"]
object -> { "R": 100, "G": 200, "B": 150 }
下表显示了每个值的渲染差异示例。
样式 |
explode |
空 |
字符串 |
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 |
此对象可以使用 Specification Extensions 进行扩展。
参数对象示例
一个包含 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": "username",
"in": "path",
"description": "username to fetch",
"required": true,
"schema": {
"type": "string"
}
}
name: username
in: path
description: username to fetch
required: true
schema:
type: string
一个可选的字符串值查询参数,允许通过重复查询参数来允许多个值
{
"name": "id",
"in": "query",
"description": "ID of the object to fetch",
"required": false,
"schema": {
"type": "array",
"items": {
"type": "string"
}
},
"style": "form",
"explode": true
}
name: id
in: query
description: ID of the object to fetch
required: false
schema:
type: array
items:
type: string
style: form
explode: true
一个自由形式的查询参数,允许特定类型的未定义参数
{
"in": "query",
"name": "freeForm",
"schema": {
"type": "object",
"additionalProperties": {
"type": "integer"
},
},
"style": "form"
}
in: query
name: freeForm
schema:
type: object
additionalProperties:
type: integer
style: form
一个使用 content
定义序列化的复杂参数
{
"in": "query",
"name": "coordinates",
"content": {
"application/json": {
"schema": {
"type": "object",
"required": [
"lat",
"long"
],
"properties": {
"lat": {
"type": "number"
},
"long": {
"type": "number"
}
}
}
}
}
}
in: query
name: coordinates
content:
application/json:
schema:
type: object
required:
- lat
- long
properties:
lat:
type: number
long:
type: number
请求体对象
描述单个请求体。
固定字段
字段名称 |
类型 |
描述 |
描述 |
字符串 |
请求体的简要描述。这可能包含使用示例。 CommonMark 语法 可用于富文本表示。 |
内容 |
Map[string , 媒体类型对象] |
必需。请求体的内容。键是媒体类型或 媒体类型范围,值描述它。对于匹配多个键的请求,仅适用最具体的键。例如,text/plain 覆盖 text/* |
必需 |
布尔值 |
确定请求体是否在请求中是必需的。默认为 false 。 |
此对象可以使用 Specification Extensions 进行扩展。
请求体示例
一个具有引用的模型定义的请求体。
{
"description": "user to add to the system",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/User"
},
"examples": {
"user" : {
"summary": "User Example",
"externalValue": "http://foo.bar/examples/user-example.json"
}
}
},
"application/xml": {
"schema": {
"$ref": "#/components/schemas/User"
},
"examples": {
"user" : {
"summary": "User example in XML",
"externalValue": "http://foo.bar/examples/user-example.xml"
}
}
},
"text/plain": {
"examples": {
"user" : {
"summary": "User example in Plain text",
"externalValue": "http://foo.bar/examples/user-example.txt"
}
}
},
"*/*": {
"examples": {
"user" : {
"summary": "User example in other format",
"externalValue": "http://foo.bar/examples/user-example.whatever"
}
}
}
}
}
description: user to add to the system
content:
'application/json':
schema:
$ref: '#/components/schemas/User'
examples:
user:
summary: User Example
externalValue: 'http://foo.bar/examples/user-example.json'
'application/xml':
schema:
$ref: '#/components/schemas/User'
examples:
user:
summary: User Example in XML
externalValue: 'http://foo.bar/examples/user-example.xml'
'text/plain':
examples:
user:
summary: User example in text plain format
externalValue: 'http://foo.bar/examples/user-example.txt'
'*/*':
examples:
user:
summary: User example in other format
externalValue: 'http://foo.bar/examples/user-example.whatever'
一个字符串值数组的请求体参数
{
"description": "user to add to the system",
"content": {
"text/plain": {
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
description: user to add to the system
required: true
content:
text/plain:
schema:
type: array
items:
type: string
每个媒体类型对象都为其键标识的媒体类型提供模式和示例。
固定字段
字段名称 |
类型 |
描述 |
模式 |
模式对象 | 引用对象 |
定义请求、响应或参数内容的模式。 |
示例 |
任意 |
媒体类型的示例。示例对象应该具有媒体类型指定的正确格式。example 字段与 examples 字段互斥。此外,如果引用包含示例的 schema ,则 example 值应该覆盖模式提供的示例。 |
示例集 |
Map[ string , 示例对象 | 引用对象] |
媒体类型的示例集。每个示例对象都应该与媒体类型和指定的模式(如果存在)匹配。examples 字段与 example 字段互斥。此外,如果引用包含示例的 schema ,则 examples 值应该覆盖模式提供的示例。 |
编码 |
Map[string , 编码对象] |
属性名称与其编码信息之间的映射。键(即属性名称)必须在模式中作为属性存在。当媒体类型为 multipart 或 application/x-www-form-urlencoded 时,编码对象应仅适用于 requestBody 对象。 |
此对象可以使用 Specification Extensions 进行扩展。
{
"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"
文件上传的注意事项
与 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
这些示例适用于文件上传的输入有效负载或响应有效负载。
在 POST
操作中提交文件的 requestBody
可能如下例所示
requestBody:
content:
application/octet-stream:
schema:
# a binary file of any type
type: string
format: binary
此外,可以指定特定的媒体类型
# 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
要上传多个文件,必须使用 multipart
媒体类型
requestBody:
content:
multipart/form-data:
schema:
properties:
# The property name 'file' will be used for all files.
file:
type: array
items:
type: string
format: binary
要使用 RFC1866 通过表单 URL 编码提交内容,可以使用以下定义
requestBody:
content:
application/x-www-form-urlencoded:
schema:
type: object
properties:
id:
type: string
format: uuid
address:
# complex types are stringified to support RFC 1866
type: object
properties: {}
在此示例中,当传递给服务器时,requestBody
中的内容必须按照 RFC1866 进行字符串化。此外,address
字段复杂对象将被字符串化。
当在 application/x-www-form-urlencoded
内容类型中传递复杂对象时,此类属性的默认序列化策略在 编码对象
的 style
属性中描述为 form
。
multipart
内容的特殊注意事项
在将请求体传输到操作时,通常使用 multipart/form-data
作为 Content-Type
。与 2.0 相比,当使用 multipart
内容时,需要使用 schema
来定义操作的输入参数。这支持复杂的结构,以及支持上传多个文件的机制。
当传入 multipart
类型时,可以使用边界来分隔正在传输的内容的各个部分 — 因此,为 multipart
定义了以下默认的 Content-Type
- 如果属性是基本类型或基本值的数组,则默认的 Content-Type 为
text/plain
- 如果属性是复杂类型或复杂值的数组,则默认的 Content-Type 为
application/json
- 如果属性是
type: string
,且 format: binary
或 format: base64
(也称为文件对象),则默认的 Content-Type 为 application/octet-stream
示例
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
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'
引入了 encoding
属性,使您可以控制 multipart
请求体的各个部分的序列化。此属性仅适用于 multipart
和 application/x-www-form-urlencoded
请求体。
编码对象
应用于单个模式属性的单个编码定义。
固定字段
字段名称 |
类型 |
描述 |
contentType |
字符串 |
用于编码特定属性的 Content-Type。默认值取决于属性类型:对于 format 为 binary 的 string ,为 application/octet-stream ;对于其他基本类型,为 text/plain ;对于 object ,为 application/json ;对于 array ,默认值根据内部类型定义。该值可以是特定的媒体类型(例如 application/json )、通配符媒体类型(例如 image/* )或逗号分隔的两种类型列表。 |
标头 |
Map[string , Header Object | Reference Object] |
允许将其他信息作为标头提供的映射,例如 Content-Disposition 。Content-Type 是单独描述的,在此部分应忽略。如果请求体媒体类型不是 multipart ,则应忽略此属性。 |
样式 |
字符串 |
描述如何根据其类型序列化特定的属性值。有关 style 属性的详细信息,请参阅 参数对象。该行为遵循与 query 参数相同的值,包括默认值。如果请求体媒体类型不是 application/x-www-form-urlencoded ,则应忽略此属性。 |
explode |
布尔值 |
当此值为 true 时,类型为 array 或 object 的属性值会为数组的每个值或映射的键值对生成单独的参数。对于其他类型的属性,此属性不起作用。当 style 为 form 时,默认值为 true 。对于所有其他样式,默认值为 false 。如果请求体媒体类型不是 application/x-www-form-urlencoded ,则应忽略此属性。 |
允许保留 |
布尔值 |
确定参数值是否应该允许保留字符,如 RFC3986 :/?#[]@!$&'()*+,;= 中定义的那样,可以在不进行百分比编码的情况下包含。默认值为 false 。如果请求体媒体类型不是 application/x-www-form-urlencoded ,则应忽略此属性。 |
此对象可以使用 Specification Extensions 进行扩展。
编码对象示例
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
响应对象
操作的预期响应的容器。容器将 HTTP 响应代码映射到预期响应。
文档不一定需要涵盖所有可能的 HTTP 响应代码,因为它们可能是事先未知的。但是,文档应该涵盖成功的操作响应和任何已知的错误。
default
可用作规范中未单独涵盖的所有 HTTP 代码的默认响应对象。
Responses 对象
必须包含至少一个响应代码,并且它应该是成功操作调用的响应。
固定字段
模式字段
此对象可以使用 Specification Extensions 进行扩展。
Responses 对象示例
成功操作的 200 响应以及其他操作的默认响应(暗示错误)
{
"200": {
"description": "a pet to be returned",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Pet"
}
}
}
},
"default": {
"description": "Unexpected error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorModel"
}
}
}
}
}
'200':
description: a pet to be returned
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
default:
description: Unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorModel'
响应对象
描述来自 API 操作的单个响应,包括设计时,到基于响应的操作的静态 links
。
固定字段
此对象可以使用 Specification Extensions 进行扩展。
Response 对象示例
复杂类型数组的响应
{
"description": "A complex object array response",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/VeryComplexType"
}
}
}
}
}
description: A complex object array response
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/VeryComplexType'
带有字符串类型的响应
{
"description": "A simple string response",
"content": {
"text/plain": {
"schema": {
"type": "string"
}
}
}
}
description: A simple string response
content:
text/plain:
schema:
type: string
带有标头的纯文本响应
{
"description": "A simple string response",
"content": {
"text/plain": {
"schema": {
"type": "string",
"example": "whoa!"
}
}
},
"headers": {
"X-Rate-Limit-Limit": {
"description": "The number of allowed requests in the current period",
"schema": {
"type": "integer"
}
},
"X-Rate-Limit-Remaining": {
"description": "The number of remaining requests in the current period",
"schema": {
"type": "integer"
}
},
"X-Rate-Limit-Reset": {
"description": "The number of seconds left in the current period",
"schema": {
"type": "integer"
}
}
}
}
description: A simple string response
content:
text/plain:
schema:
type: string
example: 'whoa!'
headers:
X-Rate-Limit-Limit:
description: The number of allowed requests in the current period
schema:
type: integer
X-Rate-Limit-Remaining:
description: The number of remaining requests in the current period
schema:
type: integer
X-Rate-Limit-Reset:
description: The number of seconds left in the current period
schema:
type: integer
没有返回值的响应
{
"description": "object created"
}
description: object created
回调对象
与父操作相关的可能的带外回调的映射。映射中的每个值都是一个 路径项对象,它描述了 API 提供程序可能启动的一组请求以及预期的响应。用于标识路径项对象的键值是一个表达式,在运行时评估,该表达式标识用于回调操作的 URL。
模式字段
字段模式 |
类型 |
描述 |
{expression} |
路径项对象 |
用于定义回调请求和预期响应的路径项对象。有一个 完整的示例 可用。 |
此对象可以使用 Specification Extensions 进行扩展。
键表达式
标识 路径项对象 的键是一个 运行时表达式,可以在运行时 HTTP 请求/响应的上下文中对其进行评估,以标识用于回调请求的 URL。一个简单的例子可能是 $request.body#/url
。但是,使用 运行时表达式 可以访问完整的 HTTP 消息。这包括访问 JSON 指针 RFC6901 可以引用的正文的任何部分。
例如,给定以下 HTTP 请求
POST /subscribe/myevent?queryUrl=http://clientdomain.com/stillrunning HTTP/1.1
Host: example.org
Content-Type: application/json
Content-Length: 187
{
"failedUrl" : "http://clientdomain.com/failed",
"successUrls" : [
"http://clientdomain.com/fast",
"http://clientdomain.com/medium",
"http://clientdomain.com/slow"
]
}
201 Created
Location: http://example.org/subscription/1
以下示例显示了如何评估各种表达式,假设回调操作具有名为 eventType
的路径参数和名为 queryUrl
的查询参数。
Callback 对象示例
以下示例使用用户提供的 queryUrl
查询字符串参数来定义回调 URL。这是一个如何使用回调对象来描述与订阅操作一起使用的 WebHook 回调的示例,以启用注册 WebHook。
myCallback:
'{$request.query.queryUrl}':
post:
requestBody:
description: Callback payload
content:
'application/json':
schema:
$ref: '#/components/schemas/SomePayload'
responses:
'200':
description: callback successfully processed
以下示例显示了一个回调,其中服务器是硬编码的,但查询字符串参数是从请求正文中的 id
和 email
属性填充的。
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
示例对象
固定字段
字段名称 |
类型 |
描述 |
summary |
字符串 |
示例的简短描述。 |
description |
字符串 |
示例的详细描述。可以使用 CommonMark 语法 进行富文本表示。 |
value |
任意 |
嵌入的文字示例。 value 字段和 externalValue 字段是互斥的。要表示无法在 JSON 或 YAML 中自然表示的媒体类型的示例,请使用字符串值来包含示例,并在必要时进行转义。 |
externalValue |
字符串 |
指向文字示例的 URL。 这提供了引用不易包含在 JSON 或 YAML 文档中的示例的功能。value 字段和 externalValue 字段是互斥的。 |
此对象可以使用 Specification Extensions 进行扩展。
在所有情况下,示例值都应与关联值的类型架构兼容。 工具实现可以选择自动验证兼容性,如果示例值不兼容,则拒绝它。
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'
在参数中
parameters:
- name: 'zipCode'
in: 'query'
schema:
type: 'string'
format: 'zip-code'
examples:
zip-example:
$ref: '#/components/examples/zip-example'
在响应中
responses:
'200':
description: your car appointment has been booked
content:
application/json:
schema:
$ref: '#/components/schemas/SuccessResponse'
examples:
confirmation-success:
$ref: '#/components/examples/confirmation-success'
链接对象
Link 对象
表示响应的可能设计时链接。链接的存在并不保证调用者能够成功调用它,而是提供了响应与其他操作之间的已知关系和遍历机制。
与动态链接(即在响应有效负载中提供的链接)不同,OAS 链接机制不需要运行时响应中的链接信息。
对于计算链接并提供执行链接的指令,使用 运行时表达式 来访问操作中的值,并在调用链接的操作时将它们用作参数。
固定字段
字段名称 |
类型 |
描述 |
operationRef |
字符串 |
对 OAS 操作的相对或绝对 URI 引用。此字段与 operationId 字段互斥,并且必须指向 操作对象。相对 operationRef 值可用于在 OpenAPI 定义中查找现有 操作对象。 |
operationId |
字符串 |
使用唯一 operationId 定义的现有、可解析的 OAS 操作的名称。 此字段与 operationRef 字段互斥。 |
parameters |
Map[string , Any | {expression}] |
一个映射,表示传递给使用 operationId 指定或通过 operationRef 标识的操作的参数。键是要使用的参数名称,而值可以是常量或要评估并传递给链接操作的表达式。可以使用 参数位置 [{in}.]{name} 限定参数名称,以用于在不同位置使用相同参数名称的操作(例如 path.id)。 |
requestBody |
Any | {expression} |
一个文字值或 {expression},在调用目标操作时用作请求正文。 |
description |
字符串 |
链接的描述。可以使用 CommonMark 语法 进行富文本表示。 |
server |
服务器对象 |
目标操作要使用的服务器对象。 |
此对象可以使用 Specification Extensions 进行扩展。
必须使用 operationRef
或 operationId
来标识链接的操作。 如果使用 operationId
,则它必须是唯一的,并在 OAS 文档的范围内解析。由于存在名称冲突的可能性,对于具有外部引用的规范,首选使用 operationRef
语法。
示例
从请求操作计算链接,其中 $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
当运行时表达式未能求值时,不会将任何参数值传递给目标操作。
响应正文中的值可用于驱动链接的操作。
links:
address:
operationId: getUserAddressByUUID
parameters:
# get the `uuid` field from the `uuid` field in the response body
userUuid: $response.body#/uuid
客户端自行决定跟踪所有链接。仅通过存在关系并不能保证权限或能够成功调用该链接。
OperationRef 示例
由于可能无法引用 operationId
(operationId
是 操作对象 中的可选字段),因此也可以通过相对 operationRef
进行引用
links:
UserRepositories:
# returns array of '#/components/schemas/repository'
operationRef: '#/paths/~12.0~1repositories~1{username}/get'
parameters:
username: $response.body#/username
或绝对 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
请注意,在使用 operationRef
时,使用 JSON 引用时,转义斜杠是必要的。
运行时表达式
运行时表达式允许基于实际 API 调用中仅在 HTTP 消息中可用的信息定义值。 链接对象 和 回调对象 使用此机制。
运行时表达式由以下 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
在这里,json-pointer
取自 RFC 6901,char
取自 RFC 7159,token
取自 RFC 7230。
name
标识符区分大小写,而 token
则不区分。
下表提供了运行时表达式的示例以及它们在值中的用法示例
示例
源位置 |
示例表达式 |
备注 |
HTTP 方法 |
$method |
$method 的允许值将是 HTTP 操作的值。 |
请求的媒体类型 |
$request.header.accept |
|
请求参数 |
$request.path.id |
请求参数必须在父操作的 parameters 部分声明,否则无法进行评估。这包括请求头。 |
请求体属性 |
$request.body#/user/uuid |
在接受有效负载的操作中,可以引用 requestBody 的部分或整个主体。 |
请求 URL |
$url |
|
响应值 |
$response.body#/status |
在返回有效负载的操作中,可以引用响应体的部分或整个主体。 |
响应头 |
$response.header.Server |
仅提供单个头部值 |
运行时表达式保留引用值的类型。可以通过用 {}
花括号包围表达式将其嵌入到字符串值中。
Header 对象遵循 Parameter 对象 的结构,但有以下更改
name
必须不指定,它在相应的 headers
映射中给出。
in
必须不指定,它隐式地在 header
中。
- 所有受位置影响的特征必须适用于
header
的位置(例如,style
)。
一个简单的 integer
类型头部
{
"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
标签对象
向 Operation 对象 使用的单个标签添加元数据。对于 Operation 对象实例中定义的每个标签,不强制必须有一个标签对象。
固定字段
字段名称 |
类型 |
描述 |
name |
字符串 |
必需。标签的名称。 |
description |
字符串 |
标签的简短描述。 CommonMark 语法 可以用于富文本表示。 |
externalDocs |
外部文档对象 |
此标签的额外外部文档。 |
此对象可以使用 Specification Extensions 进行扩展。
标签对象示例
{
"name": "pet",
"description": "Pets operations"
}
name: pet
description: Pets operations
引用对象
一个简单的对象,允许引用规范中的其他组件,包括内部和外部。
Reference 对象由 JSON Reference 定义,并遵循相同的结构、行为和规则。
对于此规范,引用解析按照 JSON Reference 规范定义的方式完成,而不是按照 JSON Schema 规范。
固定字段
字段名称 |
类型 |
描述 |
$ref |
字符串 |
必需。引用字符串。 |
此对象不能使用其他属性进行扩展,任何添加的属性都将被忽略。
Reference 对象示例
{
"$ref": "#/components/schemas/Pet"
}
$ref: '#/components/schemas/Pet'
相对 Schema 文档示例
{
"$ref": "Pet.json"
}
$ref: Pet.yaml
带有嵌入 Schema 的相对文档示例
{
"$ref": "definitions.json#/Pet"
}
$ref: definitions.yaml#/Pet
模式对象
Schema 对象允许定义输入和输出数据类型。这些类型可以是对象,也可以是基本类型和数组。此对象是 JSON Schema Specification Wright Draft 00 的扩展子集。
有关属性的更多信息,请参阅 JSON Schema Core 和 JSON Schema Validation。除非另有说明,否则属性定义遵循 JSON Schema。
属性
以下属性直接取自 JSON Schema 定义,并遵循相同的规范
- title
- multipleOf
- maximum
- exclusiveMaximum
- minimum
- exclusiveMinimum
- maxLength
- minLength
- pattern(此字符串应该是一个有效的正则表达式,根据 Ecma-262 Edition 5.1 正则表达式 方言)
- maxItems
- minItems
- uniqueItems
- maxProperties
- minProperties
- required
- enum
以下属性取自 JSON Schema 定义,但其定义已调整为 OpenAPI 规范。
- type - 值必须是字符串。不支持通过数组使用多种类型。
- allOf - 内联或引用的 schema 必须是 Schema 对象,而不是标准的 JSON Schema。
- oneOf - 内联或引用的 schema 必须是 Schema 对象,而不是标准的 JSON Schema。
- anyOf - 内联或引用的 schema 必须是 Schema 对象,而不是标准的 JSON Schema。
- not - 内联或引用的 schema 必须是 Schema 对象,而不是标准的 JSON Schema。
- items - 值必须是对象而不是数组。内联或引用的 schema 必须是 Schema 对象,而不是标准的 JSON Schema。如果
type
是 array
,则必须存在 items
。
- properties - 属性定义必须是 Schema 对象,而不是标准的 JSON Schema(内联或引用)。
- additionalProperties - 值可以是布尔值或对象。内联或引用的 schema 必须是 Schema 对象,而不是标准的 JSON Schema。与 JSON Schema 一致,
additionalProperties
默认为 true
。
- description - CommonMark 语法 可以用于富文本表示。
- format - 有关更多详细信息,请参阅 数据类型格式。在依赖 JSON Schema 定义的格式的同时,OAS 提供了一些额外的预定义格式。
- default - 默认值表示如果未提供值,则输入的消费者将假定为 schema 的值。与 JSON Schema 不同,该值必须符合在同一级别定义的 Schema 对象的已定义类型。例如,如果
type
是 string
,则 default
可以是 "foo"
,但不能是 1
。
或者,在可以使用 Schema 对象时,可以使用 Reference 对象 代替。这允许引用定义而不是内联定义它们。
此处未提及的 JSON Schema 规范定义的其他属性严格不支持。
除了 JSON Schema 子集字段之外,以下字段可以用于进一步的 schema 文档
固定字段
字段名称 |
类型 |
描述 |
nullable |
布尔值 |
如果 type 在同一 Schema 对象中显式定义,则 true 值会将 "null" 添加到 type 关键字允许的类型中。其他 Schema 对象约束保留其定义的行为,因此可能会禁止使用 null 作为值。 false 值将使指定的或默认的 type 保持不变。默认值为 false 。 |
discriminator |
鉴别器对象 |
添加对多态性的支持。鉴别器是用于区分可能满足有效负载描述的其他 schema 的对象名称。有关更多详细信息,请参阅 组合和继承。 |
readOnly |
布尔值 |
仅与 Schema 的 "properties" 定义相关。将属性声明为“只读”。这意味着它可能作为响应的一部分发送,但不应作为请求的一部分发送。如果该属性标记为 readOnly 为 true 并且在 required 列表中,则 required 仅在响应时生效。属性不能同时标记为 readOnly 和 writeOnly 为 true 。默认值为 false 。 |
writeOnly |
布尔值 |
仅与 Schema 的 "properties" 定义相关。将属性声明为“只写”。因此,它可能作为请求的一部分发送,但不应作为响应的一部分发送。如果该属性标记为 writeOnly 为 true 并且在 required 列表中,则 required 仅在请求时生效。属性不能同时标记为 readOnly 和 writeOnly 为 true 。默认值为 false 。 |
xml |
XML 对象 |
这仅可在属性 schema 上使用。它对根 schema 没有影响。添加额外元数据来描述此属性的 XML 表示形式。 |
externalDocs |
外部文档对象 |
此 schema 的额外外部文档。 |
example |
任意 |
一个自由格式的属性,用于包含此 schema 的实例示例。为了表示不能自然地用 JSON 或 YAML 表示的示例,可以使用字符串值来包含带有必要转义的示例。 |
deprecated |
布尔值 |
指定 schema 已弃用,应停止使用。默认值为 false 。 |
此对象可以使用 Specification Extensions 进行扩展。
组合和继承(多态性)
OpenAPI 规范允许使用 JSON Schema 的 allOf
属性组合和扩展模型定义,从而有效地提供模型组合。allOf
接受一个对象定义数组,这些定义独立验证,但共同构成一个对象。
虽然组合提供了模型的可扩展性,但它并不意味着模型之间存在层次结构。为了支持多态性,OpenAPI 规范添加了 discriminator
字段。使用时,discriminator
将成为属性的名称,该属性决定哪个 schema 定义验证模型的结构。因此,discriminator
字段必须是必需字段。定义继承实例的鉴别器值有两种方法。
- 使用 schema 名称。
- 通过使用新值覆盖属性来覆盖 schema 名称。如果存在新值,则此值优先于 schema 名称。因此,没有给定 id 的内联 schema 定义不能用于多态性。
XML 建模
当将 JSON 定义转换为 XML 时,xml 属性允许额外的定义。XML 对象包含有关可用选项的更多信息。
Schema 对象示例
基本类型示例
{
"type": "string",
"format": "email"
}
type: string
format: email
简单模型
{
"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/字典属性的模型
对于简单的字符串到字符串的映射
{
"type": "object",
"additionalProperties": {
"type": "string"
}
}
type: object
additionalProperties:
type: string
对于字符串到模型的映射
{
"type": "object",
"additionalProperties": {
"$ref": "#/components/schemas/ComplexModel"
}
}
type: object
additionalProperties:
$ref: '#/components/schemas/ComplexModel'
带有示例的模型
{
"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
带有组合的模型
{
"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
支持多态性的模型
{
"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
鉴别器对象
当请求体或响应有效负载可能是多个不同 schema 中的一个时,可以使用 discriminator
对象来帮助序列化、反序列化和验证。鉴别器是 schema 中的特定对象,用于根据与其关联的值向规范的使用者告知替代 schema。
使用鉴别器时,内联 schema 将不被考虑。
固定字段
字段名称 |
类型 |
描述 |
propertyName |
字符串 |
必需。有效负载中将保存鉴别器值的属性的名称。 |
mapping |
Map[string , string ] |
一个对象,用于保存有效负载值与 schema 名称或引用之间的映射。 |
仅当使用复合关键字 oneOf
、anyOf
、allOf
时,鉴别器对象才是合法的。
在 OAS 3.0 中,可以将响应有效负载描述为任何多个类型中的一个
MyResponseType:
oneOf:
- $ref: '#/components/schemas/Cat'
- $ref: '#/components/schemas/Dog'
- $ref: '#/components/schemas/Lizard'
这意味着通过验证,有效负载必须完全匹配由 Cat
、Dog
或 Lizard
描述的 schema 中的一个。在这种情况下,鉴别器可以充当“提示”,以快捷验证和选择匹配的 schema,这可能是一项代价高昂的操作,具体取决于 schema 的复杂性。然后,我们可以准确地描述哪个字段告诉我们使用哪个 schema
MyResponseType:
oneOf:
- $ref: '#/components/schemas/Cat'
- $ref: '#/components/schemas/Dog'
- $ref: '#/components/schemas/Lizard'
discriminator:
propertyName: petType
现在的期望是,响应有效负载中必须存在名为 petType
的属性,并且该值将对应于 OAS 文档中定义的 schema 的名称。因此,响应有效负载
{
"id": 12345,
"petType": "Cat"
}
将表明 Cat
schema 应与此有效负载结合使用。
在鉴别器字段的值与 schema 名称不匹配或无法进行隐式映射的情况下,可以使用可选的 mapping
定义
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'
这里,dog
的鉴别器值将映射到模式 #/components/schemas/Dog
,而不是默认(隐式)值 Dog
。如果鉴别器值与隐式或显式映射不匹配,则无法确定模式,并且验证应该失败。映射键必须是字符串值,但工具可能会将响应值转换为字符串以进行比较。
当与 anyOf
构造结合使用时,鉴别器的使用可以避免当多个模式可能满足单个有效负载时的歧义。
在 oneOf
和 anyOf
用例中,所有可能的模式都必须显式列出。为了避免冗余,鉴别器可以添加到父模式定义中,并且 allOf
构造中组成父模式的所有模式可以用作替代模式。
例如
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
像这样的有效负载
{
"petType": "Cat",
"name": "misty"
}
将指示使用 Cat
模式。同样,这个模式
{
"petType": "dog",
"bark": "soft"
}
将由于 mappings
元素中的定义而映射到 Dog
。
XML 对象
一个元数据对象,允许更精细的 XML 模型定义。
当使用数组时,XML 元素名称不会被推断(对于单数/复数形式),并且应该使用 name
属性来添加该信息。有关预期行为,请参见示例。
固定字段
字段名称 |
类型 |
描述 |
name |
字符串 |
替换用于描述的模式属性的元素/属性的名称。在 items 中定义时,它会影响列表中各个 XML 元素的名称。当与 type 为 array (在 items 之外)一起定义时,它将影响包装元素,并且仅当 wrapped 为 true 时才生效。如果 wrapped 为 false ,则将被忽略。 |
namespace |
字符串 |
命名空间定义的 URI。值必须是绝对 URI 的形式。 |
prefix |
字符串 |
用于 name 的前缀。 |
attribute |
布尔值 |
声明属性定义转换为属性而不是元素。默认值为 false 。 |
wrapped |
布尔值 |
仅可用于数组定义。表示数组是包装的(例如,<books><book/><book/></books> )还是未包装的(<book/><book/> )。默认值为 false 。定义仅在与 type 为 array (在 items 之外)一起定义时才生效。 |
此对象可以使用 Specification Extensions 进行扩展。
XML 对象示例
XML 对象定义的示例包含在 模式对象 的属性定义中,并附带其 XML 表示形式的示例。
无 XML 元素
基本字符串属性
{
"animals": {
"type": "string"
}
}
animals:
type: string
<animals>...</animals>
基本字符串数组属性(wrapped
默认值为 false
)
{
"animals": {
"type": "array",
"items": {
"type": "string"
}
}
}
animals:
type: array
items:
type: string
<animals>...</animals>
<animals>...</animals>
<animals>...</animals>
XML 名称替换
{
"animals": {
"type": "string",
"xml": {
"name": "animal"
}
}
}
animals:
type: string
xml:
name: animal
<animal>...</animal>
XML 属性、前缀和命名空间
在此示例中,显示了一个完整的模型定义。
{
"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 数组
更改元素名称
{
"animals": {
"type": "array",
"items": {
"type": "string",
"xml": {
"name": "animal"
}
}
}
}
animals:
type: array
items:
type: string
xml:
name: animal
<animal>value</animal>
<animal>value</animal>
外部 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>
即使数组是包装的,如果没有显式定义名称,则内部和外部都将使用相同的名称
{
"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>
要克服以上示例中的命名问题,可以使用以下定义
{
"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>
影响内部和外部名称
{
"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>
如果我们更改外部元素但不更改内部元素
{
"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>
安全方案对象
定义可由操作使用的安全方案。支持的方案包括 HTTP 身份验证、API 密钥(作为标头、cookie 参数或查询参数),RFC6749 中定义的 OAuth2 的常见流程(隐式、密码、客户端凭据和授权代码)以及 OpenID Connect Discovery。
固定字段
字段名称 |
类型 |
适用范围 |
描述 |
type |
字符串 |
任意 |
必需。安全方案的类型。有效值为 "apiKey" 、"http" 、"oauth2" 、"openIdConnect" 。 |
description |
字符串 |
任意 |
安全方案的简短描述。 CommonMark 语法 可以用于富文本表示。 |
name |
字符串 |
apiKey |
必需。要使用的标头、查询或 cookie 参数的名称。 |
in |
字符串 |
apiKey |
必需。API 密钥的位置。有效值为 "query" 、"header" 或 "cookie" 。 |
scheme |
字符串 |
http |
必需。RFC7235 中定义的 Authorization 标头 中要使用的 HTTP Authorization 方案的名称。所使用的值应该在 IANA 身份验证方案注册表 中注册。 |
bearerFormat |
字符串 |
http ("bearer" ) |
提示客户端识别 bearer 令牌格式的方式。Bearer 令牌通常由授权服务器生成,因此此信息主要用于文档目的。 |
flows |
OAuth 流对象 |
oauth2 |
必需。包含支持的流类型配置信息的对象。 |
openIdConnectUrl |
字符串 |
openIdConnect |
必需。用于发现 OAuth2 配置值的 OpenId Connect URL。这必须是 URL 的形式。 |
此对象可以使用 Specification Extensions 进行扩展。
安全方案对象示例
基本身份验证示例
{
"type": "http",
"scheme": "basic"
}
type: http
scheme: basic
API 密钥示例
{
"type": "apiKey",
"name": "api_key",
"in": "header"
}
type: apiKey
name: api_key
in: header
JWT Bearer 示例
{
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT",
}
type: http
scheme: bearer
bearerFormat: JWT
隐式 OAuth2 示例
{
"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
OAuth 流对象
允许配置支持的 OAuth 流程。
固定字段
字段名称 |
类型 |
描述 |
implicit |
OAuth 流对象 |
OAuth 隐式流程的配置 |
password |
OAuth 流对象 |
OAuth 资源所有者密码流程的配置 |
clientCredentials |
OAuth 流对象 |
OAuth 客户端凭据流程的配置。在 OpenAPI 2.0 中以前称为 application 。 |
authorizationCode |
OAuth 流对象 |
OAuth 授权代码流程的配置。在 OpenAPI 2.0 中以前称为 accessCode 。 |
此对象可以使用 Specification Extensions 进行扩展。
OAuth 流对象
支持的 OAuth 流程的配置详细信息
固定字段
字段名称 |
类型 |
适用范围 |
描述 |
authorizationUrl |
字符串 |
oauth2 ("implicit" , "authorizationCode" ) |
必需。用于此流程的授权 URL。这必须是 URL 的形式。 |
tokenUrl |
字符串 |
oauth2 ("password" , "clientCredentials" , "authorizationCode" ) |
必需。用于此流程的令牌 URL。这必须是 URL 的形式。 |
refreshUrl |
字符串 |
oauth2 |
用于获取刷新令牌的 URL。这必须是 URL 的形式。 |
scopes |
Map[string , string ] |
oauth2 |
必需。OAuth2 安全方案的可用范围。范围名称与其简短描述之间的映射。该映射可能为空。 |
此对象可以使用 Specification Extensions 进行扩展。
OAuth 流程对象示例
{
"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
安全需求对象
列出执行此操作所需的安全方案。用于每个属性的名称必须与 组件对象 下的 安全方案 中声明的安全方案相对应。
包含多个方案的安全需求对象要求必须满足所有方案才能授权请求。这支持需要多个查询参数或 HTTP 标头来传递安全信息的场景。
当在 OpenAPI 对象 或 操作对象 上定义安全需求对象列表时,只需满足列表中其中一个安全需求对象即可授权请求。
模式字段
字段模式 |
类型 |
描述 |
{name} |
[string ] |
每个名称必须与在 组件对象 下的 安全方案 中声明的安全方案相对应。如果安全方案的类型为 "oauth2" 或 "openIdConnect" ,则该值是执行所需的范围名称列表,并且如果授权不需要指定的范围,则该列表可以为空。对于其他安全方案类型,数组必须为空。 |
安全需求对象示例
非 OAuth2 安全需求
{
"api_key": []
}
api_key: []
OAuth2 安全需求
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
petstore_auth:
- write:pets
- read:pets
可选 OAuth2 安全性
在 OpenAPI 对象 或 操作对象 中定义的可选 OAuth2 安全性
{
"security": [
{},
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
}
security:
- {}
- petstore_auth:
- write:pets
- read:pets
规范扩展
尽管 OpenAPI 规范试图适应大多数用例,但可以在某些点添加额外的数据以扩展规范。
扩展属性实现为始终以 "x-"
为前缀的模式化字段。
字段模式 |
类型 |
描述 |
^x- |
任意 |
允许扩展 OpenAPI 模式。字段名称必须以 x- 开头,例如 x-internal-id 。值可以是 null 、基本类型、数组或对象。可以具有任何有效的 JSON 格式值。 |
扩展可能受也可能不受可用工具的支持,但也可以扩展这些工具以添加请求的支持(如果工具是内部的或开源的)。
安全过滤
OpenAPI 规范中的某些对象可能会被声明为空,或者被完全删除,即使它们本质上是 API 文档的核心。
这样做的原因是允许对文档进行额外的访问控制层。虽然不属于规范本身,但某些库可能会选择根据某种形式的身份验证/授权来允许访问文档的某些部分。
两个例子如下
- 路径对象 可以为空。这可能违反直觉,但这可能会告诉查看者他们到了正确的位置,但无法访问任何文档。他们仍然可以访问 信息对象,其中可能包含有关身份验证的更多信息。
- 路径项对象 可以为空。在这种情况下,查看者将知道该路径存在,但无法看到其任何操作或参数。这与从 路径对象 中隐藏路径本身不同,因为用户将知道其存在。这允许文档提供者精细地控制查看者可以看到的内容。
附录 A:修订历史
版本 |
日期 |
注释 |
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 |
将 Swagger 2.0 捐赠给 OpenAPI 倡议 |
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 规范的首次发布 |