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
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.
ILIKETOLEARN is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.