OpenAPI Specification 2.0

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.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

定义

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定义了如下格式:

名称typeformat说明
integerintegerint32signed 32 bits
longintegerint64signed 64 bits
floatnumberfloat
doublenumberdouble
stringstring
bytestringbytebase64 encoded characters
binarystringbinaryany sequence of octets
booleanboolean
datestringdateAs defined by full-date - RFC3339
dateTimestringdate-timeAs defined by date-time - RFC3339
passwordstringpasswordUsed to hint UIs the input needs to be obscured.

约束

Swagger根元素
名称类型描述
swaggerstring必填。值必须为“2.0”
infoInfo对象必填。提供有关于API的元数据。
hoststringhost地址,域名或者是ip。可以包含端口,但不得包含其他路径
basePathstring必须以”/”开头,定义基础路径。不支持路径模板
schemesstring数组定义传输协议,必须从以下选择:http、https、ws、wss。如果不指定schemes,默认的scheme就是访问Swagger时访问的协议
consumesstring数组定义一系列可以被消费的MIME类型。
producesstring数组定义一系列可以被生产的MIME类型。
pathsPaths对象必填。可获得的paths和操作符。
definitionsDefinitions对象持有通过操作生产和消费的数据类型
parametersParameters Definitions对象持有操作时使用的参数。
responsesResponses Definitions对象持有操作的结果。
securityDefinitionsSecurity Definitions对象安全策略
securitySecurity Definitions对象数组整体安全策略
tagsTag对象数组标签
externalDocsExternal Documentation对象添加外部文档
通配模式对象
通配模式类型描述
^x-任何类型Swagger约束所允许的拓展。成员名必须x-开头,例如,x-internal-id。值可以为空、原始类型或者是一个数组或者一个对象。查看Vendor扩展来获取更加详细的信息

Info对象

提供API的元数据信息。

固定字段
Field NameTypeDescription
titlestringRequired. 应用名
descriptionstring应用简介。GFM syntax can be used for rich text representation.
termsOfServicestringAPI服务条款
contactContact ObjectAPI作者联系方式
licenseLicense ObjectAPI遵循的协议
versionstring版本号
通配对象
通配模式类型描述
^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 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

Contact对象

API的作者信息。

固定字段
字段类型描述
namestring联系人或组织名称
urlstring指向联系人信息的URL,必须为URL格式
emailstring邮箱,必须符合email格式
通配对象
通配模式类型描述
^x-任何类型Swagger约束所允许的拓展。成员名必须x-开头,例如,x-internal-id。值可以为空、原始类型或者是一个数组或者一个对象。查看Vendor扩展来获取更加详细的信息

举例:

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

许可证对象

固定字段
字段类型描述
namestring必填
urlstring指向联系人信息的URL,必须为URL格式

举例:

{
  "name": "Apache 2.0",
  "url": "http://www.apache.org/licenses/LICENSE-2.0.html"
}
name: Apache 2.0
url: 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可以为空,这种情况下,路径仍然会暴露在文档查看器,但是用户并不知道可以进行哪些操作和参数。

字段
字段类型描述
$refstring允许从外部引入一个配置。被引用的结构必须符合Path Item对象的结构。如果说引用于当前项配置冲突,则behavior为undifined。
getOperation对象此路径上的GET操作定义
postOperation对象此路径上POST操作的定义
putOperation对象此路径上PUT操作的定义
deleteOperation对象此路径上DELETE操作的定义
optionsOperation对象此路径上OPTIONS操作的定义
headOperation对象此路径上HEAD操作的定义
patchOperation对象此路径上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对象添加标签。标签可以用于逻辑分组。
summarystring简述操作。该字段应该少于120字符。
descriptionstring详细的描述。可以使用GFM格式
externalDocs外部文档对象为操作添加一个额外的外部文档。
operationIdstring当前操作对象的ID,该ID必须在整个文档中唯一。工具和库可能使用该ID来唯一标识一个操作,因此建议遵循通用的编程命名约定。
consumes[string]可以被消费的MIME类型列表。该值会覆盖Swagger对象的consumes值。使用空值可以清除全局配置。值必须是Mime Type中提到的值。
produces[string]可以被生产的MIME类型列表。该值会覆盖Swagger对象的consumes值。使用空值可以清除全局配置。值必须是Mime Type中提到的值。
parameters[Parameter对象数组]参数定义
responsesResponse对象必填。执行此操作后可能的一个返回值列表。
schemes[string]该操作的传输协议。必须为:httphttpswswss中的一个。该值会覆盖Swagger对象的schemes值。
deprecatedboolean声明当前操作已被弃用。已声明操作的用法应该被保留。默认值为false
securitySecurity 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)

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

字段
字段类型描述
descriptionstring目标文档的简要描述。可以使用GFM语法。
urlstring必填。目标文档的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。这种类型的表单多用于文件传输。

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

如果in的值为body

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

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

