python type_error ai_generated true

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

ID: python/fastapi-response-model-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-11-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 70% fail

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

  2. 60% fail

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