Form() function. This is common for HTML forms and file uploads.
Installing Dependencies
Form data handling requires thepython-multipart package:
Basic Form Example
UseForm() to declare form data parameters:
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 fields2
Numeric Validation
Use
gt, ge, lt, le for numeric fields3
Documentation
Add
title, description, examples for better docsOptional Form Fields
Make form fields optional by providing a default value:Multiple Form Values
You can receive multiple values for the same form field: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:Testing with curl
Form() Parameters
All parameters available inForm():
- 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
Related Topics
- Request Files - Handle file uploads
- Request Body - Work with JSON request bodies
- Query Parameters - Handle URL parameters