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

FastAPI通过Swagger传递List类型Form数据时出现422错误求助

解决FastAPI表单传递分辨率列表的422错误

问题根源

  1. Python 3.8不支持原生list[int]的泛型写法,必须使用typing.List[int],否则FastAPI无法正确识别列表类型。
  2. Swagger UI传递Form列表时,若在单个输入框填写逗号分隔的字符串(如"1080,720"),FastAPI会把整个字符串当成列表的单个元素,无法转换为整数,从而触发类型错误。

修正代码(标准列表传参)

首先导入typing.List,正确声明Form参数类型:

from typing import List
from fastapi import FastAPI, Form, HTTPException

app = FastAPI(title="视频转码API")

@app.post("/transcode-video")
async def transcode_video(
    video_file: bytes = Form(...),
    resolutions: List[int] = Form(...)
):
    # 可选:验证分辨率合理性
    valid_resolutions = [360, 480, 720, 1080, 2160]
    for res in resolutions:
        if res not in valid_resolutions:
            raise HTTPException(status_code=400, detail=f"无效分辨率:{res},支持的分辨率为{','.join(map(str, valid_resolutions))}")
    
    # 执行转码逻辑
    return {"message": "转码任务已启动", "target_resolutions": resolutions}

Swagger UI正确传参步骤

在Swagger UI的表单页面:

  • 找到resolutions字段,点击Add item按钮多次,每个输入框单独填写一个整数分辨率(如1080、720)。
  • 不要在单个输入框中填写逗号分隔的字符串,否则会触发类型转换错误。

兼容逗号分隔输入的备选方案

如果需要支持用户直接输入逗号分隔的字符串(避免多次点击添加项),可以将参数声明为字符串,自行解析转换:

from fastapi import FastAPI, Form, HTTPException

app = FastAPI(title="视频转码API")

@app.post("/transcode-video")
async def transcode_video(
    video_file: bytes = Form(...),
    resolutions_str: str = Form(...)
):
    try:
        resolutions = [int(res.strip()) for res in resolutions_str.split(",")]
    except ValueError:
        raise HTTPException(status_code=400, detail="分辨率格式错误,请输入逗号分隔的整数,如'1080,720'")
    
    # 验证分辨率
    valid_resolutions = [360, 480, 720, 1080, 2160]
    for res in resolutions:
        if res not in valid_resolutions:
            raise HTTPException(status_code=400, detail=f"无效分辨率:{res},支持的分辨率为{','.join(map(str, valid_resolutions))}")
    
    return {"message": "转码任务已启动", "target_resolutions": resolutions}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 23:47:37