介绍

OpenAPI 规范(OAS)定义了一个标准的、语言无关的 RESTful API 接口规范,它可以同时允许开发人员和操作系统查看并理解某个服务的功能,而无需访问源代码,文档或网络流量检查(既方便人类学习和阅读,也方便机器阅读)。正确定义 OAS 后,开发者可以使用最少的实现逻辑来理解远程服务并与之交互。

此外,文档生成工具可以使用 OpenAPI 规范来生成 API 文档,代码生成工具可以生成各种编程语言下的服务端和客户端代码,测试代码和其他用例。

文档:https://swagger.io/specification/
转自:https://www.cnblogs.com/yaohl0911/p/14567915.html

数据类型

type format Comments
integer int32 signed 32 bits
integer int64 signed 64 bits (a.k.a long)
number float
number double
string
string byte base64 encoded characters
string binary any sequence of octets
boolean
string date As defined by full-date - RFC3339
string date-time As defined by date-time - RFC3339
string password A hint to UIs to obscure input.

OpenAPI 根对象

  1. openapi: 3.0.0 # OpenAPI 规范版本号
  2. info: # API 元数据信息
  3. servers: # 服务器连接信息
  4. tags: # API 的分组标签
  5. paths: # 对所提供的 API 有效的路径和操作
  6. components: # 一个包含多种纲要的元素,可重复使用组件
  7. security: # 声明 API 使用的安全机制
  8. externalDocs: # 附加文档

Info 对象

Info 对象描述 API 的元数据信息。

  1. # API 元数据信息
  2. info:
  3. title: xx开放平台接口文档 # 应用的名称
  4. description: |
  5. 简短的描述信息,支持 markdown 语法。 | 表示换行,< 表示忽略换行。
  6. version: "1.0.0" # API 文档的版本信息
  7. termsOfService: 'http://swagger.io/terms/' # 指向服务条款的 URL 地址
  8. contact: # 所开放的 API 的联系人信息
  9. name: API Support # 人或组织的名称
  10. url: http://www.example.com/support # 指向联系人信息的 URL 地址
  11. email: apiteam@swagger.io # 人或组织的 email 地址
  12. license: # 所开放的 API 的证书信息。
  13. name: Apache 2.0
  14. url: 'http://www.apache.org/licenses/LICENSE-2.0.html'

Server 对象

Server 表示一个服务器的对象。这里通常填写测试服务器或者生产服务器的 IP 地址、端口版本号等信息(指定基本 URL)。

  1. servers:
  2. - url: https://development.gigantic-server.com/v1
  3. description: 开发服务器
  4. - url: https://staging.gigantic-server.com/v1
  5. description: 测试服务器
  6. - url: https://api.gigantic-server.com/v1
  7. description: 生产服务器

Tag 对象

Tag 对象用于对 path 对象中的 API 进行分组,可以更美观的生成文档。

  1. tags:
  2. - name: pet
  3. description: 与宠物相关的接口
  4. externalDocs:
  5. description: 外部文档
  6. url: 'http://swagger.io'
  7. - name: store
  8. description: 宠物商店
  9. - name: user
  10. description: 用户操作相关
  11. externalDocs:
  12. description: 外部文档
  13. url: 'http://swagger.io'

Components 对象

components 对象包含开放 API 规范规定的各种可重用组件。当没有被其他对象引用时,在这里定义的组件不会产生任何效果。

  1. # 一个包含多种纲要的元素,可重复使用组件
  2. components:
  3. schemas:
  4. responses:
  5. parameters:
  6. examples:
  7. requestBodies:
  8. headers:
  9. securitySchemes:
  10. links:
  11. callbacks:

Path 对象

