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

1

1

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":"[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
Clementclementas answered 24/9 at 18:59 Comment(12)
routeBody: RouteBody = json.loads(Form())Heliopolis
Which version of FastAPI are you using? Using a pydantic model to describe expected form values was added in 0.113 and is a fairly recent addition. According to the swagger example and the error message it seems to expect a JSON body, and not actual form data - and you can't combine a multipart form data file upload and a JSON body.Recur
@Heliopolis This does not work, TypeError: the JSON object must be str, bytes or bytearray, not FormClementclementas
@Recur I am using the latest version of FastAPI. I literally went to the official site and went through the get started guide all the way up to this point. For some reason the Pydantic Models don't work on form-data unless you set the default argument for that parameter as "Form()". And that worked no problem. But the moment I include a file it creates an error. And you CAN put an image alongside the content of a form-data. For some reason it creates an error in FastAPI though. Strange.Clementclementas
try to add ` class Config: extra = "form" ` in the class RouteBody(BaseModel):Heliopolis
@Heliopolis Strange but i added it, got this error. pydantic_core._pydantic_core.SchemaError: Invalid Schema: model.config.extra_fields_behavior Input should be 'allow', 'forbid' or 'ignore' [type=literal_error, input_value='form', input_type=str] For further information visit https://errors.pydantic.dev/2.9/v/literal_errorClementclementas
So it can only be set to "allow", "forbid" or "ignore". I set it to "forbid" and it stil didn't work. I go back to this error. TypeError: the JSON object must be str, bytes or bytearray, not FormClementclementas
so basically (routeBody: RouteBody = Form() if you replace RouteBody with str, your code should work, so you need to work on how to make data from Form validate in your pydantic modelHeliopolis
@Heliopolis That defeats the whole purpose of Pydantic then.Clementclementas
@Clementclementas try routeBody: RouteBody = Form(embed=True)Heliopolis
@Recur OP is not trying to post both JSON data and a File, but rather Form data (defined in a Pydantic model) along with some File. What they experience is actually true - just tested it (their solution below, though, is not correct). To me, this seems to be a bug with Swagger/OpenAPI, and should be brought to FastAPI's creator attention (i.e., @tiangolo). It should be possible for one to define a Pydantic model for Form attributes, and a File as well in the endpoint, but Swagger for some reason interprets the Form attributes as JSON instead, when the File is included.Wundt
In the case of uploading both File and JSON data instead, one should take a look at this answerWundt
C
0

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.

Clementclementas answered 26/9 at 16:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.