推荐答案
在 FastAPI 中,返回 JSON 响应非常简单。你可以直接返回一个 Python 字典、Pydantic 模型或其他可序列化的对象,FastAPI 会自动将其转换为 JSON 格式并返回给客户端。
// www.javascriptcn.com code example
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int):
return {"item_id": item_id, "name": "Foo", "price": 50.0}在这个例子中,read_item 函数返回一个字典,FastAPI 会自动将其转换为 JSON 响应。
本题详细解读
1. 返回字典
FastAPI 允许你直接返回一个 Python 字典,它会自动将字典转换为 JSON 格式。例如:
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id, "name": "Foo", "price": 50.0}2. 返回 Pydantic 模型
如果你使用了 Pydantic 模型,FastAPI 会自动将模型实例转换为 JSON 格式。例如:
// www.javascriptcn.com code example
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int):
return Item(name="Foo", price=50.0)3. 自定义 JSON 响应
如果你需要自定义 JSON 响应,可以使用 JSONResponse 类:
from fastapi.responses import JSONResponse
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return JSONResponse(content={"item_id": item_id, "name": "Foo", "price": 50.0})4. 返回列表
你也可以返回一个列表,FastAPI 会自动将其转换为 JSON 数组:
@app.get("/items/")
async def read_items():
return [{"name": "Foo", "price": 50.0}, {"name": "Bar", "price": 30.0}]5. 返回其他可序列化对象
FastAPI 支持返回任何可序列化为 JSON 的对象,例如 list、dict、str、int、float、bool 等。
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id, "name": "Foo", "price": 50.0, "is_available": True}通过这些方式,你可以轻松地在 FastAPI 中返回 JSON 响应。