Form Models¶
You can usePydantic models to declareform fields in FastAPI.
Info
To use forms, first installpython-multipart.
Make sure you create avirtual environment, activate it, and then install it, for example:
$pipinstallpython-multipartNote
This is supported since FastAPI version0.113.0. 🤓
Pydantic Models for Forms¶
You just need to declare aPydantic model with the fields you want to receive asform fields, and then declare the parameter asForm:
fromtypingimportAnnotatedfromfastapiimportFastAPI,FormfrompydanticimportBaseModelapp=FastAPI()classFormData(BaseModel):username:strpassword:str@app.post("/login/")asyncdeflogin(data:Annotated[FormData,Form()]):returndata🤓 Other versions and variants
Tip
Prefer to use theAnnotated version if possible.
fromfastapiimportFastAPI,FormfrompydanticimportBaseModelapp=FastAPI()classFormData(BaseModel):username:strpassword:str@app.post("/login/")asyncdeflogin(data:FormData=Form()):returndataFastAPI willextract the data foreach field from theform data in the request and give you the Pydantic model you defined.
Check the Docs¶
You can verify it in the docs UI at/docs:

Forbid Extra Form Fields¶
In some special use cases (probably not very common), you might want torestrict the form fields to only those declared in the Pydantic model. Andforbid anyextra fields.
Note
This is supported since FastAPI version0.114.0. 🤓
You can use Pydantic's model configuration toforbid anyextra fields:
fromtypingimportAnnotatedfromfastapiimportFastAPI,FormfrompydanticimportBaseModelapp=FastAPI()classFormData(BaseModel):username:strpassword:strmodel_config={"extra":"forbid"}@app.post("/login/")asyncdeflogin(data:Annotated[FormData,Form()]):returndata🤓 Other versions and variants
Tip
Prefer to use theAnnotated version if possible.
fromfastapiimportFastAPI,FormfrompydanticimportBaseModelapp=FastAPI()classFormData(BaseModel):username:strpassword:strmodel_config={"extra":"forbid"}@app.post("/login/")asyncdeflogin(data:FormData=Form()):returndataIf a client tries to send some extra data, they will receive anerror response.
For example, if the client tries to send the form fields:
username:Rickpassword:Portal Gunextra:Mr. Poopybutthole
They will receive an error response telling them that the fieldextra is not allowed:
{"detail":[{"type":"extra_forbidden","loc":["body","extra"],"msg":"Extra inputs are not permitted","input":"Mr. Poopybutthole"}]}Summary¶
You can use Pydantic models to declare form fields in FastAPI. 😎