定义各个端点和操作的相对路径。

  1. # 对所提供的 API 有效的路径和操作
  2. paths:
  3. /pet/{petId}:
  4. get:
  5. tags:
  6. - pet
  7. summary: 简要总结,描述此路径内包含的所有操作。
  8. description: 详细说明,用于描述此路径包含的所有操作。
  9. operationId: getPetById # 此操作的唯一标识符
  10. parameters: # 参数列表
  11. - name: petId
  12. in: path
  13. description: 路径参数,宠物 ID
  14. required: true
  15. schema:
  16. type: integer
  17. format: int64
  18. responses: # 接口响应内容
  19. '200':
  20. description: 操作成功
  21. content:
  22. application/json:
  23. schema:
  24. type: object
  25. properties:
  26. id:
  27. type: integer
  28. format: int64
  29. category:
  30. type: object
  31. properties:
  32. id:
  33. type: integer
  34. format: int64
  35. name:
  36. type: string
  37. name:
  38. type: string
  39. example: doggie
  40. photoUrls:
  41. type: array
  42. items:
  43. type: string
  44. tags:
  45. type: array
  46. items:
  47. type: object
  48. properties:
  49. id:
  50. type: integer
  51. format: int64
  52. name:
  53. type: string
  54. status:
  55. type: string
  56. description: 宠物在商店的状态
  57. enum:
  58. - available
  59. - pending
  60. - sold
  61. '400':
  62. description: 无效的 id
  63. '404':
  64. description: 找不到指定的资源
  65. security: # 作用于此操作的安全机制
  66. - api_key: [] # 可以声明一个空数组来变相的移除顶层的安全声明

image.png
返回的 Pet 对象详解
使用 components 对象进行优,通过 components 对象封装可重用对象,然后通过 $ref 标签进行引用:

  1. # 对所提供的 API 有效的路径和操作
  2. paths:
  3. '/pet/{petId}':
  4. get:
  5. tags:
  6. - pet
  7. summary: 简要总结,描述此路径内包含的所有操作
  8. description: 详细说明,用于描述此路径包含的所有操作
  9. operationId: getPetById # 此操作的唯一标识符
  10. parameters: # 参数列表
  11. - name: petId
  12. in: path
  13. description: pet ID
  14. required: true
  15. schema:
  16. type: integer
  17. format: int64
  18. responses: # 响应列表
  19. '200':
  20. description: 操作成功
  21. content:
  22. application/json:
  23. schema:
  24. $ref: '#/components/schemas/Pet'
  25. '400':
  26. description: 无效的 id
  27. '404':
  28. description: 找不到指定的资源
  29. security: # 作用于此操作的安全机制
  30. - api_key: [] # 可以声明一个空数组来变相的移除顶层的安全声明
  31. components:
  32. schemas:
  33. Category:
  34. type: object
  35. properties:
  36. id:
  37. type: integer
  38. format: int64
  39. name:
  40. type: string
  41. Tag:
  42. type: object
  43. properties:
  44. id:
  45. type: integer
  46. format: int64
  47. name:
  48. type: string
  49. Pet:
  50. type: object
  51. properties:
  52. id:
  53. type: integer
  54. format: int64
  55. category:
  56. $ref: '#/components/schemas/Category'
  57. name:
  58. type: string
  59. example: doggie
  60. photoUrls:
  61. type: array
  62. items:
  63. type: string
  64. tags:
  65. type: array
  66. items:
  67. $ref: '#/components/schemas/Tag'
  68. status:
  69. type: string
  70. description: 宠物在商店的状态
  71. enum:
  72. - available
  73. - pending
  74. - sold

Parameter 参数对象

参数位置(in)的值:

