添加示例
API 规范可以包含以下示例:
- 响应 MIME 类型,
- schema (数据模型),
- schema 中的单独属性。
示例可供工具和库使用,例如,Swagger UI 会根据输入 schema 示例自动填充请求体,一些 API 模拟工具则使用示例生成模拟响应。
注意:不要将示例值与 default
值混淆。示例用于说明值应该是什么样子。默认值是当请求中未提供值时服务器使用的值。
Schema 示例
example
键用于提供 schema 示例。示例可以针对单个属性、对象和整个 schema。
属性示例
属性示例可以内联指定。示例值必须符合属性类型。
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
请注意,不支持每个属性或 schema 的多个示例值,即您不能拥有
1title:2 type: string3 example: T-shirt4 example: Phone
对象示例
对象类型的属性可以拥有复杂的内联示例,其中包括该对象的属性。示例应符合对象 schema。
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
整个 Schema 示例
可以为整个 schema(包括所有嵌套 schema)指定一个 example
,前提是该示例符合 schema。
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
或者,您可以在响应 schema 中指定示例值,如上文所述。
文本示例
由于所有响应示例都是自由形式的,您可以使用工具或库支持的任何格式。例如,像这样:
1examples:2 text/html: '<html><body><p>Hello, world!</p></body></html>'3 text/plain: Hello, world!
另请参阅 Stack Overflow 上的这篇文章,获取在 YAML 中编写多行字符串的技巧。
示例优先级
如果在不同级别(属性、schema、响应)存在多个示例,则处理规范的工具将使用更高级别的示例。也就是说,优先级顺序是:
- 响应示例
- Schema 示例
- 对象和数组属性示例
- 原子属性示例和数组项示例
示例和 $ref
OpenAPI 2.0 的 example
和 examples
关键字要求使用内联示例,并且不支持 $ref
。示例值按原样显示,因此 $ref
将显示为名为 $ref
的对象属性。