FastAPI混合表单与文件上传中如何设置可选Form字段?
解决FastAPI混合表单字段与文件上传中可选字段的问题
要将表单字段设为可选,核心是在Form()中显式指定default=None,而非仅通过类型声明Union[str, None]或Optional[str]标记。以下是正确实现方式:
正确写法1:Union + Form(default=None)
@router.post("/upload") async def upload_contents( an_int: Annotated[int, Form()], a_string: Annotated[Union[str, None], Form(default=None)], some_files: Annotated[list[UploadFile], File()] ): # 业务处理逻辑 return {"an_int": an_int, "a_string": a_string, "uploaded_files": len(some_files)}
正确写法2:Optional + Form(default=None)
from typing import Optional @router.post("/upload") async def upload_contents( an_int: Annotated[int, Form()], a_string: Annotated[Optional[str], Form(default=None)], some_files: Annotated[list[UploadFile], File()] ): # 业务处理逻辑 return {"an_int": an_int, "a_string": a_string, "uploaded_files": len(some_files)}
原写法无效的原因
- 写法一仅声明了
Union[str, None]类型,但未给Form()设置默认值。FastAPI默认将表单字段视为必填项,因此仍会强制要求客户端提供a_string。 - 写法二存在语法错误(括号配对错误),且同样未设置
default=None,即便修正语法,也无法将字段设为可选。
FastAPI中,表单字段的必填性由Form()的default参数直接控制——只要显式设置default=None,无论类型是Union还是Optional,该字段都会变为可选。
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

