OpenAPI Specification 2.0

来源:互联网 发布:李雨桐和薛之谦 知乎 编辑:程序博客网 时间:2024/04/30 09:54

OpenAPI规范

OpenAPI的前身是swagger规范。Swagger是一套有助于前后端分离,接口管理和测试工具集。

注:本文由wjc133翻译并发布,转载请注明作者和原出处,感谢。
http://blog.csdn.net/wjc133/article/details/65436778

本人英语水平有限,本文仅做参考就好~

2.0版

文中所使用到的”MUST”,”MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”和”OPTIONAL”均遵循RFC 2119定义。

Swagger specification基于the Apache License, Version 2.0协议发布。

简介

SwaggerTM是一个用于描述和文档化RESTful接口的项目。
Swagger规范定义了一系列的文件,用以描述API。这些文件可以被Swagger-UI项目用于展示API,也可以被Swagger-Codegen项目用于生成代码。一些其他的工具也可以利用这些文件,例如测试工具。

历史版本

版本 发行日期 说明 2.0 2014-09-08 Release of Swagger 2.0 1.2 2014-03-14 Initial release of the formal document. 1.1 2012-08-22 Release of Swagger 1.1 1.0 2011-08-10 First release of the Swagger Specification

定义

Path Templating

路径模板,是指用一对大括号{}来标记URL中可以被参数替换的部分。这个和我们在Spring程序中使用到的路径参数是一直的概念。
Mime Types
媒体类型,是遵循RFC 6838的。例如:

  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 Status Codes

HTTP状态码,遵循RFC 7231。

规范

格式

格式是遵循JSON格式的。YAML作为JSON的一个超集,也是被支持的。
有关于field,有两种:
第一种是fixed fields,是说field的名称是固定的;
第二种是Patterned fields,field的名字不是固定的,而是使用正则表达式匹配。

filed名称大小写敏感

文件结构

Swagger的规范要求将API用一个单一的文件表示。不过,定义可以拆成多个文件。使用$ref将他们拼合在一起。这符合JSON Schema规范。
按照惯例,Swagger规范文件命名为swagger.json

数据类型

Swagger Specification的原始数据类型给予JSON-Schema Draft 4。模型使用Schema Object描述。

有一个额外添加的原始数据类型file,用于在参数对象或者响应对象中设置参数类型或者响应为一个文件。
原始类型有一个可选的属性format,Swagger使用了集中常见的格式来对数据类型做更细微的定义。然而,format属性是一个开放式的string类型的数据,可以填写任何支持的属性。格式可以是emailuuid,甚至可以是一些没有在规范中支持的属性。格式和数据类型并不一定要一致(文件除外),Swagger定义了如下格式:

名称 type format 说明 integer integer int32 signed 32 bits long integer int64 signed 64 bits float number float double number double string string byte string byte base64 encoded characters binary string binary any sequence of octets boolean boolean date string date As defined by full-date - RFC3339 dateTime string date-time As defined by date-time - RFC3339 password string password Used to hint UIs the input needs to be obscured.

约束

Swagger根元素

名称 类型 描述 swagger string 必填。值必须为“2.0” info Info对象 必填。提供有关于API的元数据。 host string host地址,域名或者是ip。可以包含端口,但不得包含其他路径 basePath string 必须以”/”开头,定义基础路径。不支持路径模板 schemes string数组 定义传输协议,必须从以下选择:http、https、ws、wss。如果不指定schemes,默认的scheme就是访问Swagger时访问的协议 consumes string数组 定义一系列可以被消费的MIME类型。 produces string数组 定义一系列可以被生产的MIME类型。 paths Paths对象 必填。可获得的paths和操作符。 definitions Definitions对象 持有通过操作生产和消费的数据类型 parameters Parameters Definitions对象 持有操作时使用的参数。 responses Responses Definitions对象 持有操作的结果。 securityDefinitions Security Definitions对象 安全策略 security Security Definitions对象数组 整体安全策略 tags Tag对象数组 标签 externalDocs External Documentation对象 添加外部文档

通配模式对象

通配模式 类型 描述 ^x- 任何类型 Swagger约束所允许的拓展。成员名必须x-开头,例如,x-internal-id。值可以为空、原始类型或者是一个数组或者一个对象。查看Vendor扩展来获取更加详细的信息

Info对象

提供API的元数据信息。

固定字段

