FastAPI 路径、请求、请求体综合使用

示例一

  • 使用 Pydantic 的 Field 在 Pydantic 模型内部声明校验和元数据

  • 更多方式,参考源码

# coding: utf8

from typing import Optional
from fastapi import FastAPI,Path, Body
from pydantic import BaseModel, Field

app = FastAPI()


class UserIn(BaseModel):
    name: str 
    age: int = Field(..., ge=0, le=200)   # 校验大于等于0,小于等于200岁
    desc: Optional[str] = Field(None, title='这是表述', max_length=100)   # 表述,默认空,最大字符100

# 传入 ID, 提交约定的内容, 并必须携带一起其他的标识,并返回内容
@app.post("/items/{id}")
async def items(*,
    id: int = Path(..., title='id'),
    user: UserIn = Body(...,embed=True),
    who: str = Body(...)
):
    return { 'id': id, 'user': user, 'who': who }


# 启动: uvicorn main:app --reload
': user, 'who': who }

模型的嵌套

Last updated