问题背景
在使用FastAPI开发API接口时,Response方法是构建自定义响应的核心工具。许多开发者会遇到返回JSON数据时的编码错误,特别是当响应包含非ASCII字符(如中文、表情符号)或复杂数据结构时。这类问题通常表现为:
- 服务器抛出
UnicodeEncodeError异常 - 客户端接收到的JSON数据出现乱码
- 特殊字符被错误转义
- Content-Type头部缺失或错误
根本原因分析
JSON编码问题通常源于三个层面:
- 字符编码不匹配:Python默认使用UTF-8编码,但某些场景下可能被覆盖
- 序列化配置不当:FastAPI的默认JSON编码器对复杂数据类型(如datetime、Decimal)处理不足
- 响应头配置错误:缺少
Content-Type: application/json; charset=utf-8头部
解决方案
方法1:显式指定编码参数
from fastapi import FastAPI, Response
import json
app = FastAPI()
@app.get("/data")
async def get_data():
data = {"message": "你好世界", "value": 3.14159}
return Response(
content=json.dumps(data, ensure_ascii=False),
media_type="application/json; charset=utf-8"
)
方法2:自定义JSON响应类
from fastapi.responses import JSONResponse
@app.get("/custom-json")
async def custom_json():
return JSONResponse(
content={"emoji": "