Skip to main content
FastAPI Docs

Search documentation

Type to search this documentation.

On this pageOverview

Form Models

You can use Pydantic models to declare form fields in FastAPI.

You just need to declare a Pydantic model with the fields you want to receive as form fields, and then declare the parameter as Form:

Python
from typing import Annotated

from fastapi import FastAPI, Form
from pydantic import BaseModel

app = FastAPI()


class FormData(BaseModel):
    username: str
    password: str


@app.post("/login/")
async def login(data: Annotated[FormData, Form()]):
    return data

FastAPI will extract the data for each field from the form data in the request and give you the Pydantic model you defined.

You can verify it in the docs UI at /docs:

In some special use cases (probably not very common), you might want to restrict the form fields to only those declared in the Pydantic model. And forbid any extra fields.

You can use Pydantic's model configuration to forbid any extra fields:

Python
from typing import Annotated

from fastapi import FastAPI, Form
from pydantic import BaseModel

app = FastAPI()


class FormData(BaseModel):
    username: str
    password: str
    model_config = {"extra": "forbid"}


@app.post("/login/")
async def login(data: Annotated[FormData, Form()]):
    return data

If a client tries to send some extra data, they will receive an error 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 field extra is not allowed:

JSON
{
    "detail": [
        {
            "type": "extra_forbidden",
            "loc": ["body", "extra"],
            "msg": "Extra inputs are not permitted",
            "input": "Mr. Poopybutthole"
        }
    ]
}

You can use Pydantic models to declare form fields in FastAPI. 😎

Suggest an edit

Propose a replacement for this page. The site team reviews it before applying any changes.

Export
Documentation menu