请求体 - 字段
字段与使用 Query
、Path
和 Body
在路径操作函数中声明额外的校验和元数据的方式相同,可以使用 Pydantic
的 Field
在 Pydantic
模型内部声明校验和元数据。
注意点:Field
是直接从 pydantic
导入的,而不是像其他的(Query
,Path
,Body
等)都从 fastapi
导入。
首先导入Field
:
from pydantic import Field
其次开始声明模型定义字段:
from pydantic import Field, BaseModel
class Items(BaseModel):
name: str
full_name: Optional[str] = Field(None, min_length=2)
description: Optional[str] = Field(None, max_length=100)
price: float = Field(..., gt=0)
gender: str = Field(..., alias="g")
tax: int = Field(None, title="用于文档中", description="在文档中显示")
注释信息:
min_length=2
是设置字段的最小长度max_length=100
是设置字段最大长度gt=0 是大于0
[ge
大于等于、lt
小于、le
小于等于]alias="g"
是取别名title="用于文档中"
显示在生成的docs
文档中description="在文档中显示"
显示在生成的docs
文档中
然后开始定义接口:
from typing import Optional
from fastapi import FastAPI
from fastapi import Body
from pydantic import Field, BaseModel
class Items(BaseModel):
name: str
full_name: Optional[str] = Field(None, min_length=2)
description: Optional[str] = Field(None, max_length=100)
price: float = Field(..., gt=0)
gender: str = Field(..., alias="g")
tax: int = Field(None, title="用于文档中", description="在文档中显示")
app = FastAPI()
@app.put("/items/{item_id}")
def read_field(item_id: int, item: Items = Body(..., embed=True)):
return {"item_id": item_id, "item": item}
然后启动服务:
lifeng@192 fastapiP