fastApi笔记06-请求体-多个参数

多个请求体参数

python 复制代码
from fastapi import FastAPI, Path, Query
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None


class User(BaseModel):
    username: str
    full_name: str | None = None


@app.put("/items")
async def update_item(item: Item, user: User):
    results = {"item": item, "user": user}
    return results

当函数有多个请求实体(多个 Pydantic 模型参数),将使用参数名称作为请求体中的键(字段名称),并期望一个类似于以下内容的请求体

python 复制代码
{
    "item": {
        "name": "Foo",
        "description": "The pretender",
        "price": 42.0,
        "tax": 3.2
    },
    "user": {
        "username": "dave",
        "full_name": "Dave Grohl"
    }
}

请求体中的单一值

假如为了拓展先前的模型,除了user和item之外,在请求体中增加一个字段importance,需要使用Body来声明,不然会被当做查询参数

python 复制代码
from fastapi import FastAPI, Body
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None


class User(BaseModel):
    username: str
    full_name: str | None = None


@app.put("/items")
async def update_item(item: Item, user: User, importance: int = Body()):
    results = {"item": item, "user": user, "importance": importance}
    return results
python 复制代码
{
    "item": {
        "name": "Foo",
        "description": "The pretender",
        "price": 42.0,
        "tax": 3.2
    },
    "user": {
        "username": "dave",
        "full_name": "Dave Grohl"
    },
    "importance": 5
}

嵌入单个请求体实参

假如只有一个来自的模型Item,如果你希望它期望一个拥有 item 键并在值中包含模型内容的 JSON,就像在声明额外的请求体参数时所做的那样。比如下面这样的。

python 复制代码
{
    "item": {
        "name": "Foo",
        "description": "The pretender",
        "price": 42.0,
        "tax": 3.2
    }
}

而不是这样的。

python 复制代码
{
    "name": "Foo",
    "description": "The pretender",
    "price": 42.0,
    "tax": 3.2
}

则可以使用一个特殊的 Body 参数 embed

python 复制代码
from typing import Annotated

from fastapi import Body, FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
    results = {"item_id": item_id, "item": item}
    return results

声明模型属性

和使用Query,Path,Body在路径操作函数中声明参数校验和元数据的方式相同,可以使Pydantic 的Field在模型内部进行声明校验和元数据

python 复制代码
from typing import Annotated

from fastapi import Body, FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str | None = Field(
        default=None, title="The description of the item", max_length=300
    )
    price: float = Field(gt=0, description="The price must be greater than zero")
    tax: float | None = None


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
    results = {"item_id": item_id, "item": item}
    return results
相关推荐
DeepLink21 分钟前
Python 小练习系列:掌握偏函数 partial,用函数更丝滑!
python·trae
用户014331939061 小时前
Jumpserver双机集群搭建
python
fantasy_41 小时前
自动化框架及其设计搭建浅谈(三)--自动化测试框架设计最佳实践
python·自动化
XYN611 小时前
【嵌入式学习6】多任务版TCP服务器
服务器·网络·笔记·python·网络协议·学习·tcp/ip
这里有鱼汤1 小时前
Python 的 bisect 模块:这个冷门宝藏你用对了吗?
前端·后端·python
小小算法师1 小时前
python中的{}
python
这里有鱼汤1 小时前
Python 跨平台路径处理:最优解来了!
前端·后端·python
人类群星闪耀时2 小时前
用Python打造去中心化身份验证系统:迈向更安全的身份未来
python·安全·去中心化
钢铁男儿2 小时前
Python 字典和集合(字典推导)
开发语言·python
非ban必选2 小时前
spring-ai-openai调用Xinference1.4.1报错
java·python·spring