Media type은 request, response body data의 형식이다.
웹 서비스 operations는 서로 다른 데이터 포맷을 받거나 응답할 수 있다. 요즘에는 보통 json, image다.
request와 response 정의에 media type을 명시할 수 있다.
예시
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
위 예시와 같이 responses
아래에 각 응답에 대한 정의를 작성한다.
위 예시를 살펴보면, 응답은 상태코드 200을 내린다.
content
키워드 밑에 코드는 response 바디에 해당한다.
하나 이상의 media type을 content
의 child keywords로(하위 필드에) 작성할 수 있다.
모든 media type은 schema
를 포함한다. schema
는 메세지 바디의 데이터 타입이다.
schema
에는 하나 이상의 예시를 작성할 수 있다.
media type들은 content
필드 아래에 작성한다. 그리고 media type은 RFC 6838과 호환되어야 한다.
media type으로 standard type 혹은 vendor-spcific types(.vnd
)를 사용할 수 있다.
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
하나 이상의 media type을 명시할 수 있다.
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
만약 하나의 데이터 포맷을 여러 media type에 사용하고 싶다면,
components
섹션에 custom object를 작성하고 각 media type이 object를 참조하도록 한다.
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
만약 하나의 데이터 포맷을 여러 media type에 사용하기 위해 */*, application/*, image/*
같은 placeholders를 사용할 수도 있다.
paths:
/info/logo:
get:
responses:
'200': # Response
description: OK
content: # Response body
image/*: # Media type
schema:
type: string
format: binary
위 예시에서 사용한 image/*
placeholder는 request의 Accept
response의 Content-Type
헤더에서 사용하는 값과 비슷하게 생겼지만 헷갈리면 안된다.
예시에서 responses에 사용한 image/*
placeholder는 이 placeholder와 매칭되는 모든 응답에 대해서 같은 응답 데이터로 같은 data structure를 쓰겠다는 의미다.
절대로 Content-Type
헤더 값으로 image/*
를 명시하겠다는 소리가 아니다.