1. 创建 FastAPI 应用
确保你已经创建了一个 FastAPI 应用。可以使用以下代码创建一个简单的应用:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
2. 定义请求体模型
使用 Pydantic 模型来定义请求体的结构,这将帮助你验证和处理传递的 JSON 数据。
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
在这个例子中,我们定义了一个名为 Item 的 Pydantic 模型,包含了 name、description、price 和 tax 字段。
3. 使用请求体
在路由函数的参数列表中使用请求体模型,以接收客户端发送的 JSON 数据。
from fastapi import HTTPException
@app.post("/items/")
def create_item(item: Item):
if item.price < 0:
raise HTTPException(status_code=400, detail="Price must be greater than or equal to 0")
total_price = item.price + (item.tax or 0)
return {"item": item, "total_price": total_price}
在这个例子中,我们使用 Item 模型作为 create_item 函数的参数。FastAPI 会自动解析请求体中的 JSON 数据,并将其转换为 Item 类型的对象。
4. 使用请求体数据
通过发送 POST 请求,并传递 JSON 数据,来测试我们的创建项目的路由。
curl -X POST -H "Content-Type: application/json" -d '{"name": "item1", "price": 10.5}' http://127.0.0.1:8000/items/
或者使用 httpie:
http POST http://127.0.0.1:8000/items/ name=item1 price:=10.5
你应该得到一个类似以下的响应:
{
"item": {
"name": "item1",
"description": null,
"price": 10.5,
"tax": null
},
"total_price": 10.5
}
5. 请求体的额外设置
你可以在请求体中进行额外的设置,例如:
- embed 参数: 将请求体的 JSON 数据嵌套在请求参数中。
- media_type 参数: 指定请求体的媒体类型。
@app.post("/items/", response_model=Item)
async def create_item(item: Item, embed: bool = False, media_type: str = "application/json"):
if embed:
return {"item": item, "embed_data": {"extra_data": "embedded"}}
return {"item": item}
在上述例子中,我们指定了 response_model 以指示 FastAPI 在响应中返回与请求体相同的数据结构。此外,我们添加了 embed 和 media_type 参数,以展示一些额外的设置。
总结
使用请求体,你可以轻松地接收和处理客户端发送的 JSON 数据。FastAPI 提供了强大的 Pydantic 模型和内置的 JSON 解析功能,使得处理请求体变得简单而直观。在 FastAPI 文档中可以找到更多关于请求体的详细信息和用法示例。
转载请注明出处:http://www.zyzy.cn/article/detail/7363/FastAPI