skip to content

In FastAPI, how do you declare form fields with Form(), and what goes wrong when you omit Form() or python-multipart?

level: juniorimportance: should knowfreq 40%

answer

  1. one body encoding per request
  2. Form is a subclass of Body
  3. an unmarked str goes to the query
  4. the parser package is checked at import

basics

~10 s

Declare each field as Annotated[str, Form()] and install python-multipart. Without Form() a str parameter becomes a query parameter, and without python-multipart FastAPI raises a RuntimeError as soon as the route is declared.

solid answer

~40 s

I declare each field as `Annotated[str, Form()]`; `Form` is a subclass of `Body`, so it takes the same validation and `alias` options, and FastAPI reads the value from an `application/x-www-form-urlencoded` or `multipart/form-data` body. If I leave `Form()` off, a `str` parameter becomes a query parameter and a lone Pydantic model becomes a JSON body, so browser submissions get a 422 for a missing query value. The parsing needs **python-multipart**: when a route declares a `Form` or `File` parameter, FastAPI tries to import it and raises a `RuntimeError` at import time if it is absent. In 0.143 an empty form value counts as missing, so an optional field gets its default. And a form endpoint cannot also read a JSON body, because a request carries one encoding.

code

python · 14 lines
python
from typing import Annotated

from fastapi import FastAPI, Form

app = FastAPI()


@app.post("/profile")
async def update_profile(
    display_name: Annotated[str, Form(min_length=1, max_length=40)],
    bio: Annotated[str | None, Form()] = None,
    nickname: str | None = None,  # no Form(): this is a query parameter
):
    return {"display_name": display_name, "bio": bio, "nickname": nickname}

go deeper

for a junior

Recall the declaration Annotated[str, Form()], the python-multipart install, and that a parameter without Form() is read from the query string.

for a middle

Explain how FastAPI chooses a parameter's source from its type and marker, why Form subclasses Body, and when the generated schema switches to multipart.

for a senior

Show you can diagnose a form that always returns 422 by reading the loc in the error and the /docs page, and that a missing parser fails at import.

for a principal

Decide whether form endpoints and JSON endpoints share one path or stay separate, and make the python-multipart dependency explicit in the project's requirements.

A browser form, and many simple clients, send their data as **form data** rather than JSON. FastAPI reads form data only for parameters you mark with `Form()`, and the parsing itself is done by a separate package, **python-multipart**. Getting either step wrong produces errors that look unrelated to forms. ## What `Form()` declares `Form` is imported from `fastapi` and used like `Query` or `Body`, normally inside `Annotated`: - `display_name: Annotated[str, Form()]` reads the form field `display_name` from the request body. - `Form()` accepts the same options as `Body`: validation such as `min_length` and `max_length`, `examples`, a `description` and an `alias` for a field whose wire name differs from the Python name. - `Form` is a subclass of `Body` whose default media type is `application/x-www-form-urlencoded`; `File` is in turn a subclass of `Form` whose media type is `multipart/form-data`. - When a path operation declares any `File` parameter, the generated schema advertises `multipart/form-data`, the encoding a browser uses for a form that carries files. Form fields are validated like any other parameter. A missing required field, or one that fails a constraint, ends in FastAPI's **422** response with a `loc` such as `["body", "display_name"]`. ## What happens when `Form()` is left off FastAPI decides where a parameter comes from by its type and its marker. Without `Form()`, the rules for plain parameters apply: | Declaration | Where FastAPI reads it | |---|---| | `name: Annotated[str, Form()]` | a form field in the body | | `name: str` | a query parameter | | `data: SomeModel` (a Pydantic model, no form or file parameters) | a JSON request body | | `file: UploadFile` | a file part in a multipart body | | `file: bytes` (no `File()`) | a query parameter, not a file | So a forgotten `Form()` rarely fails loudly at startup. The endpoint simply starts expecting `?display_name=...` in the URL, and every browser submission is rejected with a 422 that says the query parameter is missing. The docs page at `/docs` shows the mistake: the field appears under parameters instead of under the request body. ## python-multipart and the import-time check Starlette's form parsers are built on python-multipart. A plain install of the `fastapi` package does not include it; the `fastapi[standard]` extra does, and a project that installs only the base package must add it itself. FastAPI 0.143 checks for it when it analyses a route that declares a `Form` or `File` parameter: 1. The decorator such as `@app.post(...)` runs while the module is imported. 2. FastAPI finds a `Form`-derived parameter and tries to import `python_multipart`. 3. If the import fails it raises a `RuntimeError` whose message begins `Form data requires "python-multipart" to be installed.`, and the application never starts. There is a second variant of the message for a different package named `multipart` installed by mistake, telling you to uninstall it and install python-multipart instead. Failing at import time is deliberate: a missing parser shows up in the first deploy check, not on the first user who submits the form. ## Empty values from HTML forms An HTML form submits an empty text input as an empty string. In FastAPI 0.143, an empty string sent to a `Form()` parameter is treated as **not sent**: - an optional parameter such as `bio: Annotated[str | None, Form()] = None` receives its default, `None`; - a required parameter fails with a 422 error of type `missing`, not a length error. This matches how browsers fill forms, but it surprises anyone who expected `""`. Release 0.123.2 introduced the behaviour, so material written for older releases describes the opposite. ## Why the same endpoint cannot also take JSON A request has one body and one `Content-Type`. Once a path operation declares `Form()` or `File()` parameters, FastAPI parses the body as form data, so: - a client that posts JSON to a form endpoint gets a 422 listing the form fields as missing; - declaring a Pydantic model parameter next to `Form()` fields does not create a JSON part; the docs state that you cannot combine form fields with `Body` fields expected as JSON, because that is how HTTP bodies work rather than a FastAPI limitation. If one endpoint must serve both kinds of clients, write two path operations, or carry the structured part inside the form as a string field and parse it there.

  • What does a FastAPI endpoint with only Form() parameters answer when a client posts a JSON body instead?
    A 422. FastAPI parses the body as form data, finds none of the declared fields, and reports each required one as `missing` with a `loc` such as `["body", "display_name"]`. Nothing tries the body as JSON, so the fix is on the client: send form data, or give JSON clients a separate path operation.
  • In FastAPI 0.143, what does an optional Form() field receive when an HTML form submits that input empty?
    Its default. Since 0.123.2 FastAPI treats an empty string sent to a `Form()` parameter as not sent, so `bio: Annotated[str | None, Form()] = None` receives `None`. A required `Form()` parameter fails with a `missing` error rather than a length error. Code that relied on receiving `""` must check for the default instead.

  • A str parameter on a POST endpoint is read from the form even without Form().
  • python-multipart is needed only for file uploads, not for plain form fields.
  • A missing python-multipart only shows up when the first form request arrives.
  • A form endpoint can also take a Pydantic model as a JSON body.
  • An empty text input always reaches a Form() parameter as an empty string.

Assumes FastAPI 0.143; since 0.123.2 an empty string sent to a Form() parameter counts as missing, so older material showing an empty string is out of date.