FastAPI表单JSON字段验证报错:需为str/bytes/bytearray类型
问题原因
你遇到的错误本质是FastAPI与Pydantic的类型解析逻辑冲突:
- 当你在Form参数中使用
Json[List[Foo]]类型时,FastAPI会自动把表单里的字符串值解析成对应的Python对象(也就是List[Foo]实例)。 - 但Pydantic的
Json类型要求输入必须是原始的JSON格式字符串/字节,而不是已经解析好的Python对象,因此触发了类型错误。
解决方案
有两种简单的修复方式:
方式一:手动解析表单字符串(推荐)
移除Json类型,直接接收字符串参数,手动解析后传入模型:
import json from typing import Optional, List from fastapi import Form from pydantic import BaseModel class Foo(BaseModel): a: str class Bar(BaseModel): any_field: Optional[List[Foo]] @classmethod def as_form( cls, any_field: Optional[str] = Form(None), ) -> "Bar": parsed_data = None if any_field: # 解析JSON字符串并转换为Foo实例列表 parsed_data = [Foo(**item) for item in json.loads(any_field)] return cls(any_field=parsed_data)
方式二:让Pydantic自动解析字符串
如果想保留Pydantic的自动验证,可以把模型字段改为Json[List[Foo]],同时Form参数接收字符串类型:
from typing import Optional, List from fastapi import Form from pydantic import BaseModel, Json class Foo(BaseModel): a: str class Bar(BaseModel): # 模型字段改为Json类型,自动解析字符串 any_field: Optional[Json[List[Foo]]] = None @classmethod def as_form( cls, any_field: Optional[str] = Form(None), ) -> "Bar": return cls(any_field=any_field)
这样Pydantic会自动把传入的字符串解析为List[Foo],同时符合类型要求。
内容的提问来源于stack exchange,提问作者x1netta
相关产品推荐
相关产品推荐

