You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI路由中Pydantic自定义类型无法设为可选的问题

解决FastAPI中自定义Pydantic类型可选参数必填问题

问题根源

你遇到的问题有两个核心原因:

  1. 自定义的CommaSeparatedString类型未处理None输入的验证逻辑,Pydantic默认会拒绝None值
  2. FastAPI中仅标注CommaSeparatedString | None还不够,必须给参数设置默认值None,否则框架仍会将其视为必填字段

修复步骤

1. 修改自定义类型,兼容None验证

调整CommaSeparatedString的核心schema定义,允许None作为有效值,同时保留字符串转列表的逻辑:

from pydantic_core import core_schema
from pydantic import GetCoreSchemaHandler
from typing import Any, Optional

class CommaSeparatedString(list[str]):
    @classmethod
    def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
        # 同时支持None和字符串输入
        return core_schema.union_schema([
            core_schema.none_schema(),
            core_schema.no_info_wrap_validator_function(
                cls.validate,
                core_schema.str_schema(),
            )
        ])
    
    @classmethod
    def validate(cls, v: str) -> list[str]:
        return v.split(',')

或者另一种写法,在验证函数中直接处理None:

from pydantic_core import core_schema
from pydantic import GetCoreSchemaHandler
from typing import Any, Optional

class CommaSeparatedString(list[str]):
    @classmethod
    def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
        return core_schema.no_info_wrap_validator_function(
            cls.validate,
            core_schema.union_schema([core_schema.none_schema(), core_schema.str_schema()]),
        )
    
    @classmethod
    def validate(cls, v: Optional[str]) -> Optional[list[str]]:
        if v is None:
            return None
        return v.split(',')

2. 在FastAPI路由中设置默认值

路由参数必须加上= None,明确告知框架该参数是可选的:

from fastapi import FastAPI

app = FastAPI()

@app.get("/test")
async def get_items(tags: CommaSeparatedString | None = None):
    return {"tags": tags}

这样修改后,当请求不携带tags查询参数时,接口会正常返回{"tags": null},不会再提示"field required"。

内容的提问来源于stack exchange,提问作者LondonRob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 04:50:07