The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14RFC2119RFC8174 when, and only when, they appear in all capitals, as shown here.
OpenAPI 规范(OAS),是定义一个标准的、与具体编程语言无关的RESTful API的规范。OpenAPI 规范使得人类和计算机都能在“不接触任何程序源代码和文档、不监控网络通信”的情况下理解一个服务的作用。如果您在定义您的 API 时做的很好,那么使用 API 的人就能非常轻松地理解您提供的 API 并与之交互了。
原始类型可以有一个可选的修饰属性:format。 OAS 使用多个已知的格式来丰富类型定义。尽管如此,为了文档的需要,format 属性被设计为一个 string 类型的开放属性值,可以包含任意值。比如 "email", "uuid" 等未被此规范定义的格式也可以被使用。没有被定义的 format 属性类型遵从 JSON Schema 中的类型定义。无法识别某个 format 值的工具应该回退到 type 值,就像 format 未被指定一样。
{"title": "Sample Pet Store App","description": "This is a sample server for a pet store.","termsOfService": "http://example.com/terms/","contact": {"name":"API Support","url":"http://www.example.com/support","email":"support@example.com" },"license": {"name":"Apache 2.0","url":"http://www.apache.org/licenses/LICENSE-2.0.html" },"version": "1.0.1"}
title:Sample Pet Store Appdescription:This is a sample server for a pet store.termsOfService:http://example.com/terms/contact:name:API Supporturl:http://www.example.com/supportemail:support@example.comlicense:name:Apache 2.0url:http://www.apache.org/licenses/LICENSE-2.0.htmlversion:1.0.1
servers:- url:https://development.gigantic-server.com/v1description:Development server- url:https://staging.gigantic-server.com/v1description:Staging server- url:https://api.gigantic-server.com/v1description: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 servervariables:username:# note! no enum here means it is an open valuedefault:demodescription: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
"components": {"schemas": {"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:Category:type:objectproperties:id:type:integerformat:int64name:type:stringTag:type:objectproperties:id:type:integerformat:int64name:type:stringparameters:skipParam:name:skipin:querydescription:number of items to skiprequired:trueschema:type:integerformat:int32limitParam:name:limitin:querydescription:max records to returnrequired:trueschema:type:integerformat:int32responses:NotFound:description:Entity not found.IllegalInput:description:Illegal input for operation.GeneralError:description:General Errorcontent:application/json:schema:$ref:'#/components/schemas/GeneralError'securitySchemes:api_key:type:apiKeyname:api_keyin:headerpetstore_auth:type:oauth2flows:implicit:authorizationUrl:http://example.org/api/oauth/dialogscopes:write:pets:modify pets in your accountread:pets:read your pets
{"/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 toresponses:'200':description:A list of pets.content:application/json:schema:type:arrayitems:$ref:'#/components/schemas/pet'
{"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 IDsummary:Find pets by IDoperationId:getPetsByIdresponses:'200':description:pet responsecontent:'*/*':schema:type:arrayitems:$ref:'#/components/schemas/Pet'default:description:error payloadcontent:'text/html':schema:$ref:'#/components/schemas/ErrorModel'parameters:- name:idin:pathdescription:ID of pet to userequired:trueschema:type:arraystyle:simpleitems:type:string
{"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":"Invalid input","content": {"application/json": {},"application/xml": {} } } },"security": [ {"petstore_auth": ["write:pets","read:pets" ] } ]}
tags:- petsummary:Updates a pet in the store with form dataoperationId:updatePetWithFormparameters:- name:petIdin:pathdescription:ID of pet that needs to be updatedrequired:trueschema:type:stringrequestBody:content:'application/x-www-form-urlencoded':schema:properties:name:description:Updated name of the pettype:stringstatus:description:Updated status of the pettype:stringrequired: - statusresponses:'200':description:Pet updated.content:'application/json': {}'application/xml': {}'405':description:Invalid inputcontent:'application/json': {}'application/xml': {}security:- petstore_auth: - write:pets - read:pets
{"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:tokenin:headerdescription:token to be passed as a headerrequired:trueschema:type:arrayitems:type:integerformat:int64style:simple
一个值类型为字符串的路径参数:
{"name": "username","in": "path","description": "username to fetch","required": true,"schema": {"type":"string" }}
name:usernamein:pathdescription:username to fetchrequired:trueschema: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:idin:querydescription:ID of the object to fetchrequired:falseschema:type:arrayitems:type:stringstyle:formexplode:true
{"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 systemcontent:'application/json':schema:$ref:'#/components/schemas/User'examples:user:summary:User ExampleexternalValue:'http://foo.bar/examples/user-example.json''application/xml':schema:$ref:'#/components/schemas/User'examples:user:summary:User Example in XMLexternalValue:'http://foo.bar/examples/user-example.xml''text/plain':examples:user:summary:User example in text plain formatexternalValue:'http://foo.bar/examples/user-example.txt''*/*':examples:user:summary:User example in other formatexternalValue:'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 systemrequired:truecontent:text/plain:schema:type:arrayitems:type:string
{"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 catvalue:name:FluffypetType:Catcolor:Whitegender:malebreed:Persiandog:summary:An example of a dog with a cat's namevalue:name:PumapetType:Dogcolor:Blackgender:Femalebreed:Mixedfrog:$ref:"#/components/examples/frog-example"
# content transferred with base64 encodingschema:type:stringformat:base64
# content transferred in binary (octet-stream):schema:type:stringformat:binary
这些示例同时适用于文件上传和下载。
一个使用POST操作提交文件的requestBody看起来像下面这样:
requestBody:content:application/octet-stream:# any media type is accepted, functionally equivalent to `*/*`schema:# a binary file of any typetype:stringformat:binary
此外,可以指定明确的媒体类型:
# multiple, specific media types may be specified:requestBody:content:# a binary file of type png or jpeg'image/jpeg':schema:type:stringformat:binary'image/png':schema:type:stringformat: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
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
id:
type: string
format: uuid
address:
# default Content-Type for objects is `application/json`
type: object
properties: {}
profileImage:
# default Content-Type for string/binary is `application/octet-stream`
type: string
format: binary
children:
# default Content-Type for arrays is based on the `inner` type (text/plain here)
type: array
items:
type: string
addresses:
# default Content-Type for arrays is based on the `inner` type (object shown, so `application/json` in this example)
type: array
items:
type: '#/components/schemas/Address'
requestBody:
content:
multipart/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
{
"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'
description: A simple string response
representations:
text/plain:
schema:
type: string
带HTTP头的普通文本类型的响应:
{
"description": "A simple string response",
"content": {
"text/plain": {
"schema": {
"type": "string"
}
}
},
"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 对象
A map of possible out-of band callbacks related to the parent operation. 映射中的每个值都是一个描述一组可能会被API提供者发起的请求和相应的响应的 Path Item Object 。用以标识回调对象的键是一个表达式,表达式会在运行时被计算,得到的值作为回调操作的URL。
用于标识 Path Item Object 的键是一个 runtime expression,此表达式会在运行时的HTTP请求/响应上下文中被计算,计算结果用于表示回调请求的URL。 一个简单的例子是 $request.body#/url。 However, using a runtime expression the complete HTTP message can be accessed. This includes accessing any part of a body that a JSON Pointer RFC6901 can reference.
myWebhook:
'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: webhook successfully processed and no retries will be performed
In all cases, the example value is expected to be compatible with the type schema of its associated value. Tooling implementations MAY choose to validate compatibility automatically, and reject the example value(s) if incompatible.
Example 对象示例
# in a model
schemas:
properties:
name:
type: string
examples:
name:
$ref: http://example.org/petapi-examples/openapi.json#/components/examples/name-example
# in a request body:
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'
# in a parameter
parameters:
- name: 'zipCode'
in: 'query'
schema:
type: 'string'
format: 'zip-code'
examples:
zip-example:
$ref: '#/components/examples/zip-example'
# in a response
responses:
'200':
description: your car appointment has been booked
content:
application/json:
schema:
$ref: '#/components/schemas/SuccessResponse'
examples:
confirmation-success:
$ref: '#/components/examples/confirmation-success'
Link 对象
The Link 对象 represents a possible design-time link for a response. The presence of a link does not guarantee the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations.
Unlike dynamic links (i.e. links provided in the response payload), the OAS linking mechanism does not require link information in the runtime response.
For computing links, and providing instructions to execute them, a runtime expression is used for accessing values in an operation and using them as parameters while invoking the linked operation.
A linked operation MUST be identified using either an operationRef or operationId. In the case of an operationId, it MUST be unique and resolved in the scope of the OAS document. Because of the potential for name clashes, the operationRef syntax is preferred for specifications with external references.
Examples
Computing a link from a request operation where the $request.path.id is used to pass a request parameter to the linked operation.
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
When a runtime expression fails to evaluate, no parameter value is passed to the target operation.
Values from the response body can be used to drive a linked operation.
links:
address:
operationId: getUserAddressByUUID
parameters:
# get the `id` field from the request path parameter named `id`
userUuid: $response.body#/uuid
Clients follow all links at their discretion. Neither permissions, nor the capability to make a successful call to that link, is guaranteed solely by the existence of a relationship.
OperationRef Examples
As references to operationId MAY NOT be possible (the operationId is an optional value), references MAY also be made through a relative operationRef:
Note that in the use of operationRef, the escaped forward-slash is necessary when using JSON references.
Runtime Expressions
Runtime expressions allow defining values based on information that will only be available within the HTTP message in an actual API call. This mechanism is used by Link Objects and Callback Objects.
The runtime expression is defined by the following ABNF syntax
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" ["#" fragment]
fragment = a JSON Pointer [RFC 6901](https://tools.ietf.org/html/rfc6901)
name = *( char )
char = as per RFC [7159](https://tools.ietf.org/html/rfc7159#section-7)
token = as per RFC [7230](https://tools.ietf.org/html/rfc7230#section-3.2.6)
The name identifier is case-sensitive, whereas token is not.
The table below provides examples of runtime expressions and examples of their use in a value:
Examples
Runtime expressions preserve the type of the referenced value. Expressions can be embedded into string values by surrounding the expression with {} curly braces.
{
"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
Adds metadata to a single tag that is used by the Operation Object. It is not mandatory to have a Tag Object per tag defined in the Operation Object instances.
In an example, a JSON Reference MAY be used, with the explicit restriction that examples having a JSON format with object named $ref are not allowed. Therefore, that example, structurally, can be either a string primitive or an object, similar to additionalProperties.
In all cases, the payload is expected to be compatible with the type schema for the associated value. Tooling implementations MAY choose to validate compatibility automatically, and reject the example value(s) if they are incompatible.
# in a model
schemas:
properties:
name:
type: string
example:
$ref: http://foo.bar#/examples/name-example
# in a request body, note the plural `examples`
requestBody:
content:
'application/json':
schema:
$ref: '#/components/schemas/Address'
examples:
foo:
value: {"foo": "bar"}
bar:
value: {"bar": "baz"}
'application/xml':
examples:
xml:
externalValue: 'http://foo.bar/examples/address-example.xml'
'text/plain':
examples:
text:
externalValue: 'http://foo.bar/examples/address-example.txt'
# in a parameter
parameters:
- name: 'zipCode'
in: 'query'
schema:
type: 'string'
format: 'zip-code'
example:
$ref: 'http://foo.bar#/examples/zip-example'
# in a response, note the singular `example`:
responses:
'200':
description: your car appointment has been booked
content:
application/json:
schema:
$ref: '#/components/schemas/SuccessResponse'
example:
$ref: http://foo.bar#/examples/address-example.json
format - 查看 Data Type Formats 以深入了解细节。在依靠 JSON Schema 定义的格式的同时,OAS 额外提供了一些预定义的格式。
default - The default value represents what would be assumed by the consumer of the input as the value of the schema if one is not provided. 不同于 JSON Schema,这个值必须符合定义与相同级别的 Schema Object 中定义的类型,比如 type 是 string,那么 default 可以是 "foo" 但不能是 1。
The OpenAPI Specification allows combining and extending model definitions using the allOf property of JSON Schema, in effect offering model composition. allOf takes an array of object definitions that are validated independently but together compose a single object.
While composition offers model extensibility, it does not imply a hierarchy between the models. To support polymorphism, the OpenAPI Specification adds the discriminator field. When used, the discriminator will be the name of the property that decides which schema definition validates the structure of the model. As such, the discriminator field MUST be a required field. There are are two ways to define the value of a discriminator for an inheriting instance.
Use the schema name.
Override the schema name by overriding the property with a new value. If a new value exists, this takes precedence over the schema name.
As such, inline schema definitions, which do not have a given id, cannot be used in polymorphism.
XML Modeling
The xml property allows extra definitions when translating the JSON definition to XML. The XML Object contains additional information about the available options.
{
"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 对象
当一个 request bodies 或 response payloads 可以是多种 schemas 时,可以使用一个 discriminator 对象来帮助序列化、反序列化和校验。 The discriminator is a specific object in a schema which is used to inform the consumer of the specification of an alternative schema based on the value associated with it.
也就是说 payload 必须 且只能满足 Cat、Dog 或 Lizzard schemas 中的一个。 In this case, a discriminator MAY act as a "hint" to shortcut validation and selection of the matching schema which may be a costly operation, depending on the complexity of the schema. We can then describe exactly which field tells us which schema to use:
The expectation now is that a property with name pet_typeMUST be present in the response payload, and the value will correspond to the name of a schema defined in the OAS document. Thus the response payload:
{
"id": 12345,
"pet_type": "Cat"
}
Will indicate that the Cat schema be used in conjunction with this payload.
In scenarios where the value of the discriminator field does not match the schema name or implicit mapping is not possible, an optional mapping definition MAY be used:
Here the discriminator value of dog will map to the schema #/components/schemas/Dog, rather than the default (implicit) value of Dog. If the discriminator value does not match an implicit or explicit mapping, no schema can be determined and validation SHOULD fail. Mapping keys MUST be string values, but tooling MAY convert response values to strings for comparison.
When used in conjunction with the anyOf construct, the use of the discriminator can avoid ambiguity where multiple schemas may satisfy a single payload.
In both the oneOf and anyOf use cases, all possible schemas MUST be listed explicitly. To avoid redundancy, the discriminator MAY be added to a parent schema definition, and all schemas comprising the parent schema in an allOf construct may be used as an alternate schema.
For example:
components:
schemas:
Pet:
type: object
required:
- pet_type
properties:
pet_type:
type: string
discriminator:
propertyName: pet_type
mapping:
cachorro: Dog
Cat:
allOf:
- $ref: '#/components/schemas/Pet'
- type: object
# all other properties specific to a `Cat`
properties:
name:
type: string
Dog:
allOf:
- $ref: '#/components/schemas/Pet'
- type: object
# all other properties specific to a `Dog`
properties:
bark:
type: string
Lizard:
allOf:
- $ref: '#/components/schemas/Pet'
- type: object
# all other properties specific to a `Lizard`
properties:
lovesRocks:
type: boolean
a payload like this:
{
"pet_type": "Cat",
"name": "misty"
}
will indicate that the Cat schema be used. Likewise this schema:
{
"pet_type": "cachorro",
"bark": "soft"
}
will map to Dog because of the definition in the mappings element.
XML 对象
一个为 XML 模型定义微调过的元数据对象。
当使用数组时,不会推测 XML 元素的名称(单数或复数形式),所以应该添加 name 属性来提供此信息。 查看展示此期望的示例。
当When a list of Security Requirement Objects is defined on the Open API 对象 或 [Operation 对象] (#operationObject) 包含一组 Security Requirement 对象时,请求只需要满足其中一个即可。
Some objects in the OpenAPI Specification MAY be declared and remain empty, or be completely removed, even though they are inherently the core of the API documentation.
The reasoning is to allow an additional layer of access control over the documentation. While not part of the specification itself, certain libraries MAY choose to allow access to parts of the documentation based on some form of authentication/authorization.
Two examples of this:
The Paths Object MAY be empty. It may be counterintuitive, but this may tell the viewer that they got to the right place, but can't access any documentation. They'd still have access to the Info Object which may contain additional information regarding authentication.
The Path Item Object MAY be empty. In this case, the viewer will be aware that the path exists, but will not be able to see any of its operations or parameters. This is different than hiding the path itself from the Paths Object, so the user will not be aware of its existence. This allows the documentation provider to finely control what the viewer can see.
一组相对于父操作的可能出现的回调映射,A map of possible out-of band callbacks related to the parent operation. 映射中的每一个键都唯一的映射一个 Callback 对象, that describes a request that may be initiated by the API provider and the expected responses. The key value used to identify the callback object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation.
A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for Component Objects.
A relative or absolute reference to an OAS operation. This field is mutually exclusive of the operationId field, and MUST point to an Operation Object. Relative operationRef values MAY be used to locate an existing Operation Object in the OpenAPI definition.
operationId
string
The name of an existing, resolvable OAS operation, as defined with a unique operationId. This field is mutually exclusive of the operationRef field.
A map representing parameters to pass to an operation as specified with operationId or identified via operationRef. The key is the parameter name to be used, whereas the value can be a constant or an expression to be evaluated and passed to the linked operation. The parameter name can be qualified using the parameter location[{in}.]{name} for operations that use the same parameter name in different locations (e.g. path.id).
Adds support for polymorphism. The discriminator is an object name that is used to differentiate between other schemas which may satisfy the payload description. See Composition and Inheritance for more details.