FastAPI如何实现路径参数支持固定字符串或任意整数的自动校验?
实现方案
有两种完全不需要手动编写业务侧校验逻辑的优雅实现方式:
方案1:自定义Pydantic类型(推荐多合法字符串场景)
利用Pydantic的前置校验器封装校验逻辑,直接在接口参数上声明类型即可,所有校验规则自动生效。
from fastapi import FastAPI from pydantic import BeforeValidator from typing import Annotated, Union # 封装version校验逻辑 def parse_version(v: str) -> Union[str, int]: if v == "active": return v try: return int(v) except ValueError: raise ValueError("version只能是'active'或合法整数") # 自定义Version类型 Version = Annotated[Union[str, int], BeforeValidator(parse_version)] app = FastAPI() # 接口直接使用自定义类型,无需额外处理 @app.get("/{version}") def endpoint(version: Version): return {"version": version}
效果说明:
- 请求
/active:自动校验通过,version值为字符串"active" - 请求
/1//123:自动校验通过,version值为对应整数 - 请求
/abc//12.3等非法值:自动返回422参数校验错误,无需手动处理返回
方案2:拆分路由(推荐仅少量固定合法字符串场景)
利用FastAPI内置的路径匹配规则和整型参数校验能力,拆分两个路由即可自动完成匹配校验,连自定义类型都不需要编写。
from fastapi import FastAPI app = FastAPI() # 匹配固定字符串路径 @app.get("/active") def endpoint_active(): return {"version": "active"} # 匹配整型路径参数,自动校验是否为整数 @app.get("/{version:int}") def endpoint_int(version: int): return {"version": version}
效果说明:
- 请求
/active自动走第一个接口 - 请求
/1//123等整数路径自动走第二个接口 - 其他非法路径自动返回404,完全不需要额外校验代码
内容的提问来源于stack exchange,提问作者stasiekz
相关产品推荐
相关产品推荐