参数位置 描述 示例
path 参数的值是 URL 操作路径的一部分 /items/{itemId},路径参数是{itemId}
query 追加在 URL 地址之后的参数 /items?id=###,查询参数是 id
header 请求中使用的自定义请求头
cookie 用于传递特定的 cookie 值
  1. ###########一个值数组,数组元素为 64 位整数值的请求头参数:##########
  2. name: token
  3. in: header
  4. description: 需要作为 HTTP header 请求头传递的 token 参数
  5. required: true
  6. schema:
  7. type: array
  8. items:
  9. type: integer
  10. format: int64
  11. style: simple
  12. ###########路径 /pet/{petId} 下的 petId 路径参数:##########
  13. parameters: # 参数列表(以“数组”格式描述参数)
  14. - name: petId # 参数名称
  15. in: path # 参数的位置 path/query/header/cookie
  16. description: URL 路径参数,宠物 ID
  17. required: true # 是否是必选参数,path 路径下的参数必须为 true。
  18. deprecated: false # 参数是否被弃用
  19. allowEmptyValue: false # 是否允许传递空参数,仅在路径为 query 下有效。
  20. schema: # 描述参数的结构
  21. type: integer
  22. format: int64
  23. example: 123456
  24. ###########一个值类型为字符串的路径参数:###########
  25. parameters: # 参数列表(以“数组”格式描述参数)
  26. - name: username # 一个值类型为字符串的路径参数
  27. in: path
  28. description: URL 路径参数,用户名。
  29. required: true
  30. schema:
  31. type: string
  32. pattern: "[a-z0-9]{8,64}" # 正则表达式
  33. minLength: 8 # 字符串的最小长度
  34. maxLength: 64 # 字符串的最大长度
  35. ###########一个值类型为字符串的可选查询参数,允许通过通过重复参数来传递多个值:###########
  36. parameters: # 参数列表
  37. - name: id
  38. in: query
  39. description: 通过 id 查询对象。
  40. required: false # 可选的查询参数
  41. schema: # schema - 参数的结构
  42. type: array
  43. items: # 只有 array 类型才有items项,描述数组项的数据类型
  44. type: string
  45. style: form # style - 描述如何序列化参数?
  46. explode: true # 生成带分隔符的参数值
  47. ###########URL 请求路径中添加查询参数,实现分页输出:###########
  48. #GET https://example.com/v1/resources?pageSize=10&pageNumber=1
  49. parameters:
  50. - name: pageSize
  51. in: query
  52. description: 每页返回的数量
  53. type: integer
  54. format: int32
  55. minimum: 0 # 最小值
  56. exclusiveMinimum: true # 数值必须 > 最小值
  57. maximum: 100 # 最大值
  58. exclusiveMaximum: false # 数值必须 < 最大值
  59. multipleOf: 10 # 数值必须是 multipleOf 的整数倍
  60. - name: pageNumber
  61. in: query
  62. description: 当前页码
  63. type: integer
  64. ###########使用内容定义序列化的复杂参数###########
  65. in: query
  66. name: coordinates
  67. content:
  68. application/json:
  69. schema:
  70. type: object
  71. required:
  72. - lat
  73. - long
  74. properties:
  75. lat:
  76. type: number
  77. long:
  78. type: number

Request Body 请求体对象

定义请求体。

  1. paths:
  2. /pet:
  3. post:
  4. tags:
  5. - pet
  6. summary: 向商店中添加新的宠物
  7. operationId: addPet
  8. responses:
  9. '405':
  10. description: 非法的操作
  11. requestBody: # 请求体
  12. description: 需要被添加进商店的 Pet 对象
  13. required: true # 请求体是否被包含在请求中,默认值 false
  14. content: # 请求体的内容
  15. application/json:
  16. schema:
  17. $ref: '#/components/schemas/Pet'

