FastAPI | 教程 | 额外的模式

https://fastapi.tiangolo.com/tutorial/schema-extra-example/

示例结构

你可以在JSON结构里面定义其示例信息。

一个常见的方法是添加一个可以在文档中显示的example

有多种方法可以声明额外的JSON示例信息。

Pydanticschema_extra

您可以使用Configschema_extra声明一个example,Pydantic:模式定制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from typing import Optional

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None

class Config:
schema_extra = {
"example": {
"name": "Foo",
"description": "A very nice Item",
"price": 35.4,
"tax": 3.2,
}
}


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
results = {"item_id": item_id, "item": item}
return results

该示例信息将直接添加到JSON结构里面。

Field其他参数

FieldPathQueryBody以及其它的校验中,您还可以通过向函数传递任何其他任意参数来声明JSON模式的额外信息,例如:添加一个example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from typing import Optional

from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class Item(BaseModel):
name: str = Field(..., example="Foo")
description: Optional[str] = Field(None, example="A very nice Item")
price: float = Field(..., example=35.4)
tax: Optional[float] = Field(None, example=3.2)


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
results = {"item_id": item_id, "item": item}
return results

请记住,出于文档目的,传递的那些额外参数不会添加任何验证,而只会添加注释。

请求体的额外参数

你可以使用相同的方式,对PathQueryBody等添加额外的信息。

例如,您可以将example作为请求体传递给Body

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from typing import Optional

from fastapi import Body, FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None


@app.put("/items/{item_id}")
async def update_item(
item_id: int,
item: Item = Body(
...,
example={
"name": "Foo",
"description": "A very nice Item",
"price": 35.4,
"tax": 3.2,
},
),
):
results = {"item_id": item_id, "item": item}
return results

docs 界面中的示例

使用以上任何一种方法,/docs页面都会展示如下信息:

img

技术细节

关于exampleexamples

JSON Schema在最新版本中定义了一个字段 examples,但是OpenAPI是基于JSON Schema的旧版本,所以没有examples

因此,OpenAPI 出于相同目的(是example而不是examples)定义了自己的APIexample,docs UI(使用Swagger UI)用的就是这个。

因此,尽管example它不是JSON结构的一部分,但它是OpenAPI的一部分,而这正是docs UI所使用的。

其他信息

同样,您可以在所有的model中添加自定义JSON结构,例如,自定义前端用户界面等。