在 FastAPI 中,你可以使用响应模型、响应头等参数来自定义响应头。以下是一些示例:

1. 返回带有自定义响应头的 JSON 响应:
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get("/items/")
async def read_items():
    content = {"message": "Read all items"}
    headers = {"X-Custom-Header": "value"}
    return JSONResponse(content=content, headers=headers)

在这个例子中,我们使用 JSONResponse 返回 JSON 响应,并使用 headers 参数来指定自定义的响应头。

2. 返回带有响应头的 HTML 响应:
from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()

@app.get("/items/", response_class=HTMLResponse)
async def read_items():
    content = "<html><body><h1>Read all items</h1></body></html>"
    headers = {"X-Custom-Header": "value"}
    return HTMLResponse(content=content, headers=headers)

在这个例子中,我们使用 HTMLResponse 返回 HTML 响应,并使用 headers 参数来指定自定义的响应头。

3. 使用响应模型和响应头:
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse

app = FastAPI()

class ItemResponseModel:
    message: str
    additional_info: str

@app.get("/items/", response_model=ItemResponseModel)
async def read_items():
    content = {"message": "Read all items", "additional_info": "Some additional info"}
    headers = {"X-Custom-Header": "value"}
    return JSONResponse(content=content, headers=headers)

在这个例子中,我们使用了一个响应模型 ItemResponseModel,并且在路径操作中通过返回 JSONResponse 设置了响应头。

这些示例演示了在 FastAPI 中如何返回带有响应头的响应。你可以根据实际需求使用这些参数来自定义响应。


转载请注明出处:http://www.zyzy.cn/article/detail/7411/FastAPI