为了方便重用,requestBody 的内容也可以放到 components 对象的 requestBodies 中:

  1. # 对所提供的 API 有效的路径和操作
  2. paths:
  3. /pet:
  4. post:
  5. tags:
  6. - pet
  7. summary: 向商店中添加新的宠物
  8. operationId: addPet
  9. responses:
  10. '405':
  11. description: 非法的操作
  12. requestBody: # 请求体
  13. $ref: '#/components/requestBodies/Pet'
  14. components:
  15. schemas:
  16. Category:
  17. type: object
  18. properties:
  19. id:
  20. type: integer
  21. format: int64
  22. name:
  23. type: string
  24. Tag:
  25. type: object
  26. properties:
  27. id:
  28. type: integer
  29. format: int64
  30. name:
  31. type: string
  32. Pet:
  33. type: object
  34. required: # 必填字段
  35. - name
  36. - photoUrls
  37. properties:
  38. id:
  39. type: integer
  40. format: int64
  41. category:
  42. $ref: '#/components/schemas/Category'
  43. name:
  44. type: string
  45. example: doggie
  46. photoUrls:
  47. type: array
  48. items:
  49. type: string
  50. tags:
  51. type: array
  52. items:
  53. $ref: '#/components/schemas/Tag'
  54. status:
  55. type: string
  56. description: 宠物在商店的状态
  57. enum:
  58. - available
  59. - pending
  60. - sold
  61. requestBodies:
  62. Pet:
  63. description: 需要被添加进商店的 Pet 对象
  64. required: true # 请求体是否被包含在请求中,默认值 false
  65. content: # 请求体的内容
  66. application/json:
  67. schema:
  68. $ref: '#/components/schemas/Pet'

Media Type 类型

文件上传和下载
  1. # 使用 base64 编码传输的内容
  2. schema:
  3. type: string
  4. format: base64
  5. # 以二进制(octet-stream,八位字节流)传输的内容
  6. schema:
  7. type: string
  8. format: binary

一个使用 POST 操作提交文件的 requestBody 看起来像下面这样:

  1. requestBody:
  2. content:
  3. application/octet-stream:
  4. # any media type is accepted, functionally equivalent to `*/*`
  5. # 任何媒体类型都被接受,功能上等同于 `* / *`
  6. schema:
  7. # a binary file of any type
  8. # 任何类型的二进制文件
  9. type: string
  10. format: binary

此外,可以指定明确的媒体类型:

  1. # 可以指定多个特定媒体类型
  2. requestBody:
  3. content:
  4. # png 或 jpeg 类型的二进制文件
  5. 'image/jpeg':
  6. schema:
  7. type: string
  8. format: binary
  9. 'image/png':
  10. schema:
  11. type: string
  12. format: binary

为了同时上传多个文件,必须指定 multipart 媒体类型。

  1. requestBody:
  2. content:
  3. multipart/form-data:
  4. schema:
  5. properties:
  6. # 属性名称 'file' 将用于所有文件
  7. file:
  8. type: array
  9. items:
  10. type: string
  11. format: binary

使用 multipart/form-data 作为 Content-Type 来传送请求体是很常见的做法。
当定义 multipart 内容的输入参数时必须指定 schema 属性。这不但支持复杂的结构而且支持多文件上传机制。

  1. requestBody:
  2. content:
  3. multipart/form-data:
  4. schema:
  5. type: object
  6. properties:
  7. id:
  8. type: string
  9. format: uuid
  10. address:
  11. # default Content-Type for objects is `application/json`
  12. # 如果属性是复杂对象或者复杂对象的数组,那么默认的 Content-Type 是 application/json
  13. type: object
  14. properties: {}
  15. profileImage:
  16. # default Content-Type for string/binary is `application/octet-stream`
  17. # 如果属性是 type: string 与 format: binary 或 format: base64(也就是文件对象) 的组合,那么默认的 Content-Type 是 application/octet-stream
  18. type: string
  19. format: binary
  20. children:
  21. # default Content-Type for arrays is based on the `inner` type (text/plain here)
  22. # 如果属性是一个原始值或者是一个原始值的数组,那么默认的 Content-Type 是 text/plain
  23. type: array
  24. items:
  25. type: string
  26. addresses:
  27. # default Content-Type for arrays is based on the `inner` type (object shown, so `application/json` in this example)
  28. type: array
  29. items:
  30. type: '#/components/schemas/Address'

Encoding 对象

