路徑和操作
在 Swagger 的術語中,路徑 是您的 API 公開的端點(資源),例如 /users
或 /reports/summary
,而操作是操控這些路徑所使用的 HTTP 方法,例如 GET、POST 或 DELETE。
路徑
API 路徑和操作定義在 API 規格的整體 paths
區段中。
1paths:2 /ping: ...3 /users: ...4 /users/{id}: ...
所有路徑都相對於 basePath
(請參閱 API 主機和基本 URL)。完整的請求 URL 建構為 scheme://host/basePath/path
。
路徑範本
Swagger 支援路徑範本,這表示您可以使用大括號 {}
將 URL 的一部分標示為 路徑參數。
1/users/{id}2/organizations/{orgId}/members/{memberId}3/report.{format}
API 用戶端在進行 API 呼叫時需要提供適當的參數值,例如 /users/5
或 /users/12
。
操作
針對每個路徑,您可以定義可用於存取該路徑的操作 (HTTP 方法)。Swagger 2.0 支援 get
、post
、put
、patch
、delete
、head
和 options
。單一路徑可以支援多個操作,例如,GET /users
取得使用者清單,以及 POST /users
新增使用者。Swagger 將唯一操作定義為路徑和 HTTP 方法的組合。這表示不允許同一路徑有兩個 GET 或兩個 POST 方法,即使它們具有不同的參數(參數對唯一性沒有影響)。操作的最小範例
1paths:2 /ping:3 get:4 responses:5 200:6 description: OK
具有參數和回應結構描述的更詳細範例
1paths:2 /users/{id}:3 get:4 summary: Gets a user by ID.5 description: >6 A detailed description of the operation.7 GitHub Flavored Markdown can be used for rich text representation,8 such as **bold**, *italic* and [links](https://swagger.dev.org.tw).9 operationId: getUsers10 tags:11 - users12 produces:13 - application/json14 - application/xml15 parameters:16 - name: id17 in: path18 description: User ID19 type: integer20 required: true21 responses:22 200:23 description: OK24 schema:25 $ref: "#/definitions/User"26 externalDocs:27 url: http://api.example.com/docs/user-operations/28 description: Learn more about User operations provided by this API.29definitions:30 User:31 type: object32 properties:33 id:34 type: integer35 name:36 type: string37 required:38 - id39 - name
操作支援一些選用元素,用於文件用途
- 操作的簡短
summary
和較長的description
。description
可以是多行,並且支援 GitHub 風格的 Markdown,以呈現豐富的文字。 tags
用於在 Swagger UI 中分組操作。externalDocs
允許參考包含額外文件的外部資源。
操作參數
Swagger 支援透過路徑、查詢字串、標頭和請求主體傳遞的操作參數。如需詳細資訊,請參閱描述參數。
operationId
每個操作都可以指定唯一的 operationId
。某些程式碼產生器會使用此值來命名程式碼中的對應方法。
1/users:2 get:3 operationId: getUsers4 summary: Gets all users.5 ...6 post:7 operationId: addUser8 summary: Adds a new user.9 ...10 /user/{id}:11 get:12 operationId: getUserById13 summary: Gets a user by user ID.14 ...
路徑中的查詢字串
查詢字串參數不得包含在路徑中。它們應該定義為查詢參數。錯誤範例
1paths:2 /users?role={role}:
正確範例
1paths:2 /users:3 get:4 parameters:5 - in: query6 name: role7 type: string8 enum: [user, poweruser, admin]9 required: false
這也表示不可能有多個路徑只在查詢字串上有所不同,例如
1GET /users?firstName=value&lastName=value2GET /users?role=value
這是因為 Swagger 將唯一操作視為路徑和 HTTP 方法的組合,額外的參數並不會使操作變得唯一。相反地,您應該使用唯一的路徑,例如
1GET /users/findByName?firstName=value&lastName=value2GET /users/findByRole?role=value
標示為已淘汰
您可以將特定操作標記為 deprecated
,以表示它們應該停止使用
1/pet/findByTags:2 get:3 deprecated: true
工具可能會以特定方式處理已淘汰的操作。例如,Swagger UI 會以不同的樣式顯示它們