FastAPI Error when handling file and form-data at the same time

For some reason handling Form Data and File Upload at the same time produces an error.

from typing import Annotated

from pydantic import BaseModel, StringConstraints, EmailStr

class RouteBody(BaseModel):
    email: Annotated[EmailStr, StringConstraints(
        max_length = 255
    )]
    password: Annotated[str, StringConstraints(
        max_length = 60
    )]

And this enforces that the routes body is correct. Super nice.

from fastapi import UploadFile, File

@some_api_router.post("/some-route")
async def handleRoute(routeBody: RouteBody = Form(), profilePicture: UploadFile = File(...)):
    return {"msg": "Route"}

And I test it out using SwaggerUI docs

Check Image for Form Input with Image

I get the following error

error [{'type': 'model_attributes_type', 'loc': ('body', 'routeBody'), 'msg': 'Input should be a valid dictionary or object to extract fields from', 'input': '{"email":"[email protected]","password":"string"}'}]

  • Tested it out on a separate route without the “RouteBody” and it worked perfectly.
  • Rewrote Route Handler from Scratch
  • Changed the order of the parameters (don’t know why I thought this mattered … maybe it did?)
  • Instead of using a Pydantic Model type for the RouteBody, I opted for individual parameters to make it functional. However, this isn’t an ideal solution, as it requires listing out all the parameters if you have many of them.
  • Asked ChatGPT for guidance

New contributor

ILIKETOLEARN is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

10

To use a Pydantic model with a file input, you just need to include the file in the Pydantic model itself. Instead of adding an additional parameter to your function, integrate the file field directly into your Pydantic model. For example, it would look like this

class RouteBody(BaseModel):
    email: Annotated[EmailStr, StringConstraints(
        max_length = 255
    )]
    password: Annotated[str, StringConstraints(
        max_length = 60
    )]
    image: Annotated[UploadFile, File()]
    model_config = {"extra": "forbid"}

@some_api_router.post("/some-route")
async def handleRoute(routeBody: RouteBody = Form()):
    return {"msg": "Route"}

In SwaggerUI, you’ll still encounter an error because the content type defaults to “application/x-www-form-urlencoded.” To avoid this, switch to Postman and set the body type to “form-data,” and it should work smoothly. The great part is that all the validation will function properly, which is a big plus. This approach is better than listing each required input in the function parameters because it lets you define the logic in one go without unnecessary repetition and its way cleaner.

New contributor

ILIKETOLEARN is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật