FastAPI 学习之路(九)请求体有多个参数如何处理?

本文介绍使用FastAPI处理带有多个参数的请求体的方法。包括如何定义请求体参数,实现可选参数,以及如何处理多个复杂的请求体参数,并展示了如何通过Body函数添加额外的请求体字段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

请求体有多个参数如何处理?

 别的不多说,我们先写一个需求,然后演示下如何展示。

需求:写一个接口,传递以下参数,书本的名称,描述,价格,打折。

接口返回返回最后的价格

我们去看下代码如何实现

from fastapi import FastAPI
from typing import Optional
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    deacription: Optional[str] = None
    price: float
    tax: Optional[float] = None


@app.put("/items")
def update_item(item: Optional[Item]):
    result = {}
    if item.tax is not None:
        total = item.price * item.tax
        result["price"] = total
        result["name"] = item.name
        return result
    result["price"] = item.price
    result["name"] = item.name
    return result

那么我们测试下,最后是否实现了这个功能,当我们输入所有的参数的时候。

最后是在我们实际的打折上返回的。

          那么我们看下,我们不增加打折如何返回

没有打折就原价返回了名称和价格。

如果默认给了None或者其他内容,这个参数就是可以选择增加或者不增加。但是没有给默认值的时候,就是必须传递的,否则会返回对应的错误,我们可以看下。假如我们不传递价格。

我们可以看到没有默认值的参数就是一个必须的。不然接口会返回对应的错误。

除了声明以上单个的,我们还可以声明多个请求体参数,比如我们可以在之前的需求,增加一个返回,要求返回作者,和作者的朝代。如何实现呢。

from fastapi import FastAPI
from typing import Optional
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    deacription: Optional[str] = None
    price: float
    tax: Optional[float] = None


class User(BaseModel):
    username: str
    year: str


@app.put("/items")
def update_item(item: Optional[Item], user: User):
    result = {}
    if item.tax is not None:
        total = item.price * item.tax
        result["price"] = total
        result["name"] = item.name
        result["user"] = user
        return result
    result["price"] = item.price
    result["name"] = item.name
    result["user"] = user
    return result

那么我们看下接口的请求

当我们增加打折,看下返回结果: 

 我们可以看下接口的返回:

         FastAPI 将自动对请求中的数据进行转换,因此 item 参数将接收指定的内容,user 参数也是如此。

我们要想在增加一个键,在哪里出售,但是要作为请求体的另一个键进行处理,如何 实现呢?

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

app = FastAPI()


class Item(BaseModel):
    name: str
    deacription: Optional[str] = None
    price: float
    tax: Optional[float] = None


class User(BaseModel):
    username: str
    year: str


@app.put("/items")
def update_item(item: Optional[Item], user: User, sell: str = Body(...)):
    result = {}
    if item.tax is not None:
        total = item.price * item.tax
        result["price"] = total
        result["name"] = item.name
        result["user"] = user
        result["sell"] = sell
        return result
    result["price"] = item.price
    result["name"] = item.name
    result["user"] = user
    result["sell"] = sell
    return result

我们可以看到如下

假如我们把参数放在查询内,返回错误

sell参数必须放在body内请求,因为指定了Body。

### FastAPI 请求参数使用指南 在 FastAPI 中,请求参数分为多种类型,包括查询参数、路径参数请求体参数以及表单数据等。以下是关于这些参数的具体说明及其常见问题解决方法。 #### 查询参数 查询参数通常用于过滤或分页等功能。它们可以通过函数签名中的默认值来定义为可选或者必填项。如果未提供任何默认值,则该参数会被视为必需[^1]。 ```python from fastapi import FastAPI app = FastAPI() @app.get("/items/") async def read_items(q: str | None = None): if q: return {"q": q} return {"message": "No query parameter provided"} ``` #### 路径参数 路径参数是指 URL 的一部分作为输入传递给路由处理程序的数据。FastAPI 支持自动类型转换和校验功能,能够确保传入的值符合预期类型[^2]。 ```python @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id} ``` #### 请求体参数 对于复杂的结构化数据(如 JSON),可以利用 Pydantic 模型来自动生成解析逻辑并实施字段级约束条件检查[^4]。 ```python 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.dict() ``` #### 表单数据与文件上传支持 当涉及到 HTML 表单提交时,需特别注意区分 `application/x-www-form-urlencoded` 和 multipart/form-data 编码方式下的不同处理手法[^5]。 ```python from fastapi import File, UploadFile @app.post("/uploadfile/") async def upload_file(file: UploadFile = File(...)): contents = await file.read() # Read the content of the uploaded file. return {"filename": file.filename, "content_type": file.content_type} ``` #### 自动依赖注入系统 FastAPI 提供了一个强大的依赖注入框架,允许开发者轻松实现跨层资源共享和服务实例管理而无需手动编写繁琐代码片段[^3]。 --- ### 常见问题解答 1. **为什么我的浮点数总是被截断成整数?** 需确认是否正确设置了相应变量类型的注解;例如应采用 `float` 类型而非隐式推导为 `int`. 2. **如何捕获非法输入引发的异常并向客户端反馈更友好的消息?** 可借助于自定义 Exception Handlers 来完成此目标. 3. **能否在一个单一端点同时接收多个来源的数据比如 Query String 加 Body Payload?** 是完全可以做到这一点只需按照常规语法分别声明各部分所需参数即可. ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值