跳至內容

基本結構

您可以使用 YAMLJSON 編寫 OpenAPI 定義。在本指南中,我們僅使用 YAML 範例,但 JSON 的效果也相同。一個使用 YAML 編寫的 OpenAPI 3.0 定義範例如下

1
openapi: 3.0.0
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.0

OpenAPI 版本定義了 API 定義的整體結構 – 您可以記錄什麼以及如何記錄。OpenAPI 3.0 使用具有三部分版本號碼的 語意版本控制。可用的版本3.0.03.0.13.0.23.0.3;它們在功能上是相同的。

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 方言以進行 RTF 表示。HTML 支援的程度由 CommonMark 提供(請參閱 CommonMark 0.27 規格中的 HTML 區塊)。version 是一個任意字串,指定您的 API 版本(不要將它與檔案修訂或 openapi 版本混淆)。您可以使用 語意版本控制(例如 major.minor.patch)或任意字串(例如 1.0-beta2017-07-25)。info 也支援其他用於聯絡資訊、授權、服務條款和其他詳細資料的關鍵字。

參考:資訊物件

伺服器

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