Field Name Type Description title string Required. 应用名 description string 应用简介。GFM syntax can be used for rich text representation. termsOfService string API服务条款 contact Contact Object API作者联系方式 license License Object API遵循的协议 version string 版本号

通配对象

通配模式 类型 描述 ^x- 任何类型 Swagger约束所允许的拓展。成员名必须x-开头,例如,x-internal-id。值可以为空、原始类型或者是一个数组或者一个对象。查看Vendor扩展来获取更加详细的信息

Info对象示例:

{  "title": "Swagger Sample App",  "description": "This is a sample server Petstore server.",  "termsOfService": "http://swagger.io/terms/",  "contact": {    "name": "API Support",    "url": "http://www.swagger.io/support",    "email": "support@swagger.io"  },  "license": {    "name": "Apache 2.0",    "url": "http://www.apache.org/licenses/LICENSE-2.0.html"  },  "version": "1.0.1"}
title: Swagger Sample Appdescription: This is a sample server Petstore server.termsOfService: http://swagger.io/terms/contact:  name: API Support  url: http://www.swagger.io/support  email: support@swagger.iolicense:  name: Apache 2.0  url: http://www.apache.org/licenses/LICENSE-2.0.htmlversion: 1.0.1

Contact对象

API的作者信息。

固定字段

字段 类型 描述 name string 联系人或组织名称 url string 指向联系人信息的URL,必须为URL格式 email string 邮箱,必须符合email格式

通配对象

通配模式 类型 描述 ^x- 任何类型 Swagger约束所允许的拓展。成员名必须x-开头,例如,x-internal-id。值可以为空、原始类型或者是一个数组或者一个对象。查看Vendor扩展来获取更加详细的信息

举例:

{  "name": "API Support",  "url": "http://www.swagger.io/support",  "email": "support@swagger.io"}
name: API Supporturl: http://www.swagger.io/supportemail: support@swagger.io

许可证对象

固定字段

字段 类型 描述 name string 必填。 url string 指向联系人信息的URL,必须为URL格式

举例:

{  "name": "Apache 2.0",  "url": "http://www.apache.org/licenses/LICENSE-2.0.html"}
name: Apache 2.0url: http://www.apache.org/licenses/LICENSE-2.0.html

Paths对象

用于保存各个接口的相对路径。加上basePath就可以组成完整的URL了。Paths可以为空,详见ACL constraints。

字段:

字段 类型 描述 /{path} Path Item对象 单个接口的相对路径。路径必须以’/’开头。允许使用Path模板。 ^x- Any

举例:

{  "/pets": {    "get": {      "description": "Returns all pets from the system that the user has access to",      "produces": [        "application/json"      ],      "responses": {        "200": {          "description": "A list of pets.",          "schema": {            "type": "array",            "items": {              "$ref": "#/definitions/pet"            }          }        }      }    }  }}
/pets:  get:    description: Returns all pets from the system that the user has access to    produces:    - application/json    responses:      '200':        description: A list of pets.        schema:          type: array          items:            $ref: '#/definitions/pet'

Path Item对象

用于描述对于单一Path可以进行的操作。Path Item可以为空,这种情况下,路径仍然会暴露在文档查看器,但是用户并不知道可以进行哪些操作和参数。

字段

字段 类型 描述 $ref string 允许从外部引入一个配置。被引用的结构必须符合Path Item对象的结构。如果说引用于当前项配置冲突,则behavior为undifined。 get Operation对象 此路径上的GET操作定义 post Operation对象 此路径上POST操作的定义 put Operation对象 此路径上PUT操作的定义 delete Operation对象 此路径上DELETE操作的定义 options Operation对象 此路径上OPTIONS操作的定义 head Operation对象 此路径上HEAD操作的定义 patch Operation对象 此路径上PATCH操作的定义 parameters [Parameter对象数组] 参数定义

举例

以下只提供json举例,需要yaml可到官网。

{  "get": {    "description": "Returns pets based on ID",    "summary": "Find pets by ID",    "operationId": "getPetsById",    "produces": [      "application/json",      "text/html"    ],    "responses": {      "200": {        "description": "pet response",        "schema": {          "type": "array",          "items": {            "$ref": "#/definitions/Pet"          }        }      },      "default": {        "description": "error payload",        "schema": {          "$ref": "#/definitions/ErrorModel"        }      }    }  },  "parameters": [    {      "name": "id",      "in": "path",      "description": "ID of pet to use",      "required": true,      "type": "array",      "items": {        "type": "string"      },      "collectionFormat": "csv"    }  ]}

