Fastapi Multipart/form data error: required fields

Solution 1:

According to the FastAPI docs:

You can declare multiple File and Form parameters in a path operation, but you can't also declare Body fields that you expect to receive as JSON, as the request will have the body encoded using multipart/form-data instead of application/json.

This is not a limitation of FastAPI, it's part of the HTTP protocol.

And when passing an object, FastAPI will try to treat it as a body specification, not as a form field. That means, you have to explicitly define your banner argument as a form field:

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

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

Make also sure that your Banner object is a valid pydantic model, as FastAPI can't recognize bare objects properly in this context.