FastAPI请求体参数解析:从基础到高级的学习

FastAPI 请求体参数详解

1. 参数类型

FastAPI 中的参数主要分为以下三种类型:

  • 路径参数(Path Parameters):如果参数出现在路径中,FastAPI 默认将其视为路径参数。
  • 查询参数(Query Parameters):如果单个参数未在路径中出现,默认会被视为查询参数,即使使用 POST 方法也是如此。
  • 请求体参数(Body Parameters):如果参数类型是一个 Pydantic 模型,则该参数会被默认视为请求体参数。
2. 单个请求体参数

要将单个参数作为请求体参数,需要使用 Body 显式声明。

from fastapi import Body, FastAPI
from typing import Annotated

app = FastAPI()

@app.post("/items/")
async def read_item(item_id: Annotated[int, Body()]):
    return {"item_id": item_id}

测试方法:

  • FastAPI 提供的 Docs 界面:在浏览器中访问 /docs,通过界面测试接口。
  • Requests 库
import requests

url = 'http://127.0.0.1:8009/items/'
res = requests.put(url, json=5)
print(res.text)  # 输出:{"item_id":5}

3. 多个请求体参数

当有多个请求体参数时,可以将它们嵌套在一个字典中传递。

from fastapi import Body, FastAPI
from typing import Annotated

app = FastAPI()

@app.post("/items/")
async def read_item(item_id: Annotated[int, Body()], name: Annotated[str, Body()]):
    return {"item_id": item_id, "name": name}

测试方法:

  • Requests 库
url = 'http://127.0.0.1:8009/items/'
data = {"item_id": 5, "name": "张三"}
res = requests.put(url, json=data)
print(res.text)  # 输出:{"item_id":5,"name":"张三"}

4. Pydantic 模型请求体参数

可以直接将 Pydantic 模型作为请求体参数。

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

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

@app.post("/items/")
async def read_item(item: Item):
    return {"name": item.name, "price": item.price}

测试方法:

  • Requests 库
url = 'http://127.0.0.1:8009/items/'
data = {"name": "细胞生物学", "description": "考研书籍", "price": 35.8, "tax": 0.6}
res = requests.post(url, json=data)
print(res.text)  # 输出:{"name":"细胞生物学","price":35.8}

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

可以同时使用路径参数、查询参数和请求体参数。

from fastapi import Body, FastAPI
from typing import Annotated

app = FastAPI()

@app.post("/items/{name}")
async def read_item(name: str, age: int, item_id: Annotated[int, Body()]):
    return {"name": name, "age": age, "item_id": item_id}

测试方法:

  • Requests 库
url = 'http://127.0.0.1:8009/items/张三?age=18'
res = requests.post(url, json=5)
print(res.text)  # 输出:{"name":"张三","age":18,"item_id":5}

6. 多个 Pydantic 模型请求体参数

当函数中有多个 Pydantic 模型参数时,FastAPI 会自动将参数名称作为请求体中的键。

from fastapi import FastAPI
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.post("/items/")
async def read_item(item: Item, user: User):
    return {"name": item.name, "price": item.price, "user": user}

测试方法:

  • Requests 库
url = 'http://127.0.0.1:8009/items/'
data = {
    "item": {"name": "细胞生物学", "description": "考研书籍", "price": 35.8, "tax": 0.6},
    "user": {"username": "张三", "full_name": "张三丰"}
}
res = requests.post(url, json=data)
print(res.text)  # 输出:{"name":"细胞生物学","price":35.8,"user":{"username":"张三","full_name":"张三丰"}}

7. 嵌入单个请求体参数

如果希望将单个 Pydantic 模型参数嵌入到 JSON 的键中,可以使用 Body(embed=True)

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

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

@app.post("/items/")
async def read_item(item: Item = Body(embed=True)):
    return {"name": item.name, "price": item.price}

测试方法:

  • Requests 库
url = 'http://127.0.0.1:8009/items/'
data = {
    "item": {"name": "细胞生物学", "description": "考研书籍", "price": 35.8, "tax": 0.6}
}
res = requests.post(url, json=data)
print(res.text)  # 输出:{"name":"细胞生物学","price":35.8}
8. 总结
  • 路径参数:直接出现在 URL 路径中。
  • 查询参数:通过 URL 的查询字符串传递。
  • 请求体参数:通过 JSON 格式的请求体传递。
  • Pydantic 模型:可以简化复杂的请求体结构,并提供自动校验功能。
  • 混合使用:可以同时使用路径参数、查询参数和请求体参数。

通过以上内容,可以灵活地处理各种类型的参数,满足不同的 API 需求。

FastAPI 额外参数信息详解

1. 核心概念理解
  • 校验与元数据声明:通过Field在数据模型中定义字段约束条件(如数值范围、字符串长度)和描述信息
  • 文档集成机制:所有声明信息会自动转换为OpenAPI规范,驱动交互式文档生成
  • 作用域区分
    • Query/Path/Body
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值