对具体属性的 Content-Type 的编码。默认值取决于属性的类型:

  • application/octet-stream 编码适用于 binary 格式的 string;
  • text/plain 适用于其他原始值;
  • application/json 适用于 object;
  • 对于 array 值类型的默认值取决于数组内元素的类型,默认值可以是明确的媒体类型 (比如 application/json), 或者通配符类型的媒体类型 (比如 image/*), 又或者是用分号分隔的两种媒体类型。

Responses 对象

描述一个操作可能发生响应的响应码与响应包含的响应体的对象。

  1. '200':
  2. description: 操作成功返回的对象
  3. content:
  4. application/json:
  5. schema:
  6. $ref: '#/components/schemas/Pet'
  7. default:
  8. description: Unexpected error,未知的错误
  9. content:
  10. application/json:
  11. schema:
  12. $ref: '#/components/schemas/ErrorModel'

带 HTTP 头的普通文本类型的响应:

  1. description: 响应简单的字符串
  2. content:
  3. text/plain:
  4. schema:
  5. type: string
  6. example: 'whoa!'
  7. headers:
  8. X-Rate-Limit-Limit:
  9. description: 当前期间允许的请求数目
  10. schema:
  11. type: integer
  12. X-Rate-Limit-Remaining:
  13. description: 当前期间的剩余请求数
  14. schema:
  15. type: integer
  16. X-Rate-Limit-Reset:
  17. description: 当前期间剩余的秒数
  18. schema:
  19. type: integer

一个包含复杂类型的数组格式的响应:

  1. responses:
  2. '200':
  3. description: successful operation
  4. content:
  5. application/json:
  6. schema:
  7. type: array # 返回一个数组,数组中每个值都是 Pet 对象。
  8. items:
  9. $ref: '#/components/schemas/Pet'

没有返回值的响应:

  1. responses:
  2. '400':
  3. description: Invalid ID supplied
  4. '404':
  5. description: Pet not found
  6. '405':
  7. description: Validation exception

Header 对象

Header 对象的结构与 Parameter 对象的结构相似,并添加以下规则:

  1. name 属性不必指定!
  2. in 属性不必指定!
  3. 受 loaction 影响的所有特征必须适用于 header 位置,例如 style 属性。
    1. headers:
    2. X-Rate-Limit-Limit:
    3. description: 当前期间允许的请求数
    4. schema:
    5. type: integer
    6. X-Rate-Limit-Remaining:
    7. description: 当前期间剩余请求数
    8. schema:
    9. type: integer
    10. X-Rate-Limit-Reset:
    11. description: 当前时段剩余的秒数
    12. schema:
    13. type: integer
    Reference 对象
    一个允许引用规范内部的其他部分或外部规范的对象。
    1. $ref: '#/components/schemas/Pet'
    Schema 对象
    Schema对象用于定义输入和输出的数据类型。这些类型可以是对象,也可以是原始值和数组。 ```yaml type: object required:
  • name properties: name: type: string address: $ref: ‘#/components/schemas/Address’ age: type: integer format: int32 minimum: 0
    1. <a name="EQwCT"></a>
    2. ### Security Schema 对象
    3. security Schemes 和 security 关键字用于描述 API 中使用的身份验证方法。<br />components 对象下的 securitySchemas 对象示例:
    4. ```yaml
    5. # 一个包含多种纲要的元素,可重复使用组件
    6. components:
    7. securitySchemes:
    8. petstore_auth:
    9. type: oauth2
    10. flows:
    11. implicit:
    12. authorizationUrl: 'http://petstore.swagger.io/oauth/dialog'
    13. scopes:
    14. 'write:pets': modify pets in your account
    15. 'read:pets': read your pets
    16. api_key:
    17. type: apiKey
    18. name: api_key
    19. in: header

    Basic Authentication Sample

    基础(basic)鉴权。
    1. components:
    2. securitySchemes:
    3. BasicAuth:
    4. type: http # 有效值包括 apiKey、http、oauth2、openIdConnect
    5. scheme: basic

    API Key Sample

    API 秘钥鉴权
    1. securitySchemes:
    2. api_key:
    3. type: apiKey
    4. name: api_key # name 用于 header、 query 或 cookie 的参数名字
    5. in: header # 指定 API 密钥的位置。有效值包括:query、header、cookie

    JWT Bearer Sample

    1. type: http
    2. scheme: bearer
    3. bearerFormat: JWT

    OAuth2 鉴权

    当我们定义 OAuth2 类型的安全项时,我们通常会定义 OAuth2 的流程(flow)和并根据选定的流程配置相应的鉴权地址(authorizationUrl)和/或令牌地址(tokenUrl)。
    OAuth2 的流程(Flow)有如下四个:
流程 所需要的 URL
implicit authorizationUrl(鉴权地址)
password tokenUrl(令牌地址)
application tokenUrl
accessCode authorizationUrl and tokenUrl
  1. securitySchemes:
  2. petstore_auth:
  3. type: oauth2
  4. flows: # 一个包含所支持的 flow types 的配置信息的对象。
  5. implicit: # OAuth 隐式流的配置
  6. authorizationUrl: https://example.com/api/oauth/dialog # 此流程所需的鉴权地址
  7. scopes: # 此 OAuth2 安全方案的作用范围
  8. write:pets: modify pets in your account
  9. read:pets: read your pets
  10. authorizationCode: # OAuth 授权码流程的配置
  11. authorizationUrl: https://example.com/api/oauth/dialog
  12. tokenUrl: https://example.com/api/oauth/token # 此流程所需的令牌地址。
  13. scopes:
  14. write:pets: modify pets in your account
  15. read:pets: read your pets

通用型子对象

Schema Object

  • title
  • multipleOf
  • maximum
  • exclusiveMaximum : bool类型,某些 json schema 版本要求是number型
  • minimum
  • exclusiveMinimum : bool类型,某些 json schema 版本要求是number型
  • maxLength
  • minLength
  • pattern
  • maxItems
  • minItems
  • uniqueItems
  • maxProperties
  • minProperties
  • required
  • enum

    以下属性取自JSON Schema定义,但它们的定义被调整到OpenAPI规范

  • type - Value MUST be a string. Multiple types via an array are not supported.

  • allOf - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
  • oneOf - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
  • anyOf - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
  • not - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
  • items - Value MUST be an object and not an array. Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema. items MUST be present if the type is array.
  • properties - Property definitions MUST be a Schema Object and not a standard JSON Schema (inline or referenced).
  • additionalProperties - Value can be boolean or object. Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema. Consistent with JSON Schema, additionalProperties defaults to true.
  • description - CommonMark syntax MAY be used for rich text representation.
  • format - See Data Type Formats for further details. While relying on JSON Schema’s defined formats, the OAS offers a few additional predefined formats.
  • 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. Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object defined at the same level. For example, if type is string, then default can be “foo” but cannot be 1.

固定字段:

  • nullable :bool,是否允许为 null


简单例子:

  1. type: object
  2. required:
  3. - name
  4. properties:
  5. name:
  6. type: string
  7. address:
  8. $ref: '#/components/schemas/Address'
  9. age:
  10. type: integer
  11. format: int32
  12. minimum: 0
  13. exclusiveMinimum: true #最小是0,但不包含0

Composition 下的定义

  1. components:
  2. schemas:
  3. Pet:
  4. type: object
  5. discriminator:
  6. propertyName: petType
  7. properties:
  8. name:
  9. type: string
  10. petType:
  11. type: string
  12. required:
  13. - name
  14. - petType
  15. Cat: ## "Cat" will be used as the discriminator value
  16. description: A representation of a cat
  17. allOf:
  18. - $ref: '#/components/schemas/Pet'
  19. - type: object
  20. properties:
  21. huntingSkill:
  22. type: string
  23. description: The measured skill for hunting
  24. enum:
  25. - clueless
  26. - lazy
  27. - adventurous
  28. - aggressive
  29. required:
  30. - huntingSkill
  31. Dog: ## "Dog" will be used as the discriminator value
  32. description: A representation of a dog
  33. allOf:
  34. - $ref: '#/components/schemas/Pet'
  35. - type: object
  36. properties:
  37. packSize:
  38. type: integer
  39. format: int32
  40. description: the size of the pack the dog is from
  41. default: 0
  42. minimum: 0
  43. required:
  44. - packSize