OpenAPI规范3.1.0

OpenAPI规范

版本 3.1.0

介绍

OpenAPI规范(OAS)为HTTP API定义了一个与语言无关的标准接口,使得人和计算机都可以在不使用源代码、文档或监听网络通信的情况下,具备发现和理解服务的能力。正确定义后,使用者可以使用最少的实现逻辑来理解远程服务并与之交互。

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

目录

术语定义

OpenAPI文件

一种自包含或复合资源,用于定义或描述API或API元素。OpenAPI文档必须至少包含一个paths 字段,一个components字段或一个webhooks字段。OpenAPI文档使用并符合OpenAPI规范。

Path模板

Path模板是指使用大括号({})包围的模板表达式,用来在URL路径中标记一个可以被path参数替换的部分。

路径中每个模板表达式必须对应于一个path参数, 这些path参数包含在每个Path 元素或其Operations中。例外的是,如果路径项为空(例如由于ACL约束),则不需要匹配的路径参数。

这些path参数的值不得包含RFC3986描述的任何未转义的“通用语法”字符:正斜杠(/),问号(?)或哈希(#)。

媒体类型

媒体类型定义分布在多种资源中。媒体类型定义应该符合 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 Status Code Registry中列出。

规范

版本

OpenAPI规范的版本使用major.minor.patch的格式。版本字符串中major.minor部分(例如3.1)应该规定OAS功能集。*.patch*用于修订文档出现的错误或提供说明,而不应用于增加功能集。支持OAS 3.1的工具应该与所有的OAS 3.1.*版本兼容。工具不应该考虑补丁版本,例如对工具来说3.1.03.1.1版本没有任何区别。

偶尔,在minor版本中可以不向后兼容,这种情况通常认为相对于收益而言,影响较小。

与OAS 3.*.*兼容的OpenAPI文档包含一个必填 openapi字段,用于指定其使用的OAS版本。

格式

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

例如,如果字段是数组类型,则将使用JSON数组表示:

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

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

该模式公开两种类型的字段:固定字段(字段名为明确的名称)和模式字段(字段名为正则表达式)。

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

为了能在YAML和JSON格式之间转换,建议使用YAML 1.2版,并且需要满足以下约束:

注意: 尽管API可以由OpenAPI文档以YAML或JSON格式定义,但API请求和响应以及其他内容可以是任意格式。

文档结构

OpenAPI文档可以是单个文档,也可以由作者自行决定分成多个相互联系的文档。在后一种情况, 需要在Reference ObjectsSchema Object中使用 $ref关键字。

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

数据类型

OAS中的数据类型基于 JSON Schema Specification Draft 2020-12支持的类型。请注意, integer类型是不带分数或指数部分的JSON数字。使用Schema Object定义模型,该对象是JSON Schema Specification Draft 2020-12的超集。

根据JSON Schema Validation vocabulary的定义,数据类型可以具有可选的修饰符属性:format。OAS为原始数据类型定义了额外的格式,以提供更加详细信息。

OAS定义的格式为:

typeformatComments
integerint32signed 32 bits
integerint64signed 64 bits (a.k.a long)
numberfloat
numberdouble
stringpasswordA hint to UIs to obscure input.

富文本格式

在整个规范 description字段中都支持CommonMark markdown格式。OpenAPI工具呈现富文本的地方必须至少支持CommonMark 0.27描述的markdown语法。为了安全目的,工具可以选择忽略一些CommonMark特性。

URIs中的相对引用

除非另有说明,否则所有URI属性都是RFC3986定义的相对引用。

相对引用(包括Reference Objects, PathItem Object $ref 字段, Link Object operationRef 字段和 Example Object externalValue字段),根据RFC3986的基本URI进行解析。

如果URI包含片段标识符,则应按照所引用文档的片段解析机制来解析该片段。如果引用文档的表示形式是JSON或YAML,则片段标识符应按照 RFC6901解释为JSON指针。

正如JSON Schema Specification Draft 2020-12描述的那样,Schema Objects中的相对引用,包括任何作为$id出现的值,使用距离最近的父级 $id作为基本URI。如果没有父模式包含$id,则必须根据RFC3986确定基本的URI。

URLs中的相对引用

除非另有说明,否则所有作为URL的属性都可以是RFC3986定义的相对引用。
除非另有说明,否则相对引用将使用Server Object的定义为基本URL的进行解析。注意这些本身可能是相对于参考文件而言的。

模式

在以下描述中,如果未明确要求字段或未使用MUST或SHALL描述字段,则可以将其视为可选字段。

OpenAPI对象

这是OpenAPI document的根对象。

固定字段
Field NameType描述
openapistring必填。该字符串必须是OpenAPI文档使用的OpenAPI规范的版本号。工具应使用openapi字段来解释OpenAPI文档。这不是相关的info.version 字符串。
infoInfo Object必填。提供API有关的元数据。工具可以根据需要使用元数据。
jsonSchemaDialectstringOAS文档中包含Schema Objects$schema键值的默认值。这必须采用URI的形式。
servers[Server Object]服务器对象的数组,它们提供到目标服务器的连接信息。如果servers属性没有指定,或是空数组,默认值将是url/的一个Server Object
pathsPaths ObjectAPI的可用路径和操作。
webhooksMap[string, Path Item Object | Reference Object] ]输入webhook,可以作为API的一部分接收数据,并且可以由API使用者选择实现。与callbacks特性密切相关,本节描述了不是通过API调用(例如,带外注册)发起的请求。标识Webhook的每个键值是唯一字符串,而(可选引用)路径项对象描述了可能由API提供程序发起的请求以及预期的响应。有一个例子(…/examples/v3.1/webhook-example.yaml)。
componentsComponents Object用于保存文档的各种模式的元素。
security[Security Requirement Object]声明可以在API中使用哪些安全机制。有一系列可以供选择的安全机制对象,认证请求仅需满足一个安全需求对象。独立操作可以覆盖此定义。为了使安全性成为可选选项,数组可以包含一个空的安全性要求({})。
tags[Tag Object]文档使用的带有附加元数据的标签的列表。标签的顺序可以被解析工具用来反映它们的顺序。并非必须声明操作对象使用的所有标签。未声明的标签可以是随机组织的,也可以根据工具的逻辑来组织。列表中的每个标签名称必须唯一。
externalDocsExternal Documentation Object其他外部文档。

这个对象可以依据Specification Extensions来扩展。

Info Object

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

固定字段
Field NameTypeDescription
titlestring必填。API的标题。
summarystringAPI的简短摘要。
descriptionstringAPI的说明。 CommonMark syntax语法可以用于富文本表示。
termsOfServicestringAPI服务条款的URL地址。必须是URL的形式。
contactContact Object公开API的联系信息。
licenseLicense Object公开的API的许可证信息。
versionstring必填。OpenAPI文档的版本(与OpenAPI Specification version或API实现版本不同)。

