python type_error ai_generated true

FastAPI 响应验证错误:响应内容类型为 'application/json',但期望 'text/plain'

fastapi.exceptions.ResponseValidationError: Response content type is 'application/json' but expected 'text/plain'

ID: python/fastapi-response-model-error

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
0证据数
2024-11-14首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

端点函数返回了 JSON 格式,但 response_model 或 response_class 指定了不匹配的类型。

English

端点函数返回了 JSON 格式,但 response_model 或 response_class 指定了不匹配的类型。

generic

解决方案

  1. 90% 成功率
    from fastapi.responses import JSONResponse
    @app.get('/', response_class=JSONResponse)
    async def read_root():
        return {'message': 'Hello'}
  2. 95% 成功率
    from pydantic import BaseModel
    class Message(BaseModel):
        message: str
    @app.get('/', response_model=Message)
    async def read_root():
        return {'message': 'Hello'}

无效尝试

常见但无效的做法:

  1. 70% 失败

    FastAPI 仍会尝试序列化,可能导致类型错误或内容不符。

  2. 60% 失败

    如果 response_model 期望的是对象,字符串会导致验证失败。