Files
fastapi/docs/en/docs/tutorial/request-form-models.md
T

2.9 KiB

Form Models

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

/// note

To use forms, first install python-multipart.

Add it to your project:

$ uv add python-multipart

///

/// note

This is supported since FastAPI version 0.113.0. 🤓

///

Pydantic Models for Forms

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:

{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}

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

Boolean fields follow the same omission rules as individual form parameters.

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 to restrict the form fields to only those declared in the Pydantic model. And forbid any extra fields.

/// note

This is supported since FastAPI version 0.114.0. 🤓

///

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

{* ../../docs_src/request_form_models/tutorial002_an_py310.py hl[12] *}

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:

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

Combine Form Models

You can combine multiple form models with individual Form parameters.

{* ../../docs_src/request_form_models/tutorial003_an_py310.py hl[9:14,19:21] *}

The client sends name, tags, and token as form fields. Each model receives its own fields and validates them independently.

If multiple declarations use the same form field name, each validates that field's value. Use compatible types and constraints for shared fields so the OpenAPI schema can describe them consistently.

Form Models and Files

You can also combine a form model with file parameters.

{* ../../docs_src/request_form_models/tutorial004_an_py310.py hl[14] *}

Here the client sends the name field and the avatar file using multipart/form-data.

Summary

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