Operation对象

用于描述路径上的单一一个API操作。

固定字段

字段 类型 描述 tags [string] 为了方便API文档控制,可以为Operation对象添加标签。标签可以用于逻辑分组。 summary string 简述操作。该字段应该少于120字符。 description string 详细的描述。可以使用GFM格式。 externalDocs 外部文档对象 为操作添加一个额外的外部文档。 operationId string 当前操作对象的ID,该ID必须在整个文档中唯一。工具和库可能使用该ID来唯一标识一个操作,因此建议遵循通用的编程命名约定。 consumes [string] 可以被消费的MIME类型列表。该值会覆盖Swagger对象的consumes值。使用空值可以清除全局配置。值必须是Mime Type中提到的值。 produces [string] 可以被生产的MIME类型列表。该值会覆盖Swagger对象的consumes值。使用空值可以清除全局配置。值必须是Mime Type中提到的值。 parameters [Parameter对象数组] 参数定义 responses Response对象 必填。执行此操作后可能的一个返回值列表。 schemes [string] 该操作的传输协议。必须为:httphttpswswss中的一个。该值会覆盖Swagger对象的schemes值。 deprecated boolean 声明当前操作已被弃用。已声明操作的用法应该被保留。默认值为false security Security Requirement对象 声明当前操作的安全方案。该值的列表描述可以使用的其他安全方案(也就是说,逻辑的或者在安全要求中的)。该定义也会覆盖顶级的security配置。

举例

{  "tags": [    "pet"  ],  "summary": "Updates a pet in the store with form data",  "description": "",  "operationId": "updatePetWithForm",  "consumes": [    "application/x-www-form-urlencoded"  ],  "produces": [    "application/json",    "application/xml"  ],  "parameters": [    {      "name": "petId",      "in": "path",      "description": "ID of pet that needs to be updated",      "required": true,      "type": "string"    },    {      "name": "name",      "in": "formData",      "description": "Updated name of the pet",      "required": false,      "type": "string"    },    {      "name": "status",      "in": "formData",      "description": "Updated status of the pet",      "required": false,      "type": "string"    }  ],  "responses": {    "200": {      "description": "Pet updated."    },    "405": {      "description": "Invalid input"    }  },  "security": [    {      "petstore_auth": [        "write:pets",        "read:pets"      ]    }  ]}

外部文档对象(External Documentation Object)

允许从外部资源引用扩展文档。

字段

字段 类型 描述 description string 目标文档的简要描述。可以使用GFM语法。 url string 必填。目标文档的URL。必须符合URL格式。

举例

{  "description": "Find more info here",  "url": "https://swagger.io"}

Parameter对象

用于描述单一操作的属性。
一个唯一的属性将通过name和location定位。

有五种可能的参数类型:

  • Path - 和路径模板一起使用,也就是说参数本身是路径的一部分。相对路径。例如:/items/{itemId}中,itemId为参数。
  • Query - 添加在URL上的查询参数。例如:/items?id=###中,查询参数为id
  • Header - 自定义的请求头参数。
  • Body - 附加到HTTP请求的payload。因为一个请求只能有一个payload,所以也只能有一个Body参数。body参数的名称本身并没有什么影响。考虑到Form本身也是一种Body,所以对于同一个操作,Form和Body不能共存。
  • Form - 当请求的contentType为application/x-www-form-urlencoded或者application/form-data或者两者都有时(consumes所描述的媒体类型),用于描述附加在HTTP请求上的payload。这是唯一的一种可以用来上传文件的参数类型。Form参数基于不同的content-type有不同的格式:

application/x-www-form-urlencoded - 与Query参数格式相似,但是却是一个payload。例如:foo=1&bar=swagger中,foo和bar都是表单参数。这种格式通常用于简单参数的传输。
multipart/form-data - 每个参数使用一个内部的header单独占一段。例如:Content-Disposition: form-data; name="submit-name",参数的名字是submit-name。这种类型的表单多用于文件传输。

字段

字段 类型 说明 name string 必填。参数名,大小写敏感。 in string 必填。参数的位置,可能的值有:queryheaderpathformDatabody。 description string 参数的简述。支持GFM required boolean 参数是否必填。如果说in的值为path,那么required值必须为true。

