当前位置:   article > 正文

【FastAPI】请求体(二)_fastapi query body 同时使用

fastapi query body 同时使用

混合使用 Path、Query 和请求体参数

混合使用 Path、Query 和请求体参数是相当简单的,FastAPI提供了直观的方式来定义和处理这些参数。以下是一个简单的例子,演示了如何在 FastAPI 中混合使用这三种类型的参数:
from fastapi import FastAPI, Path, Query, Body

app = FastAPI()

class UserInfo:
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age

.put("/update_user/{user_id}")
async def update_user(
    user_id: int = Path(..., title="The ID of the user", ge=1),
    status: str = Query(..., title="The status of the user", description="Set the status of the user"),
    user_info: UserInfo = Body(..., title="User information", description="The new information for the user")
):
    # Your update logic here
    return {"user_id": user_id, "status": status, "user_info": user_info.__dict__}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

user_id 是 Path 参数,它必须是正整数。
status 是 Query 参数,它是一个字符串,不能为空。
user_info 是请求体参数,它是一个自定义的类 UserInfo 的实例,包含了用户的新名称和年龄。
FastAPI 会根据这些参数的类型和注解,自动进行验证和转换。在实际请求中,你可以使用类似以下的请求:

PUT http://127.0.0.1:8000/update_user/42?status=active

{
  "name": "New John",
  "age": 26
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

请求体中的数据是以 JSON 格式发送的

详解Path和Query

Path 和 Query 是用于处理 HTTP 请求中的路径参数和查询参数的工具。它们提供了一种声明式的方式,使得定义和验证这些参数变得非常简单。

Path 参数

Path 用于声明路径参数,也就是 URL 中的一部分。在 FastAPI 中,你可以使用 Path 类型来指定路径参数的类型,并添加其他的验证条件。

from fastapi import FastAPI, Path

app = FastAPI()

.get("/items/{item_id}")
async def read_item(item_id: int = Path(..., title="The ID of the item", ge=1)):
    return {"item_id": item_id}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

item_id 是路径参数,Path(…, title=“The ID of the item”, ge=1) 表示它是一个必须为正整数的路径参数。… 表示这个参数是必需的。

Query 参数

Query 用于声明查询参数,也就是 URL 中通过 ? 传递的参数。与 Path 类似,你可以使用 Query 类型来指定查询参数的类型,并添加其他的验证条件。

from fastapi import FastAPI, Query

app = FastAPI()

.get("/items/")
async def read_item(skip: int = Query(0, title="Skip items", ge=0), limit: int = Query(10, title="Limit items", le=100)):
    return {"skip": skip, "limit": limit}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

在这个例子中,skip 和 limit 是查询参数,它们都有默认值,并且通过 Query(0, title=“Skip items”, ge=0) 和 Query(10, title=“Limit items”, le=100) 进行了验证。ge 表示大于等于,le 表示小于等于。

总之

Path 参数 是通过 URL 路径传递的参数,使用 Path 类型进行声明。
Query 参数 是通过 URL 查询字符串传递的参数,使用 Query 类型进行声明。
通过使用这些声明式的方式,FastAPI 不仅可以进行参数的类型转换,还能自动进行验证和文档生成。
在 FastAPI 中,这些声明式的参数处理方式不仅简化了代码,还提供了更好的类型提示和验证机制,使得 API 的开发更加方便和可靠。

我的博客即将同步至腾讯云开发者社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=3ipthahvucqok

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/416540
推荐阅读
相关标签
  

闽ICP备14008679号