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 }
curl -H "Content-Type: application/json" -X POST -d '{"user": {"name":"tom", "age": 18}, "who":"二大爷"}' 127.0.0.1:8000/items/1

{"id":1,"user":{"name":"tom","age":18,"desc":null},"who":"二大爷"}

模型的嵌套

# coding: utf8

from typing import Optional,List
from fastapi import Body, FastAPI
from pydantic import BaseModel, Field,HttpUrl

app = FastAPI()

class Blog(BaseModel):
    url: HttpUrl
    name: str

class Item(BaseModel):
    name: str
    description: Optional[str] = Field(None, title="这是描述", max_length=300)
    age: float = Field(..., ge=0, description="精确到月份")
    gay: Optional[bool] = None      # 是否同性恋, true || False
    like: List[str] = []            # 爱好, 接受列表
    blog: Optional[Blog] = None       # 个人网站

@app.post("/items/{id}")
def items(id: int, item: Item = Body(..., embed=True)):
    results = {"id": id, "item": item}
    print(item)
    return results

# 启动: uvicorn main:app --reload
curl --location --request POST 'http://10.11.9.247:8000/items/1' \
--header 'Content-Type: application/json' \
--data-raw '{
    "item": {
        "name": "tom",
        "age": 18.1,
        "gay": true,
        "like": [
            "kiss",
            "papa"
        ],
        "blog": {
            "url": "http://91.com/",
            "name": "91"
        }
    }

}'
{
    "id": 1,
    "item": {
        "name": "tom",
        "description": null,
        "age": 18.1,
        "gay": true,
        "like": [
            "kiss",
            "papa"
        ],
        "blog": {
            "url": "http://91.com/",
            "name": "91"
        }
    }
}

Last updated