FastAPI请求体-多个参数

路径参数、查询参数,和请求体混合

首先,我们需要导入所需的库。我们将使用FastAPI、Path和Annotated来处理路由和参数,并使用BaseModel和Union来自定义数据模型。

完整示例代码

from typing import Annotated, Union

from fastapi import FastAPI, Path
from pydantic import BaseModel

app = FastAPI()


class Book(BaseModel):
    title: str
    author: Union[str, None] = None
    pages: int


@app.put("/books/{book_id}")
async def update_book(
        book_id: Annotated[int, Path(title="The ID of the book to get", ge=0, le=1000)],
        q: Union[str, None] = None,
        book: Union[Book, None] = None,
):
    results = {"book_id": book_id}
    if q:
        results.update({"q": q})
    if book:
        results.update({"book": book})
    return results

代码分析

class Book(BaseModel):
    title: str
    author: Union[str, None] = None
    pages: int

定义一个自定义的数据模型类。在这个例子中,我们将创建一个名为Book的类,它包含以下字段:title(字符串)、author(字符串,可选)和pages(整数):

接下来,我们定义一个带有查询参数和路径参数的路由。这个路由将用于更新一本书的信息:

@app.put("/books/{book_id}")
async def update_book(
    book_id: Annotated[int, Path(title="The ID of the book to get", ge=0, le=1000)],
    q: Union[str, None] = None,
    book: Union[Book, None] = None,
):
    results = {"book_id": book_id}
    if q:
        results.update({"q": q})
    if book:
        results.update({"book": book})
    return results

在这个例子中,我们定义了一个PUT请求的路由,其路径为"/books/{book_id}"。我们使用了Path对象来指定路径参数book_id的约束条件:大于等于0且小于等于1000。

我们还添加了一个名为q的查询参数,它可以是字符串或None。

最后,我们添加了一个名为book的参数,它可以是一个Book对象或None。这个参数允许用户在请求体中传递书籍的详细信息。

打开自动化测试文档,我们可以看到如下内容
在这里插入图片描述
发起请求进行测试
在这里插入图片描述

总结

通过使用FastAPI、Path和Annotated,你可以轻松地定义具有复杂参数的路由。同时,使用Pydantic的BaseModel可以让你更方便地定义数据模型并自动进行数据验证。

多个请求体

完整示例代码

from typing import Union

from fastapi import FastAPI, Body
from pydantic import BaseModel


class Product(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None


class Customer(BaseModel):
    username: str
    full_name: Union[str, None] = None


app = FastAPI()


@app.put("/products/{product_id}")
async def update_product(product_id: int, product: Product = Body(...), customer: Customer = Body(...)):
    results = {"product_id": product_id, "product": product, "customer": customer}
    return results

这段代码定义了一个FastAPI应用,该应用可以处理一个PUT请求,这个请求包含了商品信息和客户信息。下面是对这段代码的详细解释。

首先,我们导入了所需的库:

from typing import Union

from fastapi import FastAPI, Body
from pydantic import BaseModel

然后,我们定义了两个模型类:Product和Customer:

class Product(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None


class Customer(BaseModel):
    username: str
    full_name: Union[str, None] = None

这两个类分别代表商品和客户。它们都是BaseModel的子类,这意味着它们可以被用于解析JSON数据。

接下来,我们创建了一个FastAPI应用实例:

app = FastAPI()

最后,我们编写了一个路由处理器函数:update_product:

@app.put("/products/{product_id}")
async def update_product(product_id: int, product: Product = Body(...), customer: Customer = Body(...)):
    results = {"product_id": product_id, "product": product, "customer": customer}
    return results

这个函数接收三个参数:商品ID、商品和客户。其中,商品和客户是通过Body装饰器从请求体中获取的。当客户端发起PUT请求到"/products/{product_id}"时,FastAPI会自动将请求体中的JSON数据转换为Product和Customer对象。

嵌套参数

from typing import Annotated, Union

from fastapi import Body, FastAPI
from pydantic import BaseModel

app = FastAPI()


class Book(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None


@app.put("/books/{book_id}")
async def update_book(book_id: int, book: Annotated[Book, Body(embed=True)]):
    results = {"book_id": book_id, "book": book}
    return results

效果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

micro_cloud_fly

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值