如果in的值为body

字段 类型 说明 schema Schema对象 必填。Schema对象定义了body参数的类型。

如果in是body以外其他的类型:

字段 类型 说明 type string 必填。参数类型。”string”, “number”, “integer”, “boolean”, “array” or “file”. 由于参数不在请求体,所以都是简单类型。consumes必须为multipart/form-data或者application/x-www-form-urlencoded或者两者皆有。参数的in值必须为formData。 format string 前面提到的type的扩展格式。详情参照Data Type Formats。 allowEmptyValue boolean 仅对queryformData有效。用于指定参数是否可以为空。 items Items对象 如果type是array,则必填。用于描述array里面的item collectionFormat string 决定array的格式。可能的值如下:csv-逗号分隔;ssv-空格分隔;tsv'-tab分隔;pipes`-管道分隔。 default * 用于声明当没有给出参数值时服务器所使用的默认值。例如在请求中没有给出每页的条目数,则默认值可能是100。(注意:默认值对必填参数无意义)。 maximum number See exclusiveMaximum boolean See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2. minimum number See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3. exclusiveMinimum boolean See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3. maxLength integer See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1. minLength integer See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2. pattern string See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3. maxItems integer See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2. minItems integer See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3. uniqueItems boolean See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4. enum [*] See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1. multipleOf number See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1.

举例

Body参数

下面是一个带引用的Body参数:

{  "name": "user",  "in": "body",  "description": "user to add to the system",  "required": true,  "schema": {    "$ref": "#/definitions/User"  }}

下面是一个参数为string array的body参数:

{  "name": "user",  "in": "body",  "description": "user to add to the system",  "required": true,  "schema": {    "type": "array",    "items": {      "type": "string"    }  }}

其他参数类型
一个64位整数Header参数:

{  "name": "token",  "in": "header",  "description": "token to be passed as a header",  "required": true,  "type": "array",  "items": {    "type": "integer",    "format": "int64"  },  "collectionFormat": "csv"}

一个string类型的路径参数:

{  "name": "username",  "in": "path",  "description": "username to fetch",  "required": true,  "type": "string"}

一个可选的查询参数,string类型,可通过重复给出该查询参数接收多个值。

{  "name": "id",  "in": "query",  "description": "ID of the object to fetch",  "required": false,  "type": "array",  "items": {    "type": "string"  },  "collectionFormat": "multi"}

一个带有文件类型的表单数据,用于上传:

{  "name": "avatar",  "in": "formData",  "description": "The avatar of the user",  "required": true,  "type": "file"}

Items对象

是一个JSON-Schema的items对象的自己。被用于in不为body的参数的声明。

字段

字段 类型 说明 type string 必填。参数类型。”string”, “number”, “integer”, “boolean”, “array” or “file”. 由于参数不在请求体,所以都是简单类型。consumes必须为multipart/form-data或者application/x-www-form-urlencoded或者两者皆有。参数的in值必须为formData。 format string 前面提到的type的扩展格式。详情参照Data Type Formats。 collectionFormat string 决定array的格式。可能的值如下:csv-逗号分隔;ssv-空格分隔;tsv'-tab分隔;pipes`-管道分隔。 default * 用于声明当没有给出参数值时服务器所使用的默认值。例如在请求中没有给出每页的条目数,则默认值可能是100。(注意:默认值对必填参数无意义)。 maximum number See exclusiveMaximum boolean See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2. minimum number See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3. exclusiveMinimum boolean See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3. maxLength integer See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1. minLength integer See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2. pattern string See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3. maxItems integer See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2. minItems integer See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3. uniqueItems boolean See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4. enum [*] See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1. multipleOf number See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1.

举例

Items是至少有两个字符的string。

{    "type": "string",    "minLength": 2}

一个数组的数组,内部数组是一个integer数组,数值要在0-63之间。

{    "type": "array",    "items": {        "type": "integer",        "minimum": 0,        "maximum": 63    }}

Responses对象

操作预期结果的容器。该容器将HTTP响应码映射到预期响应。你不必在文档中覆盖所有可能的HTTP响应代码,因为它们可能事先是不可预知的。然而,文档应该包含成功操作的响应以及各种已知的错误。

default可以用于所有没有被单独提出的HTTP状态码。
Responses Object必须包含至少一个响应码,而且应该是成功操作后的响应。

