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 when, and only when, they appear in all capitals, as shown here.
This document is licensed under .
介绍
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 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
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
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
Paths 对象
模式字段
字段名模式
类型
描述
/{path}
路径模板匹配
假设有以下路径,明确定义的路径 /pets/mine 会被优先匹配:
/pets/{petId}
/pets/mine
以下路径被认为是等价的而且是无效的:
/pets/{petId}
/pets/{name}
以下路径会产生歧义:
/{entity}/me
/books/{id}
Paths 对象示例
{
"/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'
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
style: simple
items:
type: string
一个可用于此操作的额外的 server 数组,这里的定义会覆盖 Path Item 对象 或 顶层的定义。
Operation 对象示例
{
"tags": [
"pet"
],
"summary": "Updates a pet in the store with form data",
"operationId": "updatePetWithForm",
"parameters": [
{
"name": "petId",
"in": "path",
"description": "ID of pet that needs to be updated",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/x-www-form-urlencoded": {
"schema": {
"type": "object",
"properties": {
"name": {
"description": "Updated name of the pet",
"type": "string"
},
"status": {
"description": "Updated status of the pet",
"type": "string"
}
},
"required": ["status"]
}
}
}
},
"responses": {
"200": {
"description": "Pet updated.",
"content": {
"application/json": {},
"application/xml": {}
}
},
"405": {
"description": "Invalid input",
"content": {
"application/json": {},
"application/xml": {}
}
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
}
tags:
- pet
summary: Updates a pet in the store with form data
operationId: updatePetWithForm
parameters:
- name: petId
in: path
description: ID of pet that needs to be updated
required: true
schema:
type: string
requestBody:
content:
'application/x-www-form-urlencoded':
schema:
properties:
name:
description: Updated name of the pet
type: string
status:
description: Updated status of the pet
type: string
required:
- status
responses:
'200':
description: Pet updated.
content:
'application/json': {}
'application/xml': {}
'405':
description: Invalid input
content:
'application/json': {}
'application/xml': {}
security:
- petstore_auth:
- write:pets
- read:pets
External Documentation 对象
允许引用外部资源来扩展文档。
固定字段
字段名
类型
描述
description
string
url
string
必选. 外部文档的URL地址,这个值必须是URL地址格式。
External Documentation 对象示例
{
"description": "Find more info here",
"url": "https://example.com"
}
description: Find more info here
url: https://example.com
in: query
name: coordinates
content:
application/json:
schema:
type: object
required:
- lat
- long
properties:
lat:
type: number
long:
type: number
Request Body Object
定义请求体。
固定字段
字段名
类型
描述
description
string
content
required
boolean
指定请求体是不是应该被包含在请求中,默认值是false。
Request Body 示例
一个引用了模型定义的请求体。
{
"description": "user to add to the system",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/User"
},
"examples": {
"user" : {
"summary": "User Example",
"externalValue": "http://foo.bar/examples/user-example.json"
}
}
},
"application/xml": {
"schema": {
"$ref": "#/components/schemas/User"
},
"examples": {
"user" : {
"summary": "User example in XML",
"externalValue": "http://foo.bar/examples/user-example.xml"
}
}
},
"text/plain": {
"examples": {
"user" : {
"summary": "User example in Plain text",
"externalValue": "http://foo.bar/examples/user-example.txt"
}
}
},
"*/*": {
"examples": {
"user" : {
"summary": "User example in other format",
"externalValue": "http://foo.bar/examples/user-example.whatever"
}
}
}
}
}
description: user to add to the system
content:
'application/json':
schema:
$ref: '#/components/schemas/User'
examples:
user:
summary: User Example
externalValue: 'http://foo.bar/examples/user-example.json'
'application/xml':
schema:
$ref: '#/components/schemas/User'
examples:
user:
summary: User Example in XML
externalValue: 'http://foo.bar/examples/user-example.xml'
'text/plain':
examples:
user:
summary: User example in text plain format
externalValue: 'http://foo.bar/examples/user-example.txt'
'*/*':
examples:
user:
summary: User example in other format
externalValue: 'http://foo.bar/examples/user-example.whatever'
请求体是一个字符串的数组:
{
"description": "user to add to the system",
"content": {
"text/plain": {
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
description: user to add to the system
required: true
content:
text/plain:
schema:
type: array
items:
type: string
Media Type 对象
每种媒体类型对象都有相应的结构和示例来描述它。
固定字段
字段名
类型
描述
schema
定义此媒体类型的结构。
example
Any
媒体类型的示例。示例对象应该符合此媒体类型的格式, 这里指定的example对象 object is mutually exclusive of the examples object. 而且如果引用的schema也包含示例,在这里指定的example值将会覆盖schema提供的示例。
examples
媒体类型的示例,每个媒体对象的值都应该匹配它对应的媒体类型的格式。 The examples object is mutually exclusive of the example object. 而且如果引用的schema也包含示例,在这里指定的example值将会覆盖schema提供的示例。
{
"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"
requestBody:
content:
application/octet-stream:
# any media type is accepted, functionally equivalent to `*/*`
schema:
# a binary file of any type
type: string
format: binary
此外,可以指定明确的媒体类型:
# multiple, specific media types may be specified:
requestBody:
content:
# a binary file of type png or jpeg
'image/jpeg':
schema:
type: string
format: binary
'image/png':
schema:
type: string
format: binary
为了同时上传多个文件,必须指定multipart媒体类型:
requestBody:
content:
multipart/form-data:
schema:
properties:
# The property name 'file' will be used for all files.
file:
type: array
items:
type: string
format: binary
x-www-form-urlencoded 请求体的支持
requestBody:
content:
application/x-www-form-urlencoded:
schema:
type: object
properties:
id:
type: string
format: uuid
address:
# complex types are stringified to support RFC 1866
type: object
properties: {}
requestBody:
content:
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
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
Example 对象
固定字段
字段名
类型
描述
summary
string
example 的简要描述。
description
string
value
Any
嵌入的字面量 example。 value 字段和 externalValue 字段是互斥的。无法使用 JSON 或 YAML 表示的媒体类型可以使用字符串值来表示。
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.
固定字段
字段名
Type
描述
operationRef
string
operationId
string
The name of an existing, resolvable OAS operation, as defined with a unique operationId. This field is mutually exclusive of the operationRef field.
parameters
requestBody
description
string
server
A server object to be used by the target 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
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
Source Location
example expression
notes
HTTP Method
$method
The allowable values for the $method will be those for the HTTP operation.
Requested media type
$request.header.accept
Request parameter
$request.path.id
Request parameters MUST be declared in the parameters section of the parent operation or they cannot be evaluated. This includes request headers.
Request body property
$request.body#/user/uuid
In operations which accept payloads, references may be made to portions of the requestBody or the entire body.
Request URL
$url
Response value
$response.body#/status
In operations which return payloads, references may be made to portions of the response body or the entire body.
Response header
$response.header.Server
Single header values only are available
Runtime expressions preserve the type of the referenced value. Expressions can be embedded into string values by surrounding the expression with {} curly braces.
Header 对象
name 不能被指定,它在相应的 headers 映射中被指定。
in 不能被指定,它隐含在 header 中。
Header 对象示例
一个类型为 integer 的简单 header:
{
"description": "The number of allowed requests in the current period",
"schema": {
"type": "integer"
}
}
description: The number of allowed requests in the current period
schema:
type: integer
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
Reference 对象
一个允许引用规范内部的其他部分或外部规范的对象。
For this specification, reference resolution is accomplished as defined by the JSON Reference specification and not by the JSON Schema specification.