FastAPI GET接口接收List/Numpy数组及参数传递问题求助
FastAPI GET接口参数问题解决方案
问题1:接收List和numpy数组时出现422错误
原因分析
- GET请求无请求体,未指定位置的参数会被FastAPI默认解析为请求体参数,导致报错
field required。 np.ndarray无法直接作为HTTP查询参数,因为查询参数本质是字符串,无法直接映射为numpy数组类型。
修正后的API代码
import numpy as np from typing import List from fastapi import Query, FastAPI appOne = FastAPI() @appOne.get("/sabr/funcThree") def funcThree(x1: List[float] = Query(...), x2: List[float] = Query(...)): # 接口内部将列表转为numpy数组 x2_np = np.array(x2) # 返回时转成列表避免序列化问题 return {"x1": x1, "x2": x2_np.tolist()}
修正后的调用代码
import requests import numpy as np url_ = "http://127.0.0.1:8000/sabr/" func_ = "funcThree" items = [1, 2, 3, 4, 5] x2_arr = np.array([3, 100]) # GET参数放在params中,numpy数组转成列表传递 params = {"x1": items, "x2": x2_arr.tolist()} resp = requests.get(url_ + func_, params=params) print(resp.json())
问题2:type_参数传递不生效
原因分析
- GET请求不会解析请求体中的JSON数据,用
requests.get(..., json=params)传递参数,FastAPI无法获取到type_,只会使用默认值1。 - 字典中重复的
type_键会被覆盖,核心问题是参数传递方式错误。
修正后的调用代码
import requests url_ = "http://127.0.0.1:8000/sabr/" func_ = "calib_test2" item1 = [1, 2, 3, 4, 5] item2 = [4, 5, 6, 7, 8] all_ = url_ + func_ # GET参数必须放在params中,而非json参数 params = {"x1": item1, "x2": item2, "type_": 2} resp = requests.get(all_, params=params) print(resp.json())
可选优化:显式标记API参数为Query
显式标记参数位置,代码可读性更强:
import numpy as np from typing import List from fastapi import Query, FastAPI app = FastAPI() @app.get("/sabr/calib_test2") def calib_test2( x1: List[float] = Query(default=[1, 2, 3]), x2: List[float] = Query(default=[4, 5, 6]), type_: int = Query(default=1) ): s1 = np.array(x1) s2 = np.array(x2) if type_ == 1: return {"x1": x1, "x1_sum": s1.sum(), "x2": x2, "x2_sum": s2.sum(), "size_x1": s1.shape} elif type_ == 2: return ['test', x1, s1.sum(), x2, s2.sum(), s1.shape] else: return [0, 0, 0]
内容的提问来源于stack exchange,提问作者Kiann
相关产品推荐
相关产品推荐

