在FastAPI中设置响应头有多种方式,具体取决于需求和场景。以下是详细说明:
1. 直接在返回值中设置响应头(推荐)
适用场景:简单响应,无需自定义响应类。
示例代码:
python
Copy Code
from fastapi import FastAPI, Response
app = FastAPI()
@app.get("/custom-header")
async def custom_header(response: Response):
response.headers["X-Custom-Header"] = "Custom Value"
return {"message": "Check the headers"}
说明:通过在视图函数中直接操作response.headers字典,添加自定义头。FastAPI会自动处理响应体和状态码。
2. 使用Response类显式控制
适用场景:需要完全控制响应格式(如状态码、内容类型)。
示例代码:
python
Copy Code
from fastapi import FastAPI, Response
app = FastAPI()
@app.get("/custom-response")
async def custom_response():
content = '{"message": "Hello World"}'
headers = {"X-Custom-Header": "custom-value"}
return Response(
content=content,
media_type="application/json",
headers=headers,
status_code=201
)
说明:通过Response类显式设置content、headers和status_code,适用于需要自定义响应格式的场景。
3. 使用JSONResponse简化JSON响应
适用场景:返回JSON数据时,自动处理序列化。
示例代码:
python
Copy Code
from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI()
@app.get("/json-response")
async def json_response():
return JSONResponse(
content={"message": "Hello World"},
status_code=201,
headers={"X-Custom-Header": "custom-value"}
)
说明:JSONResponse是Response的子类,专门用于JSON响应,简化了序列化过程。
4. 全局错误处理中添加响应头
适用场景:自定义错误响应时添加额外头信息。
示例代码:
python
Copy Code
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import JSONResponse
app = FastAPI()
@app.exception_handler(HTTPException)
async def unicorn_exception_handler(request: Request, exc: HTTPException):
return JSONResponse(
status_code=exc.status_code,
content={"message": exc.detail},
headers={"X-Custom-Header": "Error-Info"}
)
说明:在异常处理器中通过JSONResponse的headers参数添加自定义头。
5. 注意事项
大小写敏感性:HTTP头是大小写不敏感的,但FastAPI默认将下划线转换为连字符(如x_custom_header → x-custom-header)。若需保留下划线,可设置convert_underscores=False。
重复头处理:若需处理重复头(如X-Custom-Header有多个值),可使用List[str]类型声明:
python
Copy Code
from fastapi import FastAPI, Header
from typing import List
app = FastAPI()
@app.get("/multi-headers")
async def multi_headers(x_custom_header: List[str] = Header(None)):
return {"headers": x_custom_header}
总结
FastAPI通过多种方式灵活设置响应头,推荐优先使用直接操作response.headers的方式,结合Response或JSONResponse类可实现更精细控制。