这个对象可以依据Specification Extensions来扩展。

Info Object 例子
{
  "title": "Sample Pet Store App",
  "summary": "A pet store manager.",
  "description": "This is a sample server for a pet store.",
  "termsOfService": "https://example.com/terms/",
  "contact": {
    "name": "API Support",
    "url": "https://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
summary: A pet store manager.
description: This is a sample server for a pet store.
termsOfService: https://example.com/terms/
contact:
  name: API Support
  url: https://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 Object

公开的API的联系信息。

固定字段
Field NameTypeDescription
namestring联系人/组织的标识名称。
urlstring指向联系信息的URL。必须是URL的形式。
emailstring联系人/组织的电子邮件地址。必须使用电子邮件地址的形式。

这个对象可以依据Specification Extensions来扩展。

Contact Object 例子
{
  "name": "API Support",
  "url": "https://www.example.com/support",
  "email": "support@example.com"
}
name: API Support
url: https://www.example.com/support
email: support@example.com
License Object

公开API的许可信息。

固定字段
Field NameTypeDescription
namestring必填。用于API的许可证名称。
identifierstringAPI的SPDX许可表达式。identifier字段与url字段互斥。
urlstring用于API许可证的URL。必须是URL形式。url 字段与identifier字段互斥。

这个对象可以依据Specification Extensions来扩展。

License Object 例子
{
  "name": "Apache 2.0",
  "identifier": "Apache-2.0"
}
name: Apache 2.0
identifier: Apache-2.0
Server Object

代表服务器的对象。

固定字段
Field NameTypeDescription
urlstring必填。目标主机的URL。该URL支持服务器变量,并且可以是相对的,以标识主机位置相对于服务OpenAPI文档的位置。由{}包围的变量名,将被替换为合适的值。
descriptionstring可选字符串,描述URL指定的主机。可以使用支持CommonMark syntax语法的富文本表示。
variablesMap[string, Server Variable Object]由变量名和值组成的map。用于替换服务器URL模板中的变量。

这个对象可以依据Specification Extensions来扩展。

Server Object 例子

单个服务器将描述为:

{
  "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
Server Variable Object

该对象描述了用于替换URL模板的服务器变量。

固定字段
Field NameTypeDescription
enum[string]在选项是有限集合时,使用的字符串枚举。数组一定不能为空。
defaultstring必填。当未指定具体值时,使用的默认值。请注意,这里处理默认值的方式有别于Schema Object’s,原因在于Schema Object’s是可选的。如果定义了enum,该值必须是[enum]中的值。
descriptionstring可选的服务器变量描述信息。 可以使用支持CommonMark syntax语法的富文本表示。

这个对象可以依据Specification Extensions来扩展。

Components Object

包含一组可重用的对象,可以在OAS的其他地方使用,可以将其理解是一个字典。除非其他对象显式引用,否则在components中定义的对象不会影响API。

固定字段
Field NameTypeDescription
schemasMap[string, Schema Object]保存可重用Schema Objects的对象。
responsesMap[string, Response Object | Reference Object]保存可重用 Response Objects的对象。
parametersMap[string, Parameter Object | Reference Object]保存可重用Parameter Objects的对象。
examplesMap[string, Example Object | Reference Object]保存可重用Example Objects的对象。
requestBodiesMap[string, Request Body Object | Reference Object]保存可重用[Request Body Objects]的对象.
headersMap[string, Header Object | Reference Object]保存可重用Header Objects的对象。
securitySchemesMap[string, Security Scheme Object | Reference Object]保存可重用的Security Scheme Objects对象.
linksMap[string, Link Object | Reference Object]有可重用Link Objects的对象。
callbacksMap[string, Callback Object | Reference Object]保存可重用 Callback Objects的对象。
pathItemsMap[string, Path Item Object | Reference Object]保存可重用Path Item Object的对象。

这个对象可以依据Specification Extensions来扩展。

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

字段名举例:

User
User_1
User_Name
user-name
my.org.User
Components Object 例子
"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": "https://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: https://example.org/api/oauth/dialog
          scopes:
            write:pets: modify pets in your account
            read:pets: read your pets
Paths Object

定义各个端点及其操作的相对路径,该path会追加到来自Server Object的URL上,以构建完整的URL。由于Access Control List (ACL) constraints的限制,路径可能为空。

模式匹配字段
Field PatternTypeDescription
/{path}Path Item Object到单个端点的相对路径,必须以(/)开头,允许使用Path templating。该路径被追加到Server Object中的 url字段,以构建完整的URL。当匹配URL时,具体的路径(非模板)将优先于模板路径被匹配。应该避免定义多个具有相同路径层级但是路径参数名不同的路径,因为它们是等价的。当匹配出现歧义时,则由工具决定使用哪个匹配。

这个对象可以依据Specification Extensions来扩展。

Path 模板匹配

假设配置如下,则具体的路径/pets/mine将被首先匹配。

  /pets/{petId}
  /pets/mine

以下路径被视为相同且无效:

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

下面的配置可能得到模棱两可的解析:

  /{entity}/me
  /books/{id}
Paths Object 例子
{
  "/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'
Path Item Object

描述单个路径上可用的操作。由于ACL constraints约束,路径项可能为空。该路径本身仍显示在文档查看器中,但是他们将不知道哪些操作和参数可用。

固定字段
Field NameTypeDescription
$refstring允许引用此路径项的定义。被引用的结构必须采用Path Item Object的形式。万一“路径项对象”字段同时出现在定义的对象和引用的对象中,则该行为是未定义的。请参阅解析Relative References的规则。
summarystring可选的字符串摘要,试图应用于此路径上的所有操作。
descriptionstring可选的字符串描述,试图应用于此路径上的所有操作。可以使用支持CommonMark syntax语法的富文本表示。
getOperation Object在此路径上的GET操作的定义。
putOperation Object在此路径上的PUT操作的定义。
postOperation Object在此路径上的POST操作的定义。
deleteOperation Object在此路径上的DELETE操作的定义。
optionsOperation Object在此路径上的OPTIONS操作的定义。
headOperation Object在此路径上的HEAD操作的定义。
patchOperation Object在此路径上的PATCH操作的定义。
traceOperation Object在此路径上的TRACE操作的定义。
servers[Server Object]服务于该路径上所有操作的可选的server数组。
parameters[Parameter Object | Reference Object]适用于此路径下描述的所有操作的参数列表。这些参数可以在操作级别覆盖,但不能删除。该列表不得包含重复的参数。不重复的参数名由namelocation组合而成。该列表可以使用Reference Object链接到[OpenAPI Object’s components/parameters]中定义的参数。

这个对象可以依据Specification Extensions来扩展。

Path Item Object 例子
{
  "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
Operation Object

描述路径上单个API操作。

固定字段
Field NameTypeDescription
tags[string]用于API文档控制的标签列表。标签可用于按资源或任何其他限定符对操作进行逻辑分组。
summarystring该操作的简短摘要。
descriptionstring操作行为的详细说明。可以使用支持CommonMark syntax语法的富文本表示。
externalDocsExternal Documentation Object有关此操作的其他外部文档。
operationIdstring用于标识操作的唯一字符串。该ID在API中描述的所有操作中必须唯一,并且区分大小写。工具和库可以使用该值唯一地标识一个操作,因此建议遵循通用的编程命名约定。
parameters[Parameter Object | Reference Object]适用于此操作的参数列表。如果在Path Item中已经定义了参数,则新定义将覆盖它,但永远不能删除它。该列表不得包含重复的参数。唯一参数由namelocation的组合而成。该列表可以使用Reference Object链接到[OpenAPI Object’s components/parameters]中定义的参数。
requestBodyRequest Body Object | Reference Object适用于此操作的请求正文。requestBody完全支持HTTP 1.1 规范RFC7231中定义HTTP方法的语义。在其他HTTP规范含糊不清的情况下(例如GET, HEADDELETE),requestBody允许、但没有明确定义的语义,不过应尽可能避免这种情况。
responsesResponses Object执行此操作返回的所有可能响应的列表。
callbacksMap[string, Callback Object | Reference Object]父操作有关的可能的带外回调的map。键值是回调对象的唯一标识符。map中的每个值都是一个Callback Object ,该对象描述了可能由API提供程序发起的请求以及预期的响应。
deprecatedboolean声明不推荐使用此操作。使用者应避免使用已声明的操作。默认值为false。
security[Security Requirement Object]声明可以用于此操作的安全机制。这是一个包含可选的安全性要求对象的列表。授权请求只需要满足一个安全性要求对象。为了使安全性成为可选选项, 列表中可以包含一个空的安全性要求({})。此定义将覆盖所有声明的top-level security。要删除top-level安全声明,可以使用一个空列表。
servers[Server Object]服务此操作的server可选列表。如果在“路径项对象”或“根”级别指定了server的替代对象,则它将被该值覆盖。

这个对象可以依据Specification Extensions来扩展。

Operation Object 例子
{
  "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:
       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
External Documentation Object

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

固定字段
Field NameTypeDescription
descriptionstring目标文档的描述信息。可以使用支持CommonMark syntax语法的富文本表示。
urlstring必填。 指向目标文档的URL,必须采用URL形式。

这个对象可以依据Specification Extensions来扩展。

External Documentation Object 例子
{
  "description": "Find more info here",
  "url": "https://example.com"
}
description: Find more info here
url: https://example.com
Parameter Object

描述单个操作的参数。

参数名唯一,由namelocation的组合而成。

参数位置

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

  • path - 与Path Templating一起使用, 其中参数值实际上是操作URL的一部分。这不包括API的主机或基本路径。例如,在/items/{itemId}中, path参数是itemId
  • query - 附加到URL的参数。例如,在/items?id=###中, 查询参数是id
  • header - 自定义头,应作为请求的一部分。请注意, RFC7230声明的头名称不区分大小写。
  • cookie - 用于给API传递特定的cookie值。
固定字段
Field NameTypeDescription
namestring必填。参数的名称,区分大小写.
  • 如果 in"path", name字段必须对应于Paths Objectpath字段的模板表达式。有关更多信息,请参见Path Templating
  • 如果 in"header"中并且name字段是"Accept""Content-Type""Authorization",参数定义应该被忽略。
  • 对于所有其他情况, name对应于 in属性使用的参数名称。
instring必填。参数位置,取值范围:"query""header""path""cookie"
descriptionstring参数的简要描述。这里可能包含使用示例。可以使用支持CommonMark syntax语法的富文本表示。
requiredboolean确定此参数是否是必需的,如果parameter location"path",则此属性为必需,其值必须为true。其他情况,此属性有可能是false,默认值为false
deprecatedboolean指定不推荐使用该参数,应将尽量不使用该参数。默认值为false
allowEmptyValueboolean是否允许空值。这仅对query参数有效,表示是否允许发送带有空值的参数。默认值为false。如果使用style,并且行为是n/a(无法序列化),该值将被忽略。建议不要使用此属性,因为在以后的版本中可能会删除它。

以两种方式之一指定参数序列化的规则。

对于简单的场景, schemastyle能描述参数的结构和语法。

Field NameTypeDescription
stylestring描述如何根据参数值的类型来序列化参数值。默认值(基于in的值):对于query - form; 对于path - simple; 对于header - simple;对于cookie - form
explodeboolean如果为true,则arrayobject类型的参数值数组或map中的每个子项都生成单独的参数。对于其他类型的参数,此属性无效。当 styleform时,默认值是true。对于所有其他样式,默认值为false
allowReservedboolean确定参数值是否应该允许包含RFC3986 定义的保留字符,即 包含不进行百分比编码的😕?#[]@!$&’()*+,;=。此属性仅适用于参数queryin值。默认值为false`。
schemaSchema Object定义用于参数类型的模式。
exampleAny参数可能值的示例。该示例应该匹配指定的模式和编码属性(如果存在)。example字段与examples字段互斥。此外,如果引用schema包含示例,则example值将覆盖schema提供的示例。为了表示媒体类型(无法自然描述的JSON或YAML格式)的示例,必要时可以包含转义后的字符串。
examplesMap[ string, Example Object | Reference Object]参数可能值的示例。每个示例都应包含一个正确格式的值,该格式在参数的编码中指定。examples字段与example字段互斥。此外,如果引用schema包含示例的,则examples值将覆盖schema提供的示例。

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

Field NameTypeDescription
contentMap[string, Media Type Object]包含参数表示形式的map。map的每个条目都一个媒体类型,至少包含一个条目。
值的样式

In order to support common ways of serializing simple parameters, a set of style values are defined.
为了支持序列化简单参数的通用方法,定义了一组style的值。

styletypeinComments
matrixprimitive, array, objectpathRFC6570 定义的Path-style样式参数
labelprimitive, array, objectpathRFC6570定义的标签样式参数
formprimitive, array, objectquery, cookieRFC6570定义的表单样式参数。此选项代替OpenAPI 2.0中 collectionFormatcsv (当 explodefalse) 或 multi (当 explodetrue)值。
simplearraypath, headerRFC6570定义的简单样式参数。 此选项代替OpenAPI 2.0中 collectionFormatcsv值。
spaceDelimitedarray, objectquery空格分隔的数组或对象值。此选项代替OpenAPI 2.0中collectionFormat,等同于ssv
pipeDelimitedarray, objectquery管道分隔的数组或对象值。此选项代替OpenAPI 2.0中collectionFormat,等同于pipes
deepObjectobjectquery提供使用表单参数呈现嵌套对象的简单方法。
样式举例

假设参数名叫color,取值是在如下的列表中选取一个:

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

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

styleexplodeemptystringarrayobject
matrixfalse;color;color=blue;color=blue,black,brown;color=R,100,G,200,B,150
matrixtrue;color;color=blue;color=blue;color=black;color=brown;R=100;G=200;B=150
labelfalse..blue.blue.black.brown.R.100.G.200.B.150
labeltrue..blue.blue.black.brown.R=100.G=200.B=150
formfalsecolor=color=bluecolor=blue,black,browncolor=R,100,G,200,B,150
formtruecolor=color=bluecolor=blue&color=black&color=brownR=100&G=200&B=150
simplefalsen/ablueblue,black,brownR,100,G,200,B,150
simpletruen/ablueblue,black,brownR=100,G=200,B=150
spaceDelimitedfalsen/an/ablue%20black%20brownR%20100%20G%20200%20B%20150
pipeDelimitedfalsen/an/ablue|black|brownR|100|G|200|B|150
deepObjecttruen/an/an/acolor[R]=100&color[G]=200&color[B]=150

这个对象可以依据Specification Extensions来扩展。

Parameter Object 示例

具有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
Request Body Object

描述单个请求正文。

固定字段
Field NameTypeDescription
descriptionstring请求正文的简短描述。这里可以使用示例。可以使用支持CommonMark syntax语法的富文本表示。
contentMap[string, Media Type Object]必填。 请求正文的内容。使用媒体类型或 media type range的map结构。对于匹配多个键值的请求,仅有最具体的键值生效。例如text/plain 将覆盖text/*
requiredboolean请求中是否需要正文。默认为false

这个对象可以依据Specification Extensions来扩展。

Request Body 例子

带有参考模型地定义的请求正文。

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

字符数组类型的正文参数:

{
  "description": "user to add to the system",
  "required": true,
  "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
Media Type Object

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

固定字段
Field NameTypeDescription
schemaSchema Object定义请求、响应或参数内容的模式。
exampleAny此外,如果引用一个包含示例的schema, example值将 覆盖 schema提供的示例。媒体类型的示例。示例对象应该采用媒体类型指定的正确格式。example字段与examples字段互斥。此外,如果引用schema包含示例的,则该example值将覆盖该模式提供的示例。
examplesMap[ string, Example Object | Reference Object]媒体类型的示例。每个示例对象都应该匹配媒体类型和指定的模式(如果存在)。examples字段与example字段互斥。此外,如果引用schema包含示例的,则该example值将覆盖该模式提供的示例。
encodingMap[string, Encoding Object]属性名称和其编码信息之间的map。作为属性名称的键值,必须作为属性存在于模式中。当媒体类型是 multipartapplication/x-www-form-urlencoded时,编码对象仅适用于requestBody对象。

这个对象可以依据Specification Extensions来扩展。

Media Type 例子
{
  "application/json": {
    "schema": {
         "$ref": "#/components/schemas/Pet"
    },
    "examples": {
      "cat" : {
        "summary": "An example of a cat",
        "value": 
          {
            "name": "Fluffy",
            "petType": "Cat",
            "color": "White",
            "gender": "male",
            "breed": "Persian"
          }
      },
      "dog": {
        "summary": "An example of a dog with a cat's name",
        "value" :  { 
          "name": "Puma",
          "petType": "Dog",
          "color": "Black",
          "gender": "Female",
          "breed": "Mixed"
        },
      "frog": {
          "$ref": "#/components/examples/frog-example"
        }
      }
    }
  }
}
application/json: 
  schema:
    $ref: "#/components/schemas/Pet"
  examples:
    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输入/输出内容的语义,和任何其他模式类型相同。

与3.0规范相反,format关键字对模式的内容编码没有影响。JSON模式提供了一个contentEncoding关键字,可用于为模式指定Content-EncodingcontentEncoding关键字支持RFC4648中定义的所有编码,包括“BASE64”和“base64url”,以及来自RFC2045的"quoted-printable"。由contentEncoding关键字指定的编码独立于,在请求或响应的报文头,或多个正文元数据中的Content-Type指定的编码。当两者都存在时,首先使用contentEncoding指定的编码,然后使用Content-Type指定的编码。

JSON Schema也提供了一个contentMediaType关键字。然而,通过媒体类型的键值或Encoding ObjectcontentType字段,已经指定了媒体类型,则contentMediaType关键字应该被忽略。

示例:

以二进制(字节流)传输的内容可​​以省略schema

# a PNG image as a binary file:
content:
    image/png: {}
# an arbitrary binary file:
content:
    application/octet-stream: {}

以base64编码传输的二进制内容:

content:
    image/png:
        schema:
            type: string
            contentMediaType: image/png
            contentEncoding: base64

注意,Content-Type保留了image/png,描述了有效载荷的语义。JSON模式typecontentEncoding字段说明了有效负载是作为文本传输的。JSON模式contentMediaType在技​​术上是多余的,但是可以由可能不了解OpenAPI上下文的JSON模式工具使用。

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: {}

另外,可能指定特定的媒体类型:

# multiple, specific media types may be specified:
requestBody:
  content:
    # a binary file of type png or jpeg
    image/jpeg: {}
    image/png: {}

要上传多个文件,必须使用multipart媒体类型:

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

参见下面multipart/form-data部分,items的空模式表示application/octet-stream的媒体类型。

支持x-www-form-urlencoded请求正文

通过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内容类型中传递复杂对象时,属性的默认序列化策略,在作为formEncoding Objectstyle属性中描述。

multipart内容的特殊注意事项

当传输请求正文操作时,使用 multipart/form-data作为 Content-Type是很常见的。与2.0相比,当使用multipart 内容时,为操作定义输入参数不可缺少schema字段。这支持复杂的结构以及支持多个文件上传的机制。

multipart/form-data请求正文中,每个模式属性或模式属性数组的每个元素,都是有效负载的一部分内容,这些内容都带有RFC7578定义内部报头。 multipart/form-data请求正文每个属性的序列化策略,在与之相关的 Encoding Object中指定。

传入multipart类型时,可以使用边界来分隔要传输的内容的各个部分。因此,为multipart定义了以下Content-Type的默认值:

  • 如果属性是原始值或原始值数组,则默认的Content-Type为 text/plain
  • 如果属性是复杂的或复杂值的数组,则默认的Content-Type为 application/json
  • 如果属性是带有 contentEncodingtype: string,则默认的Content-Type为 application/octet-stream

根据JSON Schema规范,如果contentMediaType不带contentEncoding,则将其视为contentEncoding: identity(如果存在)。尽管对于将文本文档嵌入text/html到JSON字符串中很有用,但对于multipart/form-data而言却没有用,因为它只会导致将文档视为text/plain,而不是实际的媒体类型。
如果不需要 contentEncoding,请使用不带contentMediaType的编码对象。

示例:

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:
            # Content-Type for application-level encoded resource is `text/plain`
            type: string
            contentMediaType: image/png
            contentEncoding: base64
          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: object
              $ref: '#/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.
引入encoding属性,使得可以控制multipart请求主体各部分的序列化。此属性是只适用于multipartapplication/x-www-form-urlencoded请求正文。

Encoding Object

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

固定字段
Field NameTypeDescription
contentTypestring用于编码特定属性的Content-Type。默认值取决于属性类型:object - application/json; array – 默认值是取决于内部类型;所有其他情况,默认值为application/octet-stream。该值可以是特定的媒体类型(例如application/json),通配符媒体类型(例如image/*)或逗号分隔的两种类型列表。
headersMap[string, Header Object | Reference Object]携带辅助信息的报头,该报头是一个map结构,例如 Content-Disposition。单独描述的Content-Type在本节中应将被忽略。如果请求正文媒体类型不是 multipart,该属性将被忽略。
stylestring描述特定属性值如何根据其类型进行序列化,有关 style属性的详细信息,请参见Parameter Object。包括默认值在内,与query参数是相同的值。如果请求正文媒体类型不是application/x-www-form-urlencodedmultipart/form-data,应该忽略该属性。如果显式定义了值,则contentType(隐式或显式)值将被忽略。
explodeboolean当为true,数组或object类型的属性值将被拆分,每个子项变成一个独立的属性值。该属性不会影响其他类型的属性。当 styleform时,默认值是true。其他情况,默认值是false。如果请求正文媒体类型不是application/x-www-form-urlencodedmultipart/form-data,应该忽略该属性。 如果显式定义了值,则contentType(隐式或显式)值将被忽略。
allowReservedboolean参数值是否允许包含RFC3986定义的保留字符,即 包含没有进行百分比编码的:/?#[]@!$&'()*+,;=字符。默认值是false。如果请求正文媒体类型不是application/x-www-form-urlencodedmultipart/form-data,应该忽略该属性。 如果显式定义了值,则contentType(隐式或显式)值将被忽略。

这个对象可以依据Specification Extensions来扩展。

Encoding Object 例子
requestBody:
  content:
    multipart/form-data:
      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: {}
      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
Responses Object

一个操作预期响应的容器,将HTTP响应代码映射为预期的响应。

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

没有被Responses Object覆盖的其他HTTP代码,可以使用default 作为默认响应。

所述Responses Object必须至少包含一个响应码,并且如果仅设置一个响应码,应当是对应操作成功的响应。

固定字段
Field NameTypeDescription
defaultResponse Object | Reference Object除了在HTTP中指定的响应码以外,其他响应的文档。使用此字段可以覆盖未声明的响应。
模式字段
Field PatternTypeDescription
HTTP Status CodeResponse Object | Reference Object可以将任何HTTP status code用作属性名称,但每个状态码只能使用一个属性来描述该HTTP状态代码的预期响应。该字段必须用引号引起来(例如,“ 200”),以实现JSON和YAML之间的兼容性。为了定义响应代码的范围,该字段可以包含大写的通配符X。例如,2XX表示之间的所有响应代码[200-299]。只有以下范围定义允许:1XX2XX3XX4XX,和5XX。如果使用显式代码定义了响应,则显式代码定义优先于该代码的范围定义。

这个对象可以依据Specification Extensions来扩展。

Responses Object 例子

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'
Response Object

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

固定字段
Field NameTypeDescription
descriptionstring必填。 响应的描述. 可以使用支持CommonMark syntax语法的富文本表示。
headersMap[string, Header Object | Reference Object]报头名字到其定义的map结构。RFC7230声明标头名称不区分大小写。如响应头使用"Content-Type"定义,则忽略该属性。
contentMap[string, Media Type Object]包含可能响应负载描述的map结构,子项是媒体类型或media type range。对于匹配了多个键值的响应,仅最具体的键值有效。例如,text/plain将覆盖text/*
linksMap[string, Link Object | Reference Object]响应中可以遵循的操作链接的map结构。map中的键值是链接的缩写,遵循Component Objects的命名约束。

这个对象可以依据Specification Extensions来扩展。

Response Object 例子

复杂类型数组的响应:

{
  "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
Callback Object

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

为了描述来自于API提供者的输入请求,独立于其他API调用,请使用 webhooks字段。

模式字段
Field PatternTypeDescription
{expression}Path Item Object | Reference Object一个路径项对象或者其的引用,用于定义回调请求及其期望响应。这里提供一个完整示例

这个对象可以依据Specification Extensions来扩展。

键值表达式

标识Path Item Object的键值是可以在运行时HTTP请求/响应的上下文中进行评估的runtime expression ,以标识将用于回调请求的URL。一个简单的例子可能是 $request.body#/url。但是,使用 runtime expression可以访问完整的HTTP消息。包括访问正文的任何部分,该正文是有遵循RFC6901的JSON指针格式。

例如,给定下面的HTTP请求:

POST /subscribe/myevent?queryUrl=https://clientdomain.com/stillrunning HTTP/1.1
Host: example.org
Content-Type: application/json
Content-Length: 187

{
  "failedUrl" : "https://clientdomain.com/failed",
  "successUrls" : [
    "https://clientdomain.com/fast",
    "https://clientdomain.com/medium",
    "https://clientdomain.com/slow"
  ] 
}

201 Created
Location: https://example.org/subscription/1

以下示例说明了各种表达式如何求值,这里假设回调操作有一个名为enventType路径参数和一个名为queryUrl的查询参数。

表达式
$urlhttps://example.org/subscribe/myevent?queryUrl=https://clientdomain.com/stillrunning
$methodPOST
$request.path.eventTypemyevent
$request.query.queryUrlhttps://clientdomain.com/stillrunning
$request.header.content-Typeapplication/json
$request.body#/failedUrlhttps://clientdomain.com/failed
$request.body#/successUrls/2https://clientdomain.com/medium
$response.header.Locationhttps://example.org/subscription/1
Callback Object 例子

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

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

以下示例展示了一个回调,其中对服务器进行了硬编码,而查询字符串参数来自请求正文中的idemail属性

transactionCallback:
  'http://notificationServer.com?transactionId={$request.body#/id}&email={$request.body#/email}':
    post:
      requestBody:
        description: Callback payload
        content:
          'application/json':
            schema:
              $ref: '#/components/schemas/SomePayload'
      responses:
        '200':
          description: callback successfully processed
Example Object
固定字段
Field NameTypeDescription
summarystring示例的简短描述。
descriptionstring示例的详细说明。 可以使用支持CommonMark syntax语法的富文本表示。
valueAny嵌入式的文字示例。value字段和 externalValue字段是互斥。为了表示用JSON或YAML不能自然表示的媒体类型示例,请使用字符串包含示例,并在必要时进行转义。
externalValuestring一个指向文字示例的URI。这提供了一种引用示例方法,而这种示例在JSON或YAML文档中不容易被包含。 value字段和 externalValue字段是互斥。请参阅解析Relative References的规则。

这个对象可以依据Specification Extensions来扩展。

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

Example Object 例子

请求正文中:

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: 'https://example.org/examples/address-example.xml'
    'text/plain':
      examples:
        textExample: 
          summary: This is a text example
          externalValue: 'https://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 Object

Link object表示响应的一种可能的设计时链接。链接的存在并不能保证调用者能成功调用它,而是提供响应和其他操作之间的已知关系和遍历机制。

不同于动态链接(即链接提供在响应有效载荷),OAS链接机制不需要在运行时响应链接信息。

对于提供了执行指令的计算链接,为了在操作中直接使用或当做参数调用参数使用,这里使用了runtime expression

固定字段
Field NameTypeDescription
operationRefstring对OAS操作的相对或绝对URI引用。该字段与operationId字段互斥,并且必须指向一个Operation Object。相对operationRef值可用于在OpenAPI定义中定位现有的Operation Object。请参阅解析 Relative References的规则。
operationIdstring一个现有并可解析的OAS操作名称,该操作有一个独一无二的operationId。该字段与operationRef字段互斥。
parametersMap[string, Any | {expression}]表示参数的map结构,这些参数将传递给通过operationIdoperationRef指定的操作。键值是要使用的参数名称,而值可以是常量或可以求值并传递给链接操作的表达式。对于在不同位置使用相同参数名称的操作(例如,path.id),可以使用parameter location [{in}.]{name}}对参数名称进行限定。
requestBodyAny | {expression}一个字符值或{expression},当调用目标操作时请求的正文使用该表达式。
descriptionstring链接的描述信息。可以使用支持CommonMark syntax语法的富文本表示。
serverServer Object目标操作使用的服务器对象。

这个对象可以依据Specification Extensions来扩展。

一个链接操作必须使用operationRefoperationId标识。如果使用operationId,该值必须在OAS文档范围内唯一。由于潜在的名字冲突,带有外部引用的OpenAPI文档优先选择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可能无法进行引用(Operation ObjectoperationId是可选字段),可以通过相对对象进行引用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引用时 转义正斜杠 是必要的。

Runtime Expressions

运行时表达式允许基于“仅在实际API调用发生时可用的HTTP消息中的信息”来定义。这个机制被 Link Objects and Callback Objects使用。

运行时表达式的定义遵循 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 取自 RFC6901, char 取自 RFC7159token 取自 RFC7230

name标识符区分大小写,而token不区分大小写。

下表提供了运行时表达式和它们在值中使用的例子:

例子
Source Locationexample expressionnotes
HTTP Method$method$method的值将是HTTP操作允许的值。
Requested media type$request.header.accept
Request parameter$request.path.id请求参数必须在父操作的parameters部分中,否则无法求值。这包含在请求报头在。
Request body property$request.body#/user/uuid在接受有效载荷的操作中,引用可以是requestBody的全部或一部分。
Request URL$url
Response value$response.body#/status在返回有效载荷的操作中,引用可以是requestBody的全部或一部分。
Response header$response.header.Server仅单个报头值可用。

运行时表达式保留引用值的类型。通过用花括号{}将表达式括起来,可以将表达式嵌入到字符串值中。

Header Object

报头对象在Parameter Object结构的基础上,做了如下修改:

  1. 去掉name字段,它已经在对应的headers map中给出。
  2. 去掉in, 它已经隐含在 header中。
  3. 所有受位置影响的限制,必须在header的位置中可用(例如, style))。
Header Object 例子

一个简单的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
Tag Object

为单个 Operation Object使用的tag,添加元数据。在操作对象实例中,不强制要求每个tag都有tag对象。

固定字段
Field NameTypeDescription
namestring必填。tag名字。
descriptionstringtag的描述信息。可以使用支持CommonMark syntax语法的富文本表示。
externalDocsExternal Documentation Object为这个tag添加外部文档。

这个对象可以依据Specification Extensions来扩展。

Tag Object 例子
{
	"name": "pet",
	"description": "Pets operations"
}
name: pet
description: Pets operations
Reference Object

一个简单的对象,用于引用OpenAPI文档中的其他组件,包括内部的和外部的组件。

$ref字符串值包含一个URI RFC3986, 该URL标识被引用值的位置。

请参阅解析Relative References的规则。

固定字段
Field NameTypeDescription
$refstring必填。 引用的标识符,必须是URL的格式。
summarystring简短的说明,默认情况下应该覆盖所引用组件的说明。如果被引用组件的类型不允许有summary字段,则此字段无效。
descriptionstring描述信息,默认情况下应该覆盖所引用组件的描述信息。可以使用支持CommonMark syntax语法的富文本表示。 如果被引用组件的类型不允许有description字段,则此字段无效。

该对象不能使用扩展的属性,任何扩展的属性将被忽略。

请注意,这里对扩展属性的限制,对引用对象和包含$ref关键字的Schema Objects是不同的。

Reference Object 例子
{
	"$ref": "#/components/schemas/Pet"
}
$ref: '#/components/schemas/Pet'
相对模式文档引用示例
{
  "$ref": "Pet.json"
}
$ref: Pet.yaml
带有嵌入式模式的相对文档引用示例
{
  "$ref": "definitions.json#/Pet"
}
$ref: definitions.yaml#/Pet
Schema Object

模式对象定义输入和输出数据类型。这些类型可以是对象、原始类型、数组。该对象是JSON Schema Specification Draft 2020-12的一个超集。

有关这些属性的更多信息,请参阅JSON Schema CoreJSON Schema Validation

除非另有说明,否则属性定义遵循JSON Schema的定义,并且不添加任何其他语义。当JSON Schema的约定的行为需要通过应用程序定义(例如,批注),OAS将语义定义推迟到应用程序使用OpenAPI文档的时候。

属性

除了JSON Schema草案2020-12general purpose meta-schema中指定的词汇表之外,定义OpenAPI 模式对象dialect还需要 OAS base vocabulary

URI https://spec.openapis.org/oas/3.1/dialect/base(the “OAS模式方言id”)定义了本规范的OpenAPI模式对象方言。

以下属性取自JSON Schema规范,但OAS扩展了它们的定义:

  • description - 可以使用支持CommonMark syntax语法的富文本表示。
  • format - 更多细节请查阅 Data Type Formats。在依赖JSON Schema的定义格式的同时,OAS提供了一些额外的预定义格式。
    除了包含OAS方言的JSON模式属性之外,模式对象还支持其他词汇表中的关键字或完全任意的属性。

除了包含OAS方言的JSON模式属性之外,模式对象还支持其他词汇表中的关键字或完全任意的属性。

OpenAPI规范的基本词汇表由以下关键字组成:

固定字段
Field NameTypeDescription
discriminatorDiscriminator Object增加对多态的支持。鉴别器是一个用于区分不同模式的对象名称,而这些模式对有效负载的描述。有关更多详细信息,请参阅 Composition and Inheritance
xmlXML Object只能用于属性模式,对根模式无效。添加额外的元数据来描述此属性的XML表示形式。
externalDocsExternal Documentation Object本模式使用的外部文档。
exampleAny包含本模式示例的属性,没有格式限制。为了展现在JSON或YAML中不能自然显示的例子,可以在必要时使用字符串值包含带转义的示例。

Deprecated: 推荐使用JSON Schema的 examples,而不是example属性。 example不鼓励使用,并且此规范的更高版本可能会将其删除。

这个对象可以依据Specification Extensions来扩展, 对象可以用规范扩展来扩展,但是如前所述,在本对象中扩展属性可以省略x-前缀。

组合和继承(继承)

OpenAPI规范允许使用JSON Schema的allOf属性来组合和扩展模型定义,从而有效地提供了模型组合。 allOf是一个对象定义的数组,每个独立对象定义都是合法的,然后一起组成一个对象。

尽管组合提供了模型可扩展性,但并不意味着模型之间具有层次结构。为了支持多态,OpenAPI规范添加了discriminator字段。使用时,discriminator将是属性的名称,该属性决定哪个模式定义是有效的模型结构。因此,discriminator字段必须是必填字段。为继承实例定义鉴别符的值有两种方法:

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

当JSON定义转换为XML时,xml属性允许附加定义。 XML Object包含可用选项的额外信息。

指定模式方言

对于工具而言,重要的是能够确定用哪种方言或元数据模式,处理任何给定的资源:JSON Schema Core、JSON Schema Validation、OpenAPI Schema方言或自定义元数据模式。

$schema关键字可用出现在任何根模式对象中。如果存在,必须被用于确定在处理模式使用哪种方言。这允许使用与JSON Schema的其他草案兼容的Schema Object,而不是默认的Draft 2020-12。工具必须支持OAS方言模式ID,并且可以支持$schema的扩展值。

为了OAS文档中包含的所有模式对象,允许使用不同的$schema 默认值,应该在OpenAPI 对象中设置jsonSchemaDialect的值。如果默认值没有设置,这些模式对象必须使用OAS方言模式id。模式对象中$schema的值总是覆盖任何默认值。

当从不是OAS文档的外部资源(例如,原始JSON模式资源)引用模式对象时,该资源内$schema的值必须遵守JSON Schema rules

Schema Object 例子
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属性的模式

简单字符串到字符串映射:

{
  "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
Discriminator Object

当请求正文或响应有效负载可能是许多不同模式之一时,使用discriminator对象帮助进行序列化、反序列化和校验。鉴别器是模式中特定的对象,根据与之相关的值,通知文档使用者当前是哪种模式。

使用鉴别器时,将不考虑 内联 模式。

固定字段
Field NameTypeDescription
propertyNamestring必填。payload中属性名字,在payload中包含鉴别器的值。
mappingMap[string, string]一个对象,用于保存有效载荷值与模式名称或引用之间的映射。

这个对象可以依据Specification Extensions来扩展。

仅当使用复合关键字oneOfanyOfallof时,鉴别器对象才是合法的。

在OAS 3.0中,响应的有效载荷可以使用其中的一种类型描述。

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

这意味着有效载荷 必须CatDogLizard描述的模式中的一种,精确匹配并通过校验。在这种情况下,根据模式的复杂性,鉴别器可以充当快捷方式验证和匹配模式选择的“提示”,这可能是一项昂贵的操作。然后,我们可以准确地描述哪个字段告诉我们要使用哪种模式

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

在响应的payload中名字为petType的属性 必须 存在,并且该值将与OAS文档中模式定义的名称相对应。因此响应payload:

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

将指示在这个联合payload中使用Cat模式。

在鉴别器字段的值与模式名称不匹配或不可能进行隐式映射的情况下,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构造结合使用时,使用鉴别器可以避免多个模式可能满足单个有效负载的歧义。

oneOfanyOf用例中,必须明确列出所有可能的模式。为了避免冗余,可以将鉴别器添加到父模式定义中,这样包含父模式的所有模式都可以在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"
}

由于Dogmapping的元素,所以被将映射到。

XML Object

一个元数据对象,允许进行更精细的XML模型定义。

当使用数组时,不能推断XML元素名称(对于单数/复数形式),这事应该将name属性添加到信息中。请参阅示例以了解预期行为。

固定字段
Field NameTypeDescription
namestring替换用于描述的模式属性的元素/属性的名称。当定义在items内,它将影响列表中各个XML元素的名称。当typearray(在items之外)定义时,它将影响wrapping元素。且仅当wrappedtrue如此,如果wrappedfalse,它将被忽略。
namespacestring命名空间的URI。必须是绝对路径的URI格式。
prefixstringname使用的前缀。
attributeboolean声明属性定义是否转换为属性,而不是元素。默认值是 false
wrappedboolean只能用于数组定义。表示该数组是包装式的(例如<books><book/><book/></books>)还是未包装的(<book/><book/>)。默认值为false。只有当typearray(在items之外)定义时,该定义有效。

这个对象可以依据Specification Extensions来扩展。

XML Object 示例

XML对象定义的示例包含在 Schema Object的属性定义中,并带有其XML表示的示例。

No XML Element

基本字符型属性:

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

基本的字符串数组属性(默认情况下wrappedfalse):

{
    "animals": {
        "type": "array",
        "items": {
            "type": "string"
        }
    }
}
animals:
  type: array
  items:
    type: string
<animals>...</animals>
<animals>...</animals>
<animals>...</animals>
XML Name Replacement
{
  "animals": {
    "type": "string",
    "xml": {
      "name": "animal"
    }
  }
}
animals:
  type: string
  xml:
    name: animal
<animal>...</animal>
XML Attribute, Prefix and Namespace

在这个例子中,一个完整的模型定义如下:

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

改变元素名字:

{
  "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参数或作为查询参数),相互TLS(使用客户端证书),OAuth2的通用流程(隐式,密码,客户端凭据和授权代码)在 RFC6749OpenID Connect Discovery中定义。请注意,从2020年起 OAuth 2.0 Security Best Current Practice将弃用隐式流程。对于大多数用例,建议使用带有PKCE的授权码授予流程。

固定字段
Field NameTypeApplies ToDescription
typestringAny必填。 安全模式类型。有效值为: "apiKey", "http", "mutualTLS", "oauth2", "openIdConnect"
descriptionstringAny安全模式描述。可以使用支持CommonMark syntax语法的富文本表示。
namestringapiKey必填。 报头、查询或cookie参数使用的名字。
instringapiKey必填。 API key的位置。 有效值为: "query", "header" or "cookie"
schemestringhttp必填。 HTTP认证机制的名字,用在Authorization header as defined in RFC7235. 使用的值应该在IANA Authentication Scheme registry中已注册。
bearerFormatstringhttp ("bearer")向客户端提示令牌的格式。令牌通常由授权服务器生成,因此此信息主要用于文档。
flowsOAuth Flows Objectoauth2必填。 包含流程类型支持的配置信息的对象。
openIdConnectUrlstringopenIdConnect必填。 用于发现OAuth2配置值的OpenId Connect URL。这必须以URL的形式。OpenID Connect标准要求使用TLS。

这个对象可以依据Specification Extensions来扩展。

Security Scheme Object 例子
基本认证的例子
{
  "type": "http",
  "scheme": "basic"
}
type: http
scheme: basic
API Key Sample
{
  "type": "apiKey",
  "name": "api_key",
  "in": "header"
}
type: apiKey
name: api_key
in: header
JWT Bearer Sample
{
  "type": "http",
  "scheme": "bearer",
  "bearerFormat": "JWT",
}
type: http
scheme: bearer
bearerFormat: JWT
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
OAuth Flows Object

支持的OAuth流程的允许配置。

固定字段
Field NameTypeDescription
implicitOAuth Flow ObjectOAuth隐式流程的配置
passwordOAuth Flow ObjectOAuth资源所有者密码流程的配置
clientCredentialsOAuth Flow ObjectOAuth客户端凭据流程的配置。以前在OpenAPI 2.0中叫application
authorizationCodeOAuth Flow ObjectOAuth授权码流程的配置。 以前在OpenAPI 2.0中叫 accessCode

这个对象可以依据Specification Extensions来扩展。

OAuth Flow Object

支持OAuth流程的详细配置

固定字段
Field NameTypeApplies ToDescription
authorizationUrlstringoauth2 ("implicit", "authorizationCode")必填。本流程使用的认证URL,必须是URL的形式。OAuth2标准要求使用TLS。
tokenUrlstringoauth2 ("password", "clientCredentials", "authorizationCode")必填。 本流程使用的认证token URL,必须是URL的形式。OAuth2标准要求使用TLS。
refreshUrlstringoauth2更新token使用的URL,必须是URL的形式。OAuth2标准要求使用TLS。
scopesMap[string, string]oauth2必填。OAuth2安全模式可用的范围,是一个范围名字和其简短描述的map结构,可以是空。

这个对象可以依据Specification Extensions来扩展。

OAuth Flow Object 例子
{
  "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 
Security Requirement Object

支持该操作所需的安全模式列表。用于每个属性的名字必须与安全模式相对应,这些安全模式必须在Components Object下的Security Schemes中声明。

包含多个模式的安全性需求对象,需要一个被认证的请求必须满足所有的认证模式。这样可以支持需要多个查询参数或HTTP报头才能传达安全信息的场景。

当在 OpenAPI Object or Operation Object上定义了一个安全需求对象列表时,只需要满足列表中的一个安全需求对象来授权该请求。

模式字段
Field PatternTypeDescription
{name}[string]每个名字必须与安全模式相对应,这些安全模式必须在Components Object下的Security Schemes中声明。如果安全方案的类型为"oauth2""openIdConnect",则该值是执行所需的作用域名称的列表,并且如果授权不需要指定的作用域,则该列表可以为空。对于其他安全模式类型,数组可以包含执行所需的角色名称列表,但未进行其他定义或在带内交换。
Security Requirement Object 例子
Non-OAuth2 Security Requirement
{
  "api_key": []
}
api_key: []
OAuth2 Security Requirement
{
  "petstore_auth": [
    "write:pets",
    "read:pets"
  ]
}
petstore_auth:
- write:pets
- read:pets
可选的OAuth2安全机制

可选的OAuth2安全机制,将在OpenAPI ObjectOperation Object在定义:

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

规范扩展

尽管OpenAPI规范尝试适应大多数用例,但可以在某些点添加额外的数据以扩展规范。

"x-"开头的模式字段,用于实现扩展属性。

Field PatternTypeDescription
^x-Any允许扩展OpenAPI模式。字段名必须以x-开头,例如,x-internal-idx-oai-x-oas-开头的字段名保留给 OpenAPI Initiative定义使用。 该值可以是null、原始值、数组或对象。

可用工具可能支持也可能不支持扩展,但是可以修改工具以支持添加的请求(如果工具是内部的或开源的)。

Security Filtering

即使API文档的本质核心对象,也可以在OpenAPI规范中声明并将其保留为空,或者完成删除。

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

这是两个例子:

  1. Paths Object存在,但为空。这可能是违反直觉的,这也许告诉查看着他们使用了正确的地址,但不能访问任何文档。他们访问的Info Object中,至少有一个也许包含有关身份验证的其他信息。
  2. Path Item Object 也许是空的。在这种情况下,观察者将意识到该路径是存在的,但是不能看到任何操作或参数。这与从Paths Object隐藏路径自身不同,因为用户将意识到它的存在。这使得文档提供者很好的控制查看者看到的内容。

附录 A: 修订历史

VersionDateNotes
3.1.02021-02-15Release of the OpenAPI Specification 3.1.0
3.1.0-rc12020-10-08rc1 of the 3.1 specification
3.1.0-rc02020-06-18rc0 of the 3.1 specification
3.0.32020-02-20Patch release of the OpenAPI Specification 3.0.3
3.0.22018-10-08Patch release of the OpenAPI Specification 3.0.2
3.0.12017-12-06Patch release of the OpenAPI Specification 3.0.1
3.0.02017-07-26Release of the OpenAPI Specification 3.0.0
3.0.0-rc22017-06-16rc2 of the 3.0 specification
3.0.0-rc12017-04-27rc1 of the 3.0 specification
3.0.0-rc02017-02-28Implementer’s Draft of the 3.0 specification
2.02015-12-31Donation of Swagger 2.0 to the OpenAPI Initiative
2.02014-09-08Release of Swagger 2.0
1.22014-03-14Initial release of the formal document.
1.12012-08-22Release of Swagger 1.1
1.02011-08-10First release of the Swagger Specification
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值