Here is the Pydantic model used for Form
data:
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 route's body is correct.
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:
For some reason handling Form
data and File
upload at the same time raises 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"}'}]
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.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.