FASTAPI系列 09-POST请求BODY校验添加Field
前言
使用 Pydantic 的 Field 在 Pydantic 模型内部声明校验和元数据。
一、Field 字段参数说明
关于 Field 字段参数说明
- Field(None) 是可选字段,不传的时候值默认为None
- Field(…) 是设置必填项字段
- title 自定义标题,如果没有默认就是字段属性的值
- description 定义字段描述内容
定义Book的Model
from pydantic import BaseModel, Field
class Book(BaseModel):
book_name: str
description: str = Field(None,
title="The description of the user",
max_length=100)
price: float = Field(...,
gt=0,
description="The price of the book")
# 定义一个字典
book_dict = {
"book_name": "python",
"description": "The description of the user",
"price": 100.1
}
二、从 pydantic 导入 Field
from typing import Optional
from fastapi import Body, FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class Book(BaseModel):
book_name: str
description: str = Field(None,
title="The description of the user",
max_length=100)
price: float = Field(...,
gt=0,
description="The price of the book")
@app.post("/books/")
async def create_book(book: Book = Body(..., embed=True)):
results = {"book": book}
return results
注意,Field 是直接从 pydantic 导入的,而不是像其他的(Query,Path,Body 等)都从 fastapi 导入。
总结
你可以使用 Pydantic 的 Field 为模型属性声明额外的校验和元数据。你还可以使用额外的关键字参数来传递额外的 JSON Schema 元数据。