文章目录

  • 1、为什么需要规范
  • 2、接口文档的形式和定义
  • 3、接口文档的详细规范
    • 3.1 Format
    • 3.2 文档结构:Document Structure
    • 3.3 数据类型:Data Types
    • 3.4 富文本格式
    • 3.5 Schema
  • 4、示例

参考文档: Swagger Specification

1、为什么需要规范

  • 接口的使用者(front-end developer),调用者(client),提供者(server),维护者(back-end developer),测试者(tester),需要通过规范来统一思想,提高信息传达的效率;
  • 前端开发人员不需要关心后端开发的语言和平台,也不应该去查看后端的代码或开发文档,真正的做到面向接口文档开发
  • 接口定义文档可以通过代码生成工具生成各种语言形式的框架代码,避免需求变更时导致的数据不一致问题,提高开发效率;

2、接口文档的形式和定义

顾名思义,接口文档 就是定义和描述 服务接口的文档;接口定义规范(OAS - OpenAPI Specification) 则是 接口 的元模型,它详细规定了 接口 的元素和格式。将像 Java 代码Java 语言规范 的关系一样。

路径模板(Path Templating),URL 路径中的 {} 作为占位符,可以被响应的路径参数替换。

Media Types

  • text/plain; charset=utf-8
  • application/json

HTTP Status Codes

3、接口文档的详细规范

3.1 Format

根据 OpenAPI 规范,OpenAPI 的格式可以书写为 JSON 或 YAML但 API Request 和 Response 的消息体的格式不局限于 JSON 和 YAML。

现在很多配置文件(比如Nginx和大部分脚本语言的配置文件)都习惯使用 JSON 的方式。在 Springboot 中,推荐使用 properties 或者 YAML 文件来完成配置,但是对于较复杂的数据结构,YAML 远远优于 properties。

YAML 快速入门

YAML 1.2

3.2 文档结构:Document Structure

OpenAPI 文档可以是当个文件,也可以是多个文件,开发者按需求而定。多文档的情况下,可以使用 $ref 来引用其他文档,具体参照 JSON Schema 规范。

根文档(root OpenAPI document)推荐命名为: openapi.json 或 openapi.yaml !

3.3 数据类型:Data Types

数据类型,可校验,可测试。

OAS 中的类型定义:

类型 格式 说明
integer int32 signed 32 bits
integer int64 signed 64 bits
number float float
number double 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.

3.4 富文本格式

文档中 description 字段的内容支持 CommonMark 规范的 markdown 格式,因此 OpenAPI 文档渲染工具至少要支持 CommonMark 0.27.

3.5 Schema

  • OpenAPI Object
  • Info Object
  • Contact Object
  • License Object
  • Server Object
  • Server Variable Object
  • Components Object
  • Paths Object
  • Path Item Object
  • Operation Object
  • External Documentation Object
  • Parameter Object
  • Request Body Object
  • Media Type Object
  • Encoding Object
  • Responses Object
  • Response Object
  • Callback Object
  • Example Object
  • Link Object
  • Header Object
  • Tag Object
  • Reference Object
  • Schema Object
  • Discriminator Object
  • XML Object
  • Security Scheme Object
  • OAuth Flows Object
  • OAuth Flow Object

1、OpenAPI Object

该文档为根文档:

Field Name Type Description
openapi string REQUIRED:
info Info Object REQUIRED: 提供 API 所需的元数据
servers [Server Object] 提供目的连接相关信息对象的数组
paths Paths Object REQUIRED. 指定 API 的路径和操作信息
components Components Object An element to hold various schemas for the specification.
security [Security Requirement Object] A declaration of which security mechanisms can be used across the API. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. Individual operations can override this definition.
tags [Tag Object] A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The tags that are not declared MAY be organized randomly or based on the tools’ logic. Each tag name in the list MUST be unique.
externalDocs External Documentation Object Additional external documentation.

Info Object Example : JSON

{"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": "https://www.apache.org/licenses/LICENSE-2.0.html"},"version": "1.0.1"
}

Info Object Example : YAML

