pythonswaggerfastapimultipartform-dataopenapi

FastAPI error when handling file together with form-data defined in a Pydantic model


For some reason handling Form Data and File Upload at the same time raises 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:

enter image description here

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":"user@example.com","password":"string"}'}]


Solution

  • 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.