基本結構
您可以使用 YAML 或 JSON 編寫 OpenAPI 定義。在本指南中,我們僅使用 YAML 範例,但 JSON 的效果也相同。一個使用 YAML 編寫的 OpenAPI 3.0 定義範例如下
1openapi: 3.0.02info:3 title: Sample API4 description: Optional multiline or single-line description in [CommonMark](http://commonmark.org/help/) or HTML.5 version: 0.1.96
7servers:8 - url: http://api.example.com/v19 description: Optional server description, e.g. Main (production) server10 - url: http://staging-api.example.com11 description: Optional server description, e.g. Internal staging server for testing12
13paths: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 code20 description: A JSON array of user names21 content:22 application/json:23 schema:24 type: array25 items:26 type: string
所有關鍵字名稱都區分大小寫。
中繼資料
每個 API 定義都必須包含此定義所依據的 OpenAPI 規格版本
1openapi: 3.0.0
OpenAPI 版本定義了 API 定義的整體結構 – 您可以記錄什麼以及如何記錄。OpenAPI 3.0 使用具有三部分版本號碼的 語意版本控制。可用的版本為 3.0.0
、3.0.1
、3.0.2
和 3.0.3
;它們在功能上是相同的。
info
區段包含 API 資訊:title
、description
(選用)、version
1info:2 title: Sample API3 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-beta 或 2017-07-25)。info
也支援其他用於聯絡資訊、授權、服務條款和其他詳細資料的關鍵字。
參考:資訊物件。
伺服器
servers
區段指定 API 伺服器和基本 URL。您可以定義一個或多個伺服器,例如生產和沙箱。
1servers:2 - url: http://api.example.com/v13 description: Optional server description, e.g. Main (production) server4 - url: http://staging-api.example.com5 description: Optional server description, e.g. Internal staging server for testing
所有 API 路徑都相對於伺服器 URL。在上述範例中,/users
表示 http://api.example.com/v1/users
或 http://staging-api.example.com/users
,具體取決於所使用的伺服器。如需更多資訊,請參閱API 伺服器和基本路徑。
路徑
paths
區段定義 API 中的個別端點(路徑)以及這些端點支援的 HTTP 方法(操作)。例如,GET /users
可以描述為
1paths:2 /users:3 get:4 summary: Returns a list of users.5 description: Optional extended description in CommonMark or HTML6 responses:7 "200":8 description: A JSON array of user names9 content:10 application/json:11 schema:12 type: array13 items:14 type: string