In FastAPI, how do you bind a whole HTML form to a Pydantic model, and what changes when that model forbids extra fields?
answer
- one model instead of many parameters
- the Form() marker on a model
- model_config extra forbid
- extra_forbidden in the 422
basics
~20 sDeclare the parameter as Annotated[MyForm, Form()] and FastAPI fills each model field from the form data. With model_config = {"extra": "forbid"}, any undeclared form key is rejected with a 422 extra_forbidden error instead of being ignored.
solid answer
~40 sI write a Pydantic model and declare `form: Annotated[ProfileUpdate, Form()]`; FastAPI reads each model field from the form data and validates it, so constraints and 422 errors work as usual and `/docs` shows the fields. By default undeclared keys are ignored; with `model_config = {"extra": "forbid"}` they are rejected with a 422 of type `extra_forbidden` and a `loc` like `["body", "is_admin"]`. The model should be the endpoint's only body parameter: adding a separate `UploadFile` makes FastAPI expect the model under its parameter name, so I put the file in the model instead. One difference to remember: an empty input in a model field arrives as `""`, not as missing.
code
python · 23 linesfrom typing import Annotated
from fastapi import FastAPI, Form, UploadFile
from pydantic import BaseModel, Field
app = FastAPI()
class ProfileUpdate(BaseModel):
model_config = {"extra": "forbid"}
display_name: str = Field(min_length=1, max_length=40)
bio: str | None = None
avatar: UploadFile | None = None # the file lives inside the model
@app.post("/profile")
async def update_profile(form: Annotated[ProfileUpdate, Form()]):
return {
"display_name": form.display_name,
"bio": form.bio,
"avatar": form.avatar.filename if form.avatar else None,
}go deeper
Recall that Annotated[Model, Form()] fills a model from form fields, and that a lone model without Form() is read as a JSON body.
Explain how extra forbid produces a 422 extra_forbidden error and why the model should be the only body parameter.
Show you can diagnose a 422 that reports the model parameter missing, and the empty-string difference between model fields and single parameters.
Set a convention for state-changing forms: one shared model per form, extra forbid on by default, and explicit handling of empty optional inputs.
A profile form with half a dozen inputs quickly turns an endpoint signature into a wall of `Form()` parameters. FastAPI lets you declare those fields once, as a **Pydantic model**, and bind the whole form to it. ## Declaring a form model Write an ordinary Pydantic model and mark the parameter with `Form()`: - `form: Annotated[ProfileUpdate, Form()]` tells FastAPI to read **each field of the model** from the form data, by field name or alias, and to build the model from them. - Field constraints such as `Field(min_length=1, max_length=40)` are applied as usual, and failures come back as FastAPI's 422 response with `loc` entries like `["body", "display_name"]`. - The model appears in the generated schema, so `/docs` shows one form with every field. - The same model can be reused by several endpoints, and by tests that build form data from it. This needs python-multipart like any other form parameter. On an endpoint with no other form or file parameters, a Pydantic model without `Form()` is read as a JSON body, so the marker is what makes it a form model. ## Forbidding extra fields By default Pydantic ignores keys a model does not declare, so a form that posts `is_admin=true` next to the real fields is accepted and the extra key silently dropped. Setting `model_config = {"extra": "forbid"}` on the model changes that: 1. FastAPI passes the declared fields **and** any undeclared form keys to the model. 2. Pydantic rejects the undeclared ones. 3. The client receives a 422 with an error of type `extra_forbidden`, message `Extra inputs are not permitted` and a `loc` such as `["body", "is_admin"]`. Forbidding extras is a good default for forms that change state: it turns a misspelt field name or an unexpected input into a clear error instead of a silent no-op, and it tells a client exactly which key the server refused. ## Files inside the model A form model is the **only** body parameter its endpoint should declare. When an endpoint has a form model and also a separate `Form()` or `UploadFile` parameter, FastAPI has several body parameters and **embeds** them: it expects the model's data under a form key named after the parameter. A browser sends the model's fields flat, so the request fails with a 422 saying the model parameter itself is `missing`. The fix is to move the file into the model: - declare `avatar: UploadFile | None = None` as a model field, as in the example; - FastAPI extracts that field from the multipart body like the text fields, and validation still runs; - the generated schema in this case still lists `application/x-www-form-urlencoded` as the media type, so check what `/docs` offers if you rely on it for manual testing. ## Behaviour that differs from single `Form()` parameters | Situation | Single `Form()` parameter | Field of a form model | |---|---|---| | Empty text input | treated as missing, default used | arrives as `""` | | Undeclared keys | not read | ignored, or 422 with `extra: forbid` | | Several body parameters | allowed together | the model must be the only one | | Reuse across endpoints | repeat each parameter | reuse the model | The empty-value row matters for optional fields: with a single parameter `bio: Annotated[str | None, Form()] = None` an empty input gives `None`, while the model field `bio: str | None = None` receives an empty string. If the endpoint treats `""` and `None` differently, normalise it in a model validator. ## Reading the 422 from a form model Errors from a form model use the same shape as every other FastAPI validation error, which makes them easy to map back to inputs: - `loc` starts with `"body"` followed by the field name, for example `["body", "display_name"]`, not the parameter name `form`; - a constraint failure carries its own type and context, such as `string_too_long` with `ctx: {"max_length": 40}`; - a refused extra key appears as `extra_forbidden` with the submitted value in `input`; - several failing fields are reported together in one `detail` list, so a form page can mark every bad input at once. ## When a form model is worth it - Several endpoints share the same set of form fields. - The form has enough fields that a flat signature is hard to read. - You want `extra: forbid` to catch unexpected keys. For one or two fields, plain `Form()` parameters stay simpler, and they keep the empty-means-missing behaviour that browser forms expect.
- In FastAPI, why does an endpoint with a form model parameter plus a separate UploadFile parameter answer 422 for a normal browser submission?With more than one body parameter FastAPI embeds them, so it looks for the model's data under a form key named after the model parameter. The browser sends the model's fields flat, and validation reports the model parameter as `missing`. Declaring the file as a field of the model keeps a single body parameter and fixes it.
- In FastAPI, how does an empty optional text input behave in a form model compared with a single Form() parameter?A single `Form()` parameter treats an empty string as not sent and uses its default, while a form model field receives the empty string itself. If the endpoint must treat both cases alike, add a model validator that turns empty strings into `None` for the optional fields.
- Without Form(), a lone Pydantic model parameter is still filled from the form fields.
- Undeclared form keys are rejected by default, even without extra forbid.
- A form model and separate File() parameters combine freely in one endpoint.
- Fields of a form model treat empty inputs exactly like single Form() parameters.