字段 类型 说明 default Response对象 引用对象 {HTTP Status Code} Response对象 引用对象

举例

{  "200": {    "description": "a pet to be returned",    "schema": {      "$ref": "#/definitions/Pet"    }  },  "default": {    "description": "Unexpected error",    "schema": {      "$ref": "#/definitions/ErrorModel"    }  }}

Response对象

用于描述单一一个响应。

字段 类型 说明 description string 必填。简述响应值。支持GFM。 schema Schema对象 用于定义response的结构。可以是简单类型、数组或者对象。如果field不存在,这意味着没有内容作为响应的一部分被返回。作为Schema对象的一个扩展,其root type值也可以是file。这应该取决于produces定义的mine-type。 headers Headers对象 response携带的header列表 examples Example对象 示例对象

举例

响应是复杂类型的数组:

{  "description": "A complex object array response",  "schema": {    "type": "array",    "items": {      "$ref": "#/definitions/VeryComplexType"    }  }}

string类型的响应:

{  "description": "A simple string response",  "schema": {    "type": "string"  }}

带有Header的响应:

{  "description": "A simple string response",  "schema": {    "type": "string"  },  "headers": {    "X-Rate-Limit-Limit": {      "description": "The number of allowed requests in the current period",      "type": "integer"    },    "X-Rate-Limit-Remaining": {      "description": "The number of remaining requests in the current period",      "type": "integer"    },    "X-Rate-Limit-Reset": {      "description": "The number of seconds left in the current period",      "type": "integer"    }  }}

没有返回值的Response:

{  "description": "object created"}

Headers对象

字段 类型 说明 {name} Header对象 name代表的是Header的名称。值为Header的描述。

Header对象举例

{    "X-Rate-Limit-Limit": {        "description": "The number of allowed requests in the current period",        "type": "integer"    },    "X-Rate-Limit-Remaining": {        "description": "The number of remaining requests in the current period",        "type": "integer"    },    "X-Rate-Limit-Reset": {        "description": "The number of seconds left in the current period",        "type": "integer"    }}

Example对象

字段 类型 说明 {mime type} Any name代表的是返回值的mine-type,必须是produces值中的一个。值为示例。

举例

{  "application/json": {    "name": "Puma",    "type": "Dog",    "color": "Black",    "gender": "Female",    "breed": "Mixed"  }}

Header对象

字段 类型 说明 description string 简述 type string 必填。”string”, “number”, “integer”, “boolean”, or “array”. format string 对type的格式的拓展描述。详情见Data Type Format items Items对象 如果type是array,则必填。用于描述array里面的item collectionFormat string 决定array的格式。可能的值如下:csv-逗号分隔;ssv-空格分隔;tsv'-tab分隔;pipes`-管道分隔。 default * 用于声明当没有给出参数值时服务器所使用的默认值。例如在请求中没有给出每页的条目数,则默认值可能是100。(注意:默认值对必填参数无意义)。 maximum number See exclusiveMaximum boolean See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2. minimum number See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3. exclusiveMinimum boolean See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3. maxLength integer See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1. minLength integer See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2. pattern string See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3. maxItems integer See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2. minItems integer See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3. uniqueItems boolean See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4. enum [*] See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1. multipleOf number See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1.

举例

一个integer类型的头部:

{  "description": "The number of allowed requests in the current period",  "type": "integer"}

Tag对象

一般被用于Operation对象。

字段 类型 说明 name string 必填。标签名 description string 简述,支持GFM externalDocs External Documention 对象 拓展文档
{    "name": "pet",    "description": "Pets operations"}

Reference对象

一个简单的对象,允许在规范中引用其他定义。它可以用来引用在顶层定义的参数和响应以供重用。
引用对象是使用JSON Pointer作为值的JSON Reference对象。

字段

字段 类型 说明 $ref string 必填

举例

{    "$ref": "#/definitions/Pet"}

相对文件路径

{  "$ref": "Pet.json"}

嵌入型示例:

{  "$ref": "definitions.json#/Pet"}

Schema对象

Schema对象用于定义数据类型的输入和输出。这里说的数据类型可以是对象,但也可以是原始类型或者数组。该对象的定义是基于JSON Schema Specification Draft 4的,并且使用了一个预定义的子集。在这个子集的顶部,有本规范提供的扩展,以允许更完整的文档。
除非另有说明,属性定义遵循这里所引用的JSON模式规范。

