Form endpoints are an easy target for abuse. A single request with thousands of tiny form fields, or one giant text field, can eat CPU and memory long before your code runs. FastAPI 0.165.0, released on 18 November 2026, adds configurable form parsing limits so you can control this per app, per router or per endpoint.
This tutorial explains the new form_limits setting, how it works with the existing max_body_size option, and how to choose sensible values. Sources: the FastAPI 0.165.0 release and the official Request Body Limits docs.
What changed in FastAPI 0.165
The release has a single feature: “Add configurable form parsing limits” (PR #16784). In practice that means a new form_limits configuration with three keys:
| Key | What it limits | Default |
|---|---|---|
max_fields |
Number of text fields in a form | 1,000 |
max_files |
Number of files in a multipart form | 1,000 |
max_part_size |
Size in bytes of each text field | 1 MiB |
FastAPI passes these values to Starlette whenever it parses a request for a Form, File or UploadFile parameter, including parameters declared in dependencies. Going over a parser limit returns HTTP 400.
Upgrade first:
pip install -U "fastapi>=0.165.0"
Two layers of protection
It helps to think of two separate limits:
max_body_sizebounds the whole request body in bytes: every file, every field and the multipart encoding overhead. Exceeding it returns HTTP 413 Content Too Large.form_limits(new in 0.165) bounds the shape of a form: how many fields, how many files, and how large each text field may be. Exceeding these returns HTTP 400.
You usually want both. max_body_size stops a 2 GB upload; form_limits stops a 900 KB request that contains 50,000 one-byte fields.
Setting form limits on the app
The simplest setup applies one rule to the whole application:
from typing import Annotated
from fastapi import FastAPI, Form
app = FastAPI(form_limits={"max_fields": 20})
@app.post("/contact")
async def contact(
name: Annotated[str, Form()],
email: Annotated[str, Form()],
message: Annotated[str, Form()],
):
return {"ok": True, "chars": len(message)}
A contact form has three fields, so allowing 20 leaves plenty of room while rejecting requests that try to stuff in thousands.
Overriding limits per endpoint
Each setting inherits independently. That means you can override just one key on a path operation and keep the others from the app:
from typing import Annotated
from fastapi import FastAPI, Form
app = FastAPI(form_limits={"max_fields": 5})
@app.post("/notes")
async def create_note(text: Annotated[str, Form()]):
return {"size": len(text)}
@app.post("/documents", form_limits={"max_part_size": 2 * 1024 * 1024})
async def create_document(text: Annotated[str, Form()]):
return {"size": len(text)}
Here /documents allows text fields up to 2 MiB, while still inheriting max_fields=5 from the app. /notes uses the app defaults.
Router-level limits
The same form_limits setting can be applied on an APIRouter or passed to include_router(). This is handy when one group of endpoints, such as an admin area or an import tool, has different needs:
from typing import Annotated
from fastapi import APIRouter, FastAPI, File, Form, UploadFile
app = FastAPI(form_limits={"max_fields": 20, "max_files": 1})
imports = APIRouter(prefix="/imports")
@imports.post("/batch")
async def batch_upload(
files: Annotated[list[UploadFile], File()],
label: Annotated[str, Form()],
):
return {"label": label, "count": len(files)}
app.include_router(imports, form_limits={"max_files": 50})
The import router accepts up to 50 files per request, while the rest of the app allows only one.
Combining with max_body_size
The docs show max_body_size working at the same three levels. Use it to cap total bytes, and form_limits to cap structure:
from typing import Annotated
from fastapi import APIRouter, FastAPI, File, Form, UploadFile
app = FastAPI(
max_body_size=1 * 1024 * 1024, # 1 MiB for normal requests
form_limits={"max_fields": 20, "max_files": 1},
)
uploads = APIRouter(
prefix="/uploads",
max_body_size=100 * 1024 * 1024, # 100 MiB for uploads
)
@uploads.post("/")
async def upload(
file: Annotated[UploadFile, File()],
caption: Annotated[str, Form()] = "",
):
return {"filename": file.filename, "size": file.size}
app.include_router(uploads)
Some details from the docs worth remembering:
- The body limit counts bytes as FastAPI reads them, even when the client streams without a
Content-Lengthheader. - With
UploadFile, data may spill from memory to disk as it grows, but it still counts toward the same limit. - Leaving
max_body_size=Nonemeans “inherit”. If no level sets a limit, the body size is unlimited, so set one on the app. max_part_sizeapplies to text fields. For URL-encoded forms, Starlette counts the encoded name and value together. File contents are bounded bymax_body_size, not bymax_part_size.
Parsing a form manually
If you call request.form() yourself instead of declaring Form parameters, pass your limits to the first call. Starlette caches the parsed form on the request, so later calls won’t re-parse with new limits:
from fastapi import FastAPI, Request
app = FastAPI()
@app.post("/raw-form")
async def raw_form(request: Request):
form = await request.form(max_fields=10, max_files=0, max_part_size=64 * 1024)
return {"keys": list(form.keys())}
Starlette’s request.form() has accepted max_files and max_fields for some time; check your installed Starlette version’s documentation for max_part_size support before relying on it in manual parsing.
Testing your limits
It’s worth adding a test so a future refactor doesn’t silently remove a limit:
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_rejects_too_many_fields():
data = {f"f{i}": "x" for i in range(100)}
response = client.post("/contact", data=data)
assert response.status_code == 400
def test_accepts_normal_form():
response = client.post(
"/contact",
data={"name": "Asha", "email": "[email protected]", "message": "Hi"},
)
assert response.status_code == 200
Choosing good values
- Start from the real form. Count the fields your frontend sends and add a safety margin; 1,000 fields is far more than most forms need.
- Set
max_filesto 0 or 1 on endpoints that should never receive files or only one file. - Keep
max_part_sizesmall for ordinary text inputs. Raise it only where you expect large text, such as Markdown documents. - Always set an app-wide
max_body_size. Then raise it for specific upload routes. - Mind middleware. If middleware reads the body before routing, the app-level body limit applies to that read, so a router’s larger limit won’t help.
Key takeaways
- FastAPI 0.165.0 adds
form_limitswithmax_fields,max_filesandmax_part_size. - Limits can be set on the app, a router,
include_router()or a single path operation, and each key inherits independently. - Form limit violations return HTTP 400;
max_body_sizeviolations return HTTP 413. - Use both together to protect form and upload endpoints from resource-exhaustion requests.
Read the official Request Body Limits guide for the complete reference.
