2.2 媒体类型
媒体类型表示请求或响应体正文数据的格式,Web服务操作可以接受和返回不同格式的数据,最常见的是JSON、XML和图片。你可以在请求和响应定义中指定媒体类型,如下所示:
paths:
/employees:
get:
summary: Returns a list of employees.
responses:
'200': # Response
description: OK
content: # Response body
application/json: # Media type
schema: # Must-have
type: object # Data type
properties:
id:
type: integer
name:
type: string
fullTime:
type: boolean
example: # Sample data
id: 1
name: Jessica Right
fullTime: true
2.2.1 媒体类型名称
content字段下面列出的媒体类型应符合RFC 6838。例如,你可以使用标准类型或特定于供应商的类型:
application/json
application/xml
application/x-www-form-urlencoded
multipart/form-data
text/plain;charset=utf-8
text/html
application/pdf
image/png
application/vnd.mycompany.myapp.v2+json
application/vnd.ms-excel
application/vnd.openstreetmap.data+xml
application/vnd.github-issue.text+json
application/vnd.github.v3.diff
image/vnd.djvu
2.2.2 多种媒体类型
我们可以指定多个媒体类型:
paths:
/employees:
get:
summary: Returns a list of employees.
responses:
'200': # Response
description: OK
content: # Response body
application/json: # One of media types
schema:
type: object
properties:
id:
type: integer
name:
type: string
fullTime:
type: boolean
application/xml: # Another media types
schema:
type: object
properties:
id:
type: integer
name:
type: string
fullTime:
type: boolean
要对多种媒体类型使用相同的数据格式components,请在规范部分定义自定义对象,然后在美中媒体中引用此对象:
paths:
/employees:
get:
responses:
'200': # Response
description: OK
content: # Response body
application/json: # Media type
schema:
$ref: '#/components/schemas/Employee' # Reference to object definition
application/xml: # Media type
schema:
$ref: '#/components/schemas/Employee' # Reference to object definition
components:
schemas:
Employee: # Object definition
type: object
properties:
id:
type: integer
name:
type: string
fullTime:
type: boolean
要定义多种媒体类型相同的格式,你也可以使用占位符像*/,application/,image/*或其他:
paths:
/info/logo:
get:
responses:
'200': # Response
description: OK
content: # Response body
image/*: # Media type
schema:
type: string
format: binary
在实例中使用的媒体类型——image/*看起来很像HTTP的Request和Response的头信息 Accept 或 Content-Type 。不要混淆占位符的实际值Accept或Content-Type头。例如,image/*响应主题的占位符意味着服务器将对与占位符匹配的所有响应使用相同的数据结构。这并不意味着将在Header中指定Content-Type为image/*。Content-Type有可能具有image/png、image/jpg或其他。