以下属性直接取自JSON架构定义并遵循相同的规范:

  • $ref - As a JSON Reference
  • format (See Data Type Formats for further details)
  • title
  • description (GFM syntax can be used for rich text representation)
  • default (Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object)
  • multipleOf
  • maximum
  • exclusiveMaximum
  • minimum
  • exclusiveMinimum
  • maxLength
  • minLength
  • pattern
  • maxItems
  • minItems
  • uniqueItems
  • maxProperties
  • minProperties
  • required
  • enum
  • type

以下属性取自JSON Schema的定义,但是这些定义被调整到了Swagger规范。他们的定义与JSON Schema是一样的,只有原始定义吸引用JSON Schema定义时,才使用Schema对象的定义。

  • items
  • allOf
  • properties
  • additionalProperties

除了JSON Schema的子集字段外,下列字段可用于进一步完善Shcema文档。

字段 类型 说明 discriminator string 用于支持多态。 readOnly boolean 仅与Schema的”properties”定义有关。声明属性为“只读”。这意味着该值只能被当做响应值,不能参与到请求中去。readOnlytrue的属性不应该required列表中。默认值为false。 xml XML对象 仅用于properties schemas。对于root schemas无效。 externalDocs 外部文档 example Any 包含此schema实例的自由格式示例。

组合与继承(多态)

Swagger允许组合或者继承模型定义,通过使用allOf属性。以此来提供有效的模型组合。allOf在对象定义数组中独立验证,但是一起组成一个单一的对象。
虽然组成提供模型的可扩展性,它并不意味着模型之间的层次结构。为了支持多态的特性,Swagger添加了discriminator字段。使用时discriminator要配成属性的名称,用以决定到底是使用哪一个schema definition来验证模型的结构。因此,discriminator字段必须为必填字段。

举例

原始类型
不同于之前版本的Swagger,Schema定义可以用于描述原始类型和数组。

{    "type": "string",    "format": "email"}

简单模型

{  "type": "object",  "required": [    "name"  ],  "properties": {    "name": {      "type": "string"    },    "address": {      "$ref": "#/definitions/Address"    },    "age": {      "type": "integer",      "format": "int32",      "minimum": 0    }  }}

带有Map/字典的属性

这是简单的string to string 映射。

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

这是复杂些的string to object 映射。

{  "type": "object",  "additionalProperties": {    "$ref": "#/definitions/ComplexModel"  }}

带有示例的模型:

{  "type": "object",  "properties": {    "id": {      "type": "integer",      "format": "int64"    },    "name": {      "type": "string"    }  },  "required": [    "name"  ],  "example": {    "name": "Puma",    "id": 1  }}

利用组合的模型:

{  "definitions": {    "ErrorModel": {      "type": "object",      "required": [        "message",        "code"      ],      "properties": {        "message": {          "type": "string"        },        "code": {          "type": "integer",          "minimum": 100,          "maximum": 600        }      }    },    "ExtendedErrorModel": {      "allOf": [        {          "$ref": "#/definitions/ErrorModel"        },        {          "type": "object",          "required": [            "rootCause"          ],          "properties": {            "rootCause": {              "type": "string"            }          }        }      ]    }  }}

ExtendedErrorModel继承或者说组合了ErrorModel。

启用了多态性的模型:

