python type_error ai_generated true

FastAPI错误:响应字段参数无效

fastapi.exceptions.FastAPIError: Invalid args for response field 'items'

ID: python/fastapi-query-param-missing-annotation

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

版本兼容性

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

根因分析

在响应模型中定义没有类型注解或无效注解的字段(如`items = []`未指定`List[Item]`),FastAPI在生成响应模式时会失败。

English

Defining a response model with a field that has no type annotation or an invalid one (e.g., `items = []` without `List[Item]`) causes FastAPI to fail when generating the response schema.

generic

解决方案

  1. 95% 成功率
    Define the response model with proper type hints: `from typing import List; class ResponseModel(BaseModel): items: List[Item]`
  2. 90% 成功率
    Use `response_model=List[Item]` in the route decorator instead of a custom model.

无效尝试

常见但无效的做法:

  1. 80% 失败

    Adding a default value like `items: list = []` still fails if the list type is not specified; FastAPI needs `List[SomeModel]`.

  2. 70% 失败

    Using `items: Any` works but loses validation and may not be what you want.