如何通过Request向FastAPI传递参数列表?422错误排查
问题解决:FastAPI接收列表查询参数返回422错误
错误原因
你提到Python会忽略类型注解,但FastAPI完全依赖类型注解做参数解析和校验。直接用list作为查询参数类型时,FastAPI无法确定列表元素的具体类型,导致无法正确解析请求中的多个test_param参数,从而返回422错误。另外你接口返回值里的{"message": test}也存在问题——test是函数本身,应该返回接收的test_param参数。
修正后的FastAPI代码
方法1:兼容Python3.8及以下版本
#!/usr/bin/env python3 from fastapi import FastAPI, Query from fastapi.responses import JSONResponse from typing import List import uvicorn app = FastAPI() @app.get("/test") def test(test_param: List[int] = Query(...)): return JSONResponse(content={"message": test_param}) if __name__ == "__main__": uvicorn.run("minimal:app", host="0.0.0.0", port=8000, workers=2)
方法2:使用Python3.9+原生泛型语法
#!/usr/bin/env python3 from fastapi import FastAPI, Query from fastapi.responses import JSONResponse import uvicorn app = FastAPI() @app.get("/test") def test(test_param: list[int] = Query(...)): return JSONResponse(content={"message": test_param}) if __name__ == "__main__": uvicorn.run("minimal:app", host="0.0.0.0", port=8000, workers=2)
关键说明
Query(...)用于明确声明这是查询参数,还可以添加默认值、描述等配置(比如Query(..., description="传入的整数列表"));如果不需要额外配置,直接写test_param: List[int],FastAPI也能正确解析。- 你的requests发送代码是正确的,requests会自动将
{"test_param": [1,2,3]}转换为test_param=1&test_param=2&test_param=3的URL参数格式,符合HTTP查询参数传递列表的标准方式。
内容的提问来源于stack exchange,提问作者Xaver
相关产品推荐
相关产品推荐

