FastAPI中怎么处理不同的内容类型

1955
2024/5/22 16:35:53
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在FastAPI中,可以使用response_model参数来指定不同的内容类型。例如,可以使用response_model参数来指定返回JSON格式的数据:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str

@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int):
    return {"name": "Foo", "description": "This is a test item"}

在上面的例子中,response_model=Item指定了返回的数据格式为Item类,这样FastAPI会自动将返回的数据转换为JSON格式。

如果要指定其他的内容类型,可以使用response_class参数来指定。例如,可以使用response_class=HTMLResponse来返回HTML格式的数据:

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()

@app.get("/", response_class=HTMLResponse)
async def read_root():
    return "<h1>Hello, World!</h1>"

在上面的例子中,response_class=HTMLResponse指定了返回的数据格式为HTML格式。FastAPI会自动将返回的数据转换为HTML格式。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: FastAPI中怎么实现API的可解释性