Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Join theFastAPI Cloud waiting list 🚀
Follow@fastapi onX (Twitter) to stay updated
FollowFastAPI onLinkedIn to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor

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-multipart

Note

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()):returndata

FastAPI 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()):returndata

If 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:Rick
  • password:Portal Gun
  • extra: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. 😎


[8]ページ先頭

©2009-2026 Movatter.jp