title: Sample Pet Store App
description: This is a sample server for a pet store.
termsOfService: http://example.com/terms/
contact:name: API Supporturl: http://www.example.com/supportemail: support@example.com
license:name: Apache 2.0url: https://www.apache.org/licenses/LICENSE-2.0.html
version: 1.0.1

2、Server Object

Field Name Type Description
url string REQUIRED. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in {brackets}.
description string An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation.
variables Map[string, Server Variable Object] A map between a variable name and its value. The value is used for substitution in the server’s URL template.

Example : JSON

{"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"}}}]
}

Example: YAML

servers:
- url: https://{username}.gigantic-server.com:{port}/{basePath}description: The production API servervariables:username:# note! no enum here means it is an open valuedefault: demodescription: this value is assigned by the service provider, in this example `gigantic-server.com`port:enum:- '8443'- '443'default: '8443'basePath:# open meaning there is the opportunity to use special base paths as assigned by the provider, default is `v2`default: v2

Server Variable Object

  • enum: 当参数的取值范围为有限的 string 集合时,通过 enum 来定义该数组;
  • default: 用来定义默认值;

3、Components Object

组件对象中定义了一组可复用的对象。

Field Name Type Description
schemas Map[string, Schema Object Reference Object]
responses Map[string, Response Object Reference Object]
parameters Map[string, Parameter Object Reference Object]
examples Map[string, Example Object Reference Object]
requestBodies Map[string, Request Body Object Reference Object]
headers Map[string, Header Object Reference Object]
securitySchemes Map[string, Security Scheme Object Reference Object]
links Map[string, Link Object Reference Object]
callbacks Map[string, Callback Object Reference Object]

以上字段的所有属性名称必须符合 ^[a-zA-Z0-9\.\-_]+$ 格式;

例如:
User User_1 User_Name user-name my.org.User

组件对象示例:

"components": {"schemas": {"GeneralError": {"type": "object","properties": {"code": {"type": "integer","format": "int32"},"message": {"type": "string"}}},"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"}}}}}
}

4、Paths Object

Path 对象中保存了 api 的相对路径,拼接在 Server 对象中的路径后可得 api 的全路径。字段名称以 / 开头。

路径匹配规则:

  • /pets/mine 先匹配 /pets/mine,然后匹配 /pets/{id}
  • /pets/{id}/pets/{name} 是等效的
  • /{entity}/me/books/{id} 在匹配时会产生歧义

Paths Object Example:

{"/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"}}}}}}}}
}

5、Path Item Object

Field Name Type Description
$ref string Allows for an external definition of this path item. The referenced structure MUST be in the format of a Path Item Object. If there are conflicts between the referenced definition and this Path Item’s definition, the behavior is undefined.
summary string An optional, string summary, intended to apply to all operations in this path.
description string An optional, string description, intended to apply to all operations in this path. CommonMark syntax MAY be used for rich text representation.
get Operation Object A definition of a GET operation on this path.
put Operation Object A definition of a PUT operation on this path.
post Operation Object A definition of a POST operation on this path.
delete Operation Object A definition of a DELETE operation on this path.
options Operation Object A definition of a OPTIONS operation on this path.
head Operation Object A definition of a HEAD operation on this path.
patch Operation Object A definition of a PATCH operation on this path.
trace Operation Object A definition of a TRACE operation on this path.
servers [Server Object] An alternative server array to service all operations in this path.
parameters [Parameter Object Reference Object]

Path Item Object Example

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

6、Operation Object
7. External Documentation Object
8. Parameter Object
9. Request Body Object
10. Media Type Object
11. Encoding Object
12. Responses Object
13. Response Object
14. Callback Object
15. Example Object
16. Link Object
17. Header Object
18. Tag Object
19. Reference Object
20. Schema Object

4、示例

