API 響應(yīng)內(nèi)容的格式妖滔,是通過(guò) Response
對(duì)象的 content
字段,進(jìn)行描述的。
content
字段不僅能用在 Response
對(duì)象中诊县,還可以用于 Request Body
對(duì)象里。Response
對(duì)象的 content
字段 會(huì)以不同的格式返回措左,如下所示:
content:
application/json:
...
text/html:
...
text/*:
...
響應(yīng)內(nèi)容的結(jié)構(gòu)是由 Media Type Object
來(lái)描述的依痊,而在文檔中,是通過(guò) schema
字段來(lái)實(shí)現(xiàn)的怎披。
content:
application/json:
schema:
...
schema
字段對(duì)應(yīng)的是 Schema Object
胸嘁,可以定義一個(gè)數(shù)據(jù)類(lèi)型:原生類(lèi)型(string,integer凉逛,...)性宏,數(shù)組或?qū)ο蟆?code>schema 字段的具體類(lèi)型,是由 type
字段決定的状飞,可以是:number
, string
, boolean
, array
和 object
. 還可以通過(guò)一些其他字段毫胜,對(duì)數(shù)據(jù)類(lèi)型的取值進(jìn)行描述,例如诬辈,使用 minLength
和 maxLength
對(duì)字符串類(lèi)型值的長(zhǎng)度進(jìn)行限制酵使;使用 minimum
和 maximum
對(duì)整數(shù)類(lèi)型值的大小進(jìn)行限制;使用枚舉數(shù)組 enum
限制數(shù)據(jù)的選項(xiàng)焙糟。
integer 限制大小的示例如下:
content:
application/json:
schema:
type: integer
minimum: 1
maximum: 100
string 限制三個(gè)有效選項(xiàng)的示例如下:
content:
application/json:
schema:
type: string
enum:
- Alice
- Bob
- Carl
下面代碼片段是來(lái)自 OpenAPI 官方文檔的一個(gè)示例:
openapi: 3.1.0
info:
title: Tic Tac Toe
description: |
This API allows writing down marks on a Tic Tac Toe board
and requesting the state of the board or of individual squares.
version: 1.0.0
paths:
# Whole board operations
/board:
get:
summary: Get the whole board
description: Retrieves the current state of the board and the winner.
responses:
"200":
description: "OK"
content:
application/json:
schema:
type: object
properties:
winner:
type: string
enum: [".", "X", "O"]
description: |
Winner of the game. `.` means nobody has won yet.
board:
type: array
maxItems: 3
minItems: 3
items:
type: array
maxItems: 3
minItems: 3
items:
type: string
enum: [".", "X", "O"]
description: |
Possible values for a board square.
`.` means empty square.
...