在FastAPI中,可以使用response_model参数来指定不同的内容类型。例如,可以使用response_model参数来指定返回JSON格式的数据:
from fastapi import FastAPIfrom pydantic import BaseModelapp = 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 FastAPIfrom fastapi.responses import HTMLResponseapp = FastAPI()@app.get("/", response_class=HTMLResponse)async def read_root(): return "<h1>Hello, World!</h1>"在上面的例子中,response_class=HTMLResponse指定了返回的数据格式为HTML格式。FastAPI会自动将返回的数据转换为HTML格式。