OpenAPI Specification相关推荐

  1. 架构师之路 — API 经济 — Swagger OpenAPI Specification

    目录 文章目录 目录 OpenAPI Specification Swagger 生态组件 编写 OpenAPI 规范文件 基本概念 OpenAPI Root Object(根对象) OpenAPI ...

  2. 基于OpenAPI Specification自动生成Android客户端代码

    OpenAPI Specification(OAS) 无论你从事前端开发还是后端开发,或多或少都听说过Swagger. Swagger Specification 是一种 API Specificat ...

  3. OpenAPI使用(swagger3),Kotlin使用swagger3,Java使用swagger3,gradle、Maven使用swagger3

    OpenAPI使用(swagger3) demo见Gitte 一.背景及名词解释 OpenAPI是规范的正式名称.规范的开发工作于2015年启动,当时SmartBear(负责Swagger工具开发的公 ...

  4. Go 语言编程 — go-swagger OpenAPI 工具

    目录 文章目录 目录 go-swagger Generate a spec from source Generate an API server 参考文档 go-swagger go-swagger ...

  5. 使用 OAS(OpenAPI标准)来描述 Web API

    无论哪种类型的Web API, 都可能需要给其他开发者使用. 所以API的开发者体验是很重要的. API的开发者体验, 简写为 API DX (Developer Experience). 它包含很多 ...

  6. TeaDSL:支持任意 OpenAPI 网关的多语言 SDK 方案

    正在上传-重新上传取消 导读 在以云计算为主角的开发者视界中,OpenAPI 是绝对的主角.要发短信,用 OpenAPI:要管理资源,用 OpenAPI:要管理权限,用 OpenAPI.如果一个 Op ...

  7. 名词解释:swagger, openapi, springfox, springdoc

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 Swagger vs OpenApi 1. Swagger 2. OpenApi 3. 二者关系 Springfox vs ...

  8. Swagger (YAML OpenAPI) 从放弃到入门

    Swagger 是一个统一前后端用于生成文档和代码的工具,它使用 yaml / json 作为描述语言 通过 OpenAPI Specification 来描述 API,最后使用 Codegen 根据 ...

  9. OpenAPI规范3.1.0

    OpenAPI规范 版本 3.1.0 介绍 OpenAPI规范(OAS)为HTTP API定义了一个与语言无关的标准接口,使得人和计算机都可以在不使用源代码.文档或监听网络通信的情况下,具备发现和理解 ...

  10. Swagger与OpenAPI

    ** 如有错误,感谢指正** 如有错误,感谢指正,请私信博主,有辛苦红包,拜"一字之师". 请根据目录寻找自己需要的段落 导语:本博客为个人整理Java学习记录帖,如有错误,感谢指 ...

最新文章

  1. LSTM内部实现原理详解
  2. 编程语言与思维:科技公司如何自我重构?
  3. python中的lambda 和java中的lambda有什么不同?lambda相关介绍
  4. 从OpenFOAM的源码中查找信息
  5. Netty4.0学习笔记系列之五:自定义通讯协议
  6. java 普通方法_Java普通方法与static方法的多态
  7. swfobject的使用
  8. 慕课软件工程(第五章.初始模块结构图精化的原则)
  9. 12 个组织良好的网络监控工具
  10. My Fifty-Sixth Page - 子集Ⅱ - By Nicolas
  11. mysql远程3306不通_mysql服务器3306端口不能远程连接的解决
  12. python列表拆包_python拆包
  13. 零基础入门,花生壳骨灰级微信小程序开发教程
  14. python2.7安装失败_Pyside安装失败(Python 2.7.4)
  15. 小程序的 wx.createVideoContext 使用
  16. 用html语言做坦克大战
  17. 添加网桥,添加一对虚拟网卡
  18. 一名程序猿的习惯养成记录手帐(二十一)
  19. 黎曼的zeta函数(2)
  20. 自造轮子:C#中数字转中文(繁体可自行更换)

热门文章

  1. qq飞车鸿蒙车队,qq飞车鸿蒙版
  2. mybatis框架xml中trim中的prefix与suffix等标签的作用
  3. 自定义智能报表系统内容准备:基于WEB的SBO数据结构浏览器
  4. WTS 2.1.18124.1 彻底抛弃了 15063(Win 10 创意者更新)
  5. bypass-wts-waf
  6. selenium录制百度3D地图
  7. 18个最受欢迎的低代码开发平台【开源】
  8. 单引号在c语言中作用,我想知道单引号在C语言的具体作用
  9. Linux下查看电脑配置信息
  10. html 编辑cad图,cad制图是什么