{  "definitions": {    "Pet": {      "type": "object",      "discriminator": "petType",      "properties": {        "name": {          "type": "string"        },        "petType": {          "type": "string"        }      },      "required": [        "name",        "petType"      ]    },    "Cat": {      "description": "A representation of a cat",      "allOf": [        {          "$ref": "#/definitions/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",      "allOf": [        {          "$ref": "#/definitions/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"          ]        }      ]    }  }}

XML对象

感觉用到不多,需要时再补充吧。

Definitions对象

持有一个操作可以消费或者生产的数据类型。数据类型可以是原始类型、数组或者对象。

字段 类型 说明 {name} Schema对象 一个单一的定义,用于将名字映射到schema定义。

举例

{  "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 Definitions Object)

一个对象,用于在操作中重用参数。参数定义可以参照这里定义的。

字段 类型 说明 {name} Parameter对象 一个单一的定义,用于将名字映射到Parameter定义。

举例

{  "skipParam": {    "name": "skip",    "in": "query",    "description": "number of items to skip",    "required": true,    "type": "integer",    "format": "int32"  },  "limitParam": {    "name": "limit",    "in": "query",    "description": "max records to return",    "required": true,    "type": "integer",    "format": "int32"  }}

响应定义对象(Responses Definitions Object)

一个持有可重用Responses的对象。

字段 类型 说明 {name} Response对象 一个单一的定义,用于将名字映射到Response定义。

举例

{  "NotFound": {    "description": "Entity not found."  },  "IllegalInput": {    "description": "Illegal input for operation."  },  "GeneralError": {    "description": "General Error",    "schema": {        "$ref": "#/definitions/GeneralError"    }  }}

安全定义对象(Security Definitions Object)

定义可重用的Security Schema,但并不是全局安全定义。

字段 类型 说明 {name} Security Scheme对象 一个单一的定义,用于将名字映射到Security Scheme定义。

举例

{  "api_key": {    "type": "apiKey",    "name": "api_key",    "in": "header"  },  "petstore_auth": {    "type": "oauth2",    "authorizationUrl": "http://swagger.io/api/oauth/dialog",    "flow": "implicit",    "scopes": {      "write:pets": "modify pets in your account",      "read:pets": "read your pets"    }  }}

安全Scheme对象(Security Secheme Object)

定义安全Scheme,用于操作对象。支持基本的认证,API key(Header或者Query参数)和Oauth2公共流(隐含、密码、应用和访问码)。

字段 类型 有效性(Validity) 说明 type string Any 必填。安全策略的类型:basicapiKey或者oauth2。 description string Any 一段简短的描述。 name string apiKey 必填。apiKey的名字。用于在header或者Query参数中查找。 in string apiKey 必填。API key的位置,query或者header。 flow string oauth2 必填implicitpasswordapplication或者accessCode。 authorizationUrl string oauth2(“implicit”, “accessCode”) 必填。验证URL tokenUrl string oauth2(“password”,”application”,”accessCode”) 必填。token URL scopes Scopes对象 oauth2 必填。Oauth2安全方案的适用范围。

举例

基础验证

{  "type": "basic"}

API Key

{  "type": "apiKey",  "name": "api_key",  "in": "header"}

Implicit OAuth2

{  "type": "oauth2",  "authorizationUrl": "http://swagger.io/api/oauth/dialog",  "flow": "implicit",  "scopes": {    "write:pets": "modify pets in your account",    "read:pets": "read your pets"  }}

Scopes对象

用于列出OAuth2的适用范围。

字段 类型 说明 {name} string scope的名称(key)映射到简介(value)

举例

{  "write:pets": "modify pets in your account",  "read:pets": "read your pets"}

安全需求对象(Security Requirement Object)

用于列出执行操作所需要的安全方案。

字段 类型 说明 {name} string 每一个name都必须是在Security声明中定义过的。如果security scheme是oauth2类型的,则值为scope names的列表。对于其他的security scheme类型,该数组值必须为空。

举例

非OAuth2类型:

{    "api_key": []}

OAuth2类型安全需求:

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

对规范的扩展

尽管Swagger规范努力的容纳了所有的用例,但是仍可能会有一些需要拓展的点。我们可以通过添加额外的舒俱来拓展现有的规范。
所有的拓展属性均以x-开头,并且可以是任何有效的JSON格式的值。
这些拓展的值可能也可能不能被现有的工具所支持,但是他们可以被拓展,以支持请求。(如果他们是开源或者内部工具)

Security拦截

Swagger规范中的一些对象可能被声明了但是却被留空,或者已经彻底移除了,尽管在本质上它们还属于API文档的核心。
其背后的原因是允许文档本身附带有一个额外的访问控制层。虽然不是规范本身的一部分,但某些库可以选择允许基于某种形式的认证/授权访问文档的部分。

下面有两个例子:

  1. Paths对象可以为空。这可能是违反直觉的,但是这样可以告诉viewer它们到了正确的地方,但是不会在文档中访问。它们仍然可以访问Info对象,因为其中可能包含有关身份验证的其他信息。
  2. Path Item对象可以为空。在这种情况下,viewer将感知到路径存在,但是不能进行看到任何操作或参数。这不同于直接在Paths对象中隐藏路径,这样用户不会感知到它的存在。这使文档提供者可以控制最终看见的部分。
0 0
原创粉丝点击