字段类型说明
typestring必填。参数类型。”string”, “number”, “integer”, “boolean”, “array” or “file”. 由于参数不在请求体,所以都是简单类型。consumes必须为multipart/form-data或者application/x-www-form-urlencoded或者两者皆有。参数的in值必须为formData
formatstring前面提到的type的扩展格式。详情参照Data Type Formats
allowEmptyValueboolean仅对queryformData有效。用于指定参数是否可以为空。
itemsItems对象如果type是array,则必填。用于描述array里面的item
collectionFormatstring决定array的格式。可能的值如下:csv-逗号分隔;ssv-空格分隔;tsv'-tab分隔;pipes`-管道分隔。
default*用于声明当没有给出参数值时服务器所使用的默认值。例如在请求中没有给出每页的条目数,则默认值可能是100。(注意:默认值对必填参数无意义)。
maximumnumberSee
exclusiveMaximumbooleanSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2.
minimumnumberSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.
exclusiveMinimumbooleanSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.
maxLengthintegerSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1.
minLengthintegerSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2.
patternstringSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3.
maxItemsintegerSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2.
minItemsintegerSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3.
uniqueItemsbooleanSee 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.
multipleOfnumberSee 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的参数的声明。

字段
字段类型说明
typestring必填。参数类型。”string”, “number”, “integer”, “boolean”, “array” or “file”. 由于参数不在请求体,所以都是简单类型。consumes必须为multipart/form-data或者application/x-www-form-urlencoded或者两者皆有。参数的in值必须为formData
formatstring前面提到的type的扩展格式。详情参照Data Type Formats
collectionFormatstring决定array的格式。可能的值如下:csv-逗号分隔;ssv-空格分隔;tsv'-tab分隔;pipes`-管道分隔。
default*用于声明当没有给出参数值时服务器所使用的默认值。例如在请求中没有给出每页的条目数,则默认值可能是100。(注意:默认值对必填参数无意义)。
maximumnumberSee
exclusiveMaximumbooleanSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2.
minimumnumberSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.
exclusiveMinimumbooleanSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.
maxLengthintegerSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1.
minLengthintegerSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2.
patternstringSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3.
maxItemsintegerSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2.
minItemsintegerSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3.
uniqueItemsbooleanSee 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.
multipleOfnumberSee 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必须包含至少一个响应码,而且应该是成功操作后的响应。

字段类型说明
defaultResponse对象引用对象
{HTTP Status Code}Response对象引用对象
举例
{
  "200": {
    "description": "a pet to be returned",
    "schema": {
      "$ref": "#/definitions/Pet"
    }
  },
  "default": {
    "description": "Unexpected error",
    "schema": {
      "$ref": "#/definitions/ErrorModel"
    }
  }
}

Response对象

用于描述单一一个响应。

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

响应是复杂类型的数组:

{
  "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}Anyname代表的是返回值的mine-type,必须是produces值中的一个。值为示例。
举例
{
  "application/json": {
    "name": "Puma",
    "type": "Dog",
    "color": "Black",
    "gender": "Female",
    "breed": "Mixed"
  }
}

Header对象

字段类型说明
descriptionstring简述
typestring必填。”string”, “number”, “integer”, “boolean”, or “array”.
formatstring对type的格式的拓展描述。详情见Data Type Format
itemsItems对象如果type是array,则必填。用于描述array里面的item
collectionFormatstring决定array的格式。可能的值如下:csv-逗号分隔;ssv-空格分隔;tsv'-tab分隔;pipes`-管道分隔。
default*用于声明当没有给出参数值时服务器所使用的默认值。例如在请求中没有给出每页的条目数,则默认值可能是100。(注意:默认值对必填参数无意义)。
maximumnumberSee
exclusiveMaximumbooleanSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2.
minimumnumberSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.
exclusiveMinimumbooleanSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.
maxLengthintegerSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1.
minLengthintegerSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2.
patternstringSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3.
maxItemsintegerSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2.
minItemsintegerSee https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3.
uniqueItemsbooleanSee 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.
multipleOfnumberSee 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对象。

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

Reference对象

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

字段
字段类型说明
$refstring必填
举例
{
    "$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文档。

字段类型说明
discriminatorstring用于支持多态。
readOnlyboolean仅与Schema的”properties”定义有关。声明属性为“只读”。这意味着该值只能被当做响应值,不能参与到请求中去。readOnlytrue的属性不应该required列表中。默认值为false
xmlXML对象仅用于properties schemas。对于root schemas无效。
externalDocs外部文档
exampleAny包含此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)说明
typestringAny必填。安全策略的类型:basicapiKey或者oauth2
descriptionstringAny一段简短的描述。
namestringapiKey必填。apiKey的名字。用于在header或者Query参数中查找。
instringapiKey必填。API key的位置,query或者header
flowstringoauth2必填implicitpasswordapplication或者accessCode
authorizationUrlstringoauth2(“implicit”, “accessCode”)必填。验证URL
tokenUrlstringoauth2(“password”,”application”,”accessCode”)必填。token URL
scopesScopes对象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}stringscope的名称(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对象中隐藏路径,这样用户不会感知到它的存在。这使文档提供者可以控制最终看见的部分。
  • 5
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值