跳到内容

基本结构

您可以使用 YAMLJSON 编写 OpenAPI 定义。本指南中,我们只使用 YAML 示例,但 JSON 同样适用。一个用 YAML 编写的 OpenAPI 3.0 示例定义如下:

1
openapi: 3.0.4
2
info:
3
title: Sample API
4
description: Optional multiline or single-line description in [CommonMark](http://commonmark.org/help/) or HTML.
5
version: 0.1.9
6
7
servers:
8
- url: http://api.example.com/v1
9
description: Optional server description, e.g. Main (production) server
10
- url: http://staging-api.example.com
11
description: Optional server description, e.g. Internal staging server for testing
12
13
paths:
14
/users:
15
get:
16
summary: Returns a list of users.
17
description: Optional extended description in CommonMark or HTML.
18
responses:
19
"200": # status code
20
description: A JSON array of user names
21
content:
22
application/json:
23
schema:
24
type: array
25
items:
26
type: string

所有关键字名称都区分大小写

元数据

每个 API 定义都必须包含此定义所基于的 OpenAPI 规范版本

1
openapi: 3.0.4

OpenAPI 版本定义了 API 定义的整体结构——您可以文档化什么以及如何文档化。OpenAPI 3.0 使用语义版本控制,版本号由三部分组成。可用版本3.0.03.0.13.0.23.0.33.0.4;它们在功能上是相同的。

info 部分包含 API 信息:titledescription(可选)、version

1
info:
2
title: Sample API
3
description: Optional multiline or single-line description in [CommonMark](http://commonmark.org/help/) or HTML.
4
version: 0.1.9

title 是您的 API 名称。description 是关于您的 API 的扩展信息。它可以是多行,并支持 CommonMark 方言的 Markdown 用于富文本表示。HTML 的支持程度与 CommonMark 提供的一致(参见 CommonMark 0.27 规范中的 HTML 块)。version 是一个任意字符串,指定您的 API 版本(不要与文件修订或 openapi 版本混淆)。您可以使用语义版本控制,如主版本.次版本.补丁版本,或任意字符串,如1.0-beta2017-07-25info 还支持其他关键字,用于联系信息、许可证、服务条款和其他详细信息。

参考:信息对象

服务器

servers 部分指定 API 服务器和基本 URL。您可以定义一个或多个服务器,例如生产环境和沙盒环境。

1
servers:
2
- url: http://api.example.com/v1
3
description: Optional server description, e.g. Main (production) server
4
- url: http://staging-api.example.com
5
description: Optional server description, e.g. Internal staging server for testing

所有 API 路径都相对于服务器 URL。在上面的示例中,/users 表示 http://api.example.com/v1/usershttp://staging-api.example.com/users,具体取决于所使用的服务器。更多信息,请参阅API 服务器和基路径

路径

paths 部分定义了 API 中的各个端点(路径)以及这些端点支持的 HTTP 方法(操作)。例如,GET /users 可以描述为

1
paths:
2
/users:
3
get:
4
summary: Returns a list of users.
5
description: Optional extended description in CommonMark or HTML
6
responses:
7
"200":
8
description: A JSON array of user names
9
content:
10
application/json:
11
schema:
12
type: array
13
items:
14
type: string
© . All rights reserved.