添加示例
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 中 支持引用示例。