Skip to main content
When you need to receive form fields instead of JSON, use FastAPI’s Form() function. This is common for HTML forms and file uploads.

Installing Dependencies

Form data handling requires the python-multipart package:
Make sure to install python-multipart before using forms, or you’ll get an error when your application starts.

Basic Form Example

Use Form() to declare form data parameters:
This endpoint expects form data with application/x-www-form-urlencoded or multipart/form-data content type.
Form() is a class that inherits directly from Body(), so it supports the same validation and metadata parameters.

HTML Form Example

Here’s an HTML form that would work with the above endpoint:

Form Data vs JSON

You cannot mix Form() and Pydantic model body parameters in the same endpoint. They use different content types and encodings.

Form Field Validation

Form() supports all the same validation parameters as Query() and Body():
1

String Validation

Use min_length, max_length, pattern for string fields
2

Numeric Validation

Use gt, ge, lt, le for numeric fields
3

Documentation

Add title, description, examples for better docs

Optional Form Fields

Make form fields optional by providing a default value:

Multiple Form Values

You can receive multiple values for the same form field:
HTML form:

Combining Forms and Files

You can mix form fields with file uploads:
When you use both File() and Form() in the same endpoint, the content type will be multipart/form-data.

Form Data Encoding

Form data can be sent in two encodings:

application/x-www-form-urlencoded

Default encoding for simple forms:

multipart/form-data

Required when uploading files:
FastAPI automatically handles both encodings. You don’t need to specify which one.

Testing with curl

Form() Parameters

All parameters available in Form():
  • Validation: min_length, max_length, pattern, gt, ge, lt, le
  • Documentation: title, description, examples, deprecated
  • Behavior: alias, default, media_type

When to Use Forms

1

HTML Forms

Traditional web forms submitting data
2

File Uploads

When combining files with other form data
3

Legacy APIs

Integrating with systems that expect form data
4

OAuth Flows

OAuth2 password flow requires form data
For modern APIs, prefer JSON request bodies with Pydantic models. Use forms only when necessary (file uploads, HTML forms, legacy compatibility).