FastAPI GET接口传列表参数遇422错误,求curl调用解决方案
解决FastAPI GET接口422 Unprocessable Entity错误
问题根源
- 参数定义矛盾:
card_no被注释为可选参数,但代码中未设置默认值,FastAPI将其判定为必填参数,导致请求时因参数解析规则不匹配报错。 - GET列表参数传递方式错误:FastAPI默认要求GET请求的列表类型参数通过重复参数名传递,当前curl仅传单个
card_no值,且参数必填性设置错误,触发解析失败。
解决方案
1. 修正接口参数定义
将card_no设置为可选参数,添加默认值None,与注释逻辑保持一致:
@app.get("/fetch-data/") def fetch_data( month: str, # Mandate filter: execution month (yyyy/mm/dd) card_no: list[int] = None, # 添加默认值,转为可选参数 schema_order: list[str] = None, # Input schema_order (optional) ): try: # 数据库查询逻辑保持不变 db = SessionLocal() query = db.query(CardData).filter(CardData.month == month) if card_no: query = query.filter(CardData.card_no.in_(card_no)) data = query.all() # 输出处理逻辑保持不变 if schema_order: output = [{col: getattr(item, col) for col in schema_order} for item in data] else: output = [item.dict() for item in data] return output except Exception as e: raise HTTPException(status_code=500, detail=f"Error fetching data: {str(e)}")
2. 调整curl请求格式
根据FastAPI的列表参数解析规则,有两种合法传递方式:
方式一:重复参数名(推荐)
单个卡号传递:
curl -X "GET" "http://127.0.0.1:8000/fetch-data/?month=2024-01-06&card_no=123456789"
多个卡号传递:
curl -X "GET" "http://127.0.0.1:8000/fetch-data/?month=2024-01-06&card_no=123456789&card_no=987654321"
方式二:启用逗号分隔解析(可选)
若想支持逗号分隔的列表格式,需通过Query装饰器配置参数:
from fastapi import Query @app.get("/fetch-data/") def fetch_data( month: str, card_no: list[int] = Query(None, description="Optional filter: list of card numbers"), schema_order: list[str] = None, ): # 原有逻辑不变
此时curl可这样请求:
# 单个卡号 curl -X "GET" "http://127.0.0.1:8000/fetch-data/?month=2024-01-06&card_no=123456789" # 多个卡号 curl -X "GET" "http://127.0.0.1:8000/fetch-data/?month=2024-01-06&card_no=123456789,987654321"
注意:GET请求无需添加
Content-Type: application/json请求头,可直接去掉该配置,避免不必要的解析干扰。
内容的提问来源于stack exchange,提问作者abinash thakur
相关产品推荐
相关产品推荐

