FastAPI 请求体参数与 Pydantic 模型完全指南:从基础到嵌套模型实战 🚀
title: FastAPI 请求体参数与 Pydantic 模型完全指南:从基础到嵌套模型实战 🚀
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
age: int
@app.post("/users/")
async def create_user(user: User):
return user
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
@app.post("/items/")
async def create_item(item: Item):
return item
{
"name": "Foo",
"price": 45.2,
"tax": 3.2
}
from pydantic import Field, constr
class Product(BaseModel):
name: constr(min_length=3, max_length=50)
price: float = Field(..., gt=0)
description: str = Field(None, max_length=100)
@app.post("/products/")
async def create_product(product: Product):
return product
class Address(BaseModel):
street: str
city: str
state: str
zip_code: str
class User(BaseModel):
name: str
age: int
address: Address
@app.post("/users/")
async def create_user(user: User):
return user
{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip_code": "12345"
}
}
class OrderItem(BaseModel):
name: str
quantity: int = Field(..., gt=0)
price: float = Field(..., gt=0)
class Order(BaseModel):
items: List[OrderItem]
total: float = Field(..., gt=0)
@app.post("/orders/")
async def create_order(order: Order):
return order
class BaseUser(BaseModel):
email: str
password: str
class UserCreate(BaseUser):
name: str
@app.post("/users/")
async def create_user(user: UserCreate):
return user
class Item(BaseModel):
name: str
description: str = None
class Config:
alias_generator = lambda x: x.upper()
allow_population_by_field_name = True
@app.post("/items/")
async def create_item(item: Item):
return item
class Product(BaseModel):
name: str = Field(..., description="产品名称")
price: float = Field(..., description="产品价格", gt=0)
@app.post("/products/")
async def create_product(product: Product):
return product
from pydantic import BaseModel, Field
class Item(BaseModel):
name: str = Field(..., min_length=3)
price: float = Field(..., gt=0)
@app.post("/items/")
async def create_item(item: Item):
return item
class Address(BaseModel):
street: str
city: str
class User(BaseModel):
name: str
address: Address
@app.post("/users/")
async def create_user(user: User):
return user
错误代码 | 典型触发场景 | 解决方案 |
---|---|---|
422 | 类型转换失败/校验不通过 | 检查模型定义的校验规则 |
404 | 请求体格式正确但资源不存在 | 验证业务逻辑中的数据存在性 |
500 | 未捕获的模型处理异常 | 添加 try/except 包裹敏感操作 |
400 | 自定义校验规则触发拒绝 | 检查验证器的逻辑条件 |
from enum import Enum
class Status(str, Enum):
ACTIVE = "active"
INACTIVE = "inactive"
class User(BaseModel):
name: str
status: Status
@app.post("/users/")
async def create_user(user: User):
return user
class Address(BaseModel):
street: str
city: str = "Anytown"
class User(BaseModel):
name: str
address: Address = Address(street="123 Main St")
@app.post("/users/")
async def create_user(user: User):
return user
curl -X POST "http://localhost:8000/users/" -H "Content-Type: application/json" -d '{"name": "John Doe", "age": 30, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zip_code": "12345"}}'
评论
发表评论