新增範例
API 規格可以包含以下範例:
- 回應 MIME 類型、
- 綱要 (資料模型)、
- 綱要中的個別屬性。
範例可供工具和程式庫使用,例如,Swagger UI 會根據輸入綱要範例自動填入請求主體,而某些 API 模擬工具會使用範例來產生模擬回應。
注意:請勿將範例值與 default
值混淆。範例用於說明值應有的樣子。預設值是伺服器在請求中未提供值時使用的值。
綱要範例
example
金鑰用於提供綱要範例。可以為個別屬性、物件和整個綱要提供範例。
屬性範例
屬性範例可以內嵌指定。範例值必須符合屬性類型。
1definitions:2 CatalogItem:3 type: object4 properties:5 id:6 type: integer7 example: 388 title:9 type: string10 example: T-shirt11 required:12 - id13 - title
請注意,不支援每個屬性或綱要有多個範例值,也就是說,您不能有
1title:2 type: string3 example: T-shirt4 example: Phone
物件範例
類型物件的屬性可以有複雜的內嵌範例,其中包含該物件的屬性。範例應符合物件綱要。
1definitions:2 CatalogItem:3 type: object4 properties:5 id:6 type: integer7 example: 388 title:9 type: string10 example: T-shirt11 image:12 type: object13 properties:14 url:15 type: string16 width:17 type: integer18 height:19 type: integer20 required:21 - url22 example: # <-----23 url: images/38.png24 width: 10025 height: 10026 required:27 - id28 - title
陣列範例
基本類型的陣列範例
1definitions:2 ArrayOfStrings:3 type: array4 items:5 type: string6 example:7 - foo8 - bar9 - baz
同樣地,物件陣列將指定為
1definitions:2 ArrayOfCatalogItems:3 type: array4 items:5 $ref: '#/definitions/CatalogItem'6 example:7 - id: 388 title: T-shirt9 - id: 11410 title: Phone
完整綱要範例
可以為整個綱要 (包括所有巢狀綱要) 指定 example
,前提是範例符合綱要。
1definition:2 CatalogItem:3 type: object4 properties:5 id:6 type: integer7 name:8 type: string9 image:10 type: object11 properties:12 url:13 type: string14 width:15 type: integer16 height:17 type: integer18 required:19 - id20 - name21 example: # <----------22 id: 3823 name: T-shirt24 image:25 url: images/38.png26 width: 10027 height: 100
回應範例
Swagger 允許在回應層級上提供範例,每個範例都對應於操作傳回的特定 MIME 類型。例如,application/json
的一個範例,以及 text/csv
的另一個範例,依此類推。每個 MIME 類型都必須是操作的 produces
值之一 — 明確或繼承自全域範圍。
1produces:2 - application/json3 - text/csv4responses:5 200:6 description: OK7 examples:8 application/json: { "id": 38, "title": "T-shirt" }9 text/csv: >10 id,title11 38,T-shirt
所有範例都是自由格式,表示其解譯取決於工具和程式庫。
JSON 和 YAML 範例
由於 JSON 和 YAML 是可互換的 (YAML 是 JSON 的超集),因此可以使用 JSON 語法來指定兩者
1examples:2 application/json:3 {4 "id": 38,5 "title": "T-shirt"6 }
或 YAML 語法
1examples:2 application/json:3 id: 384 title: T-shirt5 image:6 url: images/38.png
XML 範例
XML 回應範例沒有特定的語法。但是,由於回應範例是自由格式的,因此您可以使用您想要的或您的工具支援的任何格式。
1examples:2 application/xml: '<users><user>Alice</user><user>Bob</user></users>'3
4examples:5 application/xml:6 users:7 user:8 - Alice9 - Bob10
11examples:12 application/xml:13 url: http://myapi.com/examples/users.xml
或者,您可以在回應綱要中指定範例值,如以上所述。
文字範例
由於所有回應範例都是自由格式的,因此您可以使用您的工具或程式庫支援的任何格式。例如,類似於
1examples:2 text/html: '<html><body><p>Hello, world!</p></body></html>'3 text/plain: Hello, world!
另請參閱 Stack Overflow 上的這篇文章,以取得如何在 YAML 中撰寫多行字串的提示。
範例優先順序
如果不同層級 (屬性、綱要、回應) 上有多個範例,則工具會使用處理規格的較高層級範例。也就是說,優先順序的順序是
- 回應範例
- 綱要範例
- 物件和陣列屬性範例
- 基本屬性範例和陣列項目範例
範例和 $ref
OpenAPI 2.0 example
和 examples
關鍵字需要內嵌範例,且不支援 $ref
。範例值會按原樣顯示,因此 $ref
會顯示為名為 $ref
的物件屬性。
在 OpenAPI 3.0 中支援參考範例。