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

FastAPI实现Product+文件上传接口时触发422错误求助

问题原因与解决方案

错误根源

当接口同时包含File和Pydantic模型参数时,FastAPI会自动将请求解析为multipart/form-data编码格式,而非默认的application/json。此时直接声明product: Product参数,FastAPI无法从表单数据中正确解析出符合Product模型的字典结构,因此抛出value is not a valid dict错误。

修正代码

需要将product参数通过Form接收为JSON字符串,再手动解析为Product模型,同时添加文件保存逻辑:

from fastapi import FastAPI, File, UploadFile, Depends, Form
from sqlalchemy.orm import Session
import json
# 导入你的models和Product模型

@app.post("/products")
def create_product(
    product: str = Form(...), 
    file: UploadFile = File(...), 
    db: Session = Depends(get_db)
):
    # 将表单中的JSON字符串解析为Product模型实例
    product_data = json.loads(product)
    product = Product(**product_data)
    
    # 构建数据库模型并写入
    product_model = models.Products()
    product_model.name = product.product_name
    product_model.description = product.description
    product_model.remaining_quantity = product.start_quantity
    product_model.start_quantity = product.start_quantity
    product_model.limit_per_user = product.limit
    product_model.is_featured = product.is_featured
    product_model.is_open = product.is_open 

    db.add(product_model)
    db.commit()
    db.refresh(product_model)  # 可选,获取数据库自动生成的字段(如ID)
    
    # 保存上传的图片文件
    with open(f"uploads/{file.filename}", "wb") as buffer:
        buffer.write(file.file.read())
    
    return {"product": product_model, "uploaded_file": file.filename}

请求方式说明

调用接口时需使用multipart/form-data格式传递参数:

  • 表单字段product:传入符合Product模型结构的JSON字符串
  • 表单字段file:选择要上传的图片文件

内容的提问来源于stack exchange,提问作者Brian Campana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:05:22