Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastAPI Multipart/form data error when uploading File with JSON data [duplicate]

My Pydantic model looks like ths:

class Banner:
    title: str
    text: str

My route looks like this:

@router.post('', status_code=201)
async def create_banner(
    banner: Banner,
    photo: UploadFile = File(...)  # multipart/form-data

):
    return await Banners.create(banner.dict())

But FastAPI returns the following error:

enter image description here

like image 828
Hahan't Avatar asked Jul 18 '26 07:07

Hahan't


1 Answers

Update

Please have a look at this answer for more options on how to upload a File together with JSON data.

Original answer

In short, you can't have Pydantic models (JSON data) defined together with Form (and/or File) data. You can either use Form fields, i.e, sending the data as form-data in the body:

@router.post("/")
def create_banner(title: str = Form(...), text: str = Form(...), photo: UploadFile = File(...)):
        return {"JSON Payload ": {"title": title, "text": text}, "Uploaded Filename": photo.filename}

or, use Dependencies with Pydantic models, i.e., sending the data as query parameters:

from pydantic import BaseModel
from fastapi import Depends

class Banner(BaseModel):
    title: str
    text: str

@router.post("/")
def create_banner(banner: Banner = Depends(), photo: UploadFile = File(...)):
    return {"JSON Payload ": banner.dict(), "Uploaded Filename": photo.filename}
like image 94
Chris Avatar answered Jul 19 '26 19:07

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!