Almost every real web API ends up accepting files: profile photos, CSV imports, PDF invoices, audio for transcription or documents for an AI pipeline. FastAPI makes the first upload look trivial, but a production endpoint has to answer harder questions. What happens with a 4 GB file? Can a user upload script.exe renamed to photo.png? Can a filename like ../../etc/passwd overwrite something on your server? In this tutorial we build file upload endpoints step by step: a single UploadFile, multiple files with form fields, saving large files to disk in chunks, validating the real file type, the brand-new request body size limits and form parsing limits added in FastAPI 0.164 and 0.165 (released on 18 November 2026), and finally a real server with uploads and downloads over HTTP. Everything was run on Python 3.15.2 with FastAPI 0.165.0, Starlette 1.10.0, python-multipart 0.0.34 and Pillow 13.0.0, and every output block below is the real output of the script above it.
Setup
FastAPI reads multipart form data with the python-multipart package. It is included when you install fastapi[standard]; with a minimal install you must add it yourself, otherwise FastAPI raises an error telling you to install it as soon as you declare a File or Form parameter. The test client in Starlette 1.x now prefers httpx2, the successor of httpx maintained by the Pydantic team, so install it too if you write tests.
python -m venv .venv # or: uv venv
pip install "fastapi[standard]" python-multipart httpx2 pillow
python -c "import fastapi; print(fastapi.__version__)" # 0.165.0
All examples use TestClient, which calls the app in-process, so you can run each file with plain python stepN.py and see the result without starting a server. In your own project you would run the same app with fastapi dev main.py and try the endpoints in the automatic /docs page, which shows a file picker for every upload parameter.
Step 1: upload a single file with UploadFile
There are two ways to receive a file. bytes with File() gives you the whole content in memory, which is fine for tiny files. UploadFile is what you want almost always: it is a "spooled" temporary file that stays in memory while small and moves to disk when it grows, and it gives you the original filename, the content type sent by the client and the size.
from typing import Annotated
from fastapi import FastAPI, File, UploadFile
from fastapi.testclient import TestClient
app = FastAPI()
@app.post("/bytes")
async def upload_bytes(data: Annotated[bytes, File()]):
# Small files only: the whole file is read into memory as bytes
return {"size": len(data)}
@app.post("/upload")
async def upload(file: UploadFile):
head = await file.read(16) # read only what you need
return {
"filename": file.filename,
"content_type": file.content_type,
"size": file.size,
"first_bytes": head.decode(errors="replace"),
}
client = TestClient(app)
csv = b"name,score\nAli,91\nSara,88\nBilal,79\n"
print(client.post("/bytes", files={"data": ("scores.csv", csv)}).json())
r = client.post("/upload", files={"file": ("scores.csv", csv, "text/csv")})
print(r.status_code, r.json())
r = client.post("/upload") # forgot the file
print(r.status_code, r.json()["detail"][0]["type"], r.json()["detail"][0]["loc"])
Output:
{'size': 35}
200 {'filename': 'scores.csv', 'content_type': 'text/csv', 'size': 35, 'first_bytes': 'name,score\nAli,9'}
422 missing ['body', 'file']
file.read(16) read only the first 16 bytes; the rest of the upload was never loaded into Python memory. If the client forgets the file, FastAPI returns a 422 validation error pointing at body.file, exactly like a missing JSON field. Note that file.filename and file.content_type come from the client, so treat them as hints, not facts. We will deal with that in step 4.
Step 2: multiple files plus form fields
To accept several files under one field, declare list[UploadFile]. You can mix files with normal form fields using Form(), and all the usual Pydantic validation (lengths, booleans, numbers) still applies. What you cannot do is combine files with a JSON body in the same request: a multipart request has no JSON part, so metadata travels as form fields.
from typing import Annotated
from fastapi import FastAPI, File, Form, UploadFile
from fastapi.testclient import TestClient
app = FastAPI()
@app.post("/albums")
async def create_album(
title: Annotated[str, Form(min_length=3, max_length=50)],
files: Annotated[list[UploadFile], File(description="One or more photos")],
public: Annotated[bool, Form()] = False,
):
return {
"title": title,
"public": public,
"count": len(files),
"files": [{"name": f.filename, "size": f.size} for f in files],
}
client = TestClient(app)
files = [
("files", ("beach.jpg", b"\xff\xd8\xff" + b"0" * 2048, "image/jpeg")),
("files", ("hills.jpg", b"\xff\xd8\xff" + b"1" * 4096, "image/jpeg")),
("files", ("city.png", b"\x89PNG\r\n\x1a\n" + b"2" * 1024, "image/png")),
]
r = client.post("/albums", data={"title": "Summer 2026", "public": "true"}, files=files)
print(r.status_code, r.json())
r = client.post("/albums", data={"title": "ab"}, files=files[:1])
print(r.status_code, r.json()["detail"][0]["msg"])
Output:
200 {'title': 'Summer 2026', 'public': True, 'count': 3, 'files': [{'name': 'beach.jpg', 'size': 2051}, {'name': 'hills.jpg', 'size': 4099}, {'name': 'city.png', 'size': 1032}]}
422 String should have at least 3 characters
The string "true" from the form was converted to a real boolean, and the title that was too short was rejected with a clear message before our function ran. In the browser the matching HTML form needs enctype="multipart/form-data" and an input with the multiple attribute; from JavaScript you build a FormData object and append each file under the same name.
Step 3: save large uploads to disk in chunks
The classic mistake is contents = await file.read() followed by writing contents to disk. That loads the entire file into RAM, and a few parallel uploads of big videos can take a server down. Instead, copy the file in fixed-size chunks and hash it on the way. Because file I/O is blocking, we run the copy in a worker thread with run_in_threadpool so the event loop stays free. We also ignore the client filename when building the path and generate a random name, keeping only a short extension.
import hashlib
import shutil
import uuid
from pathlib import Path
from fastapi import FastAPI, UploadFile
from fastapi.concurrency import run_in_threadpool
from fastapi.testclient import TestClient
UPLOAD_DIR = Path("uploads")
UPLOAD_DIR.mkdir(exist_ok=True)
CHUNK = 1024 * 1024 # 1 MiB
app = FastAPI()
def save_to_disk(file: UploadFile, dest: Path) -> str:
sha = hashlib.sha256()
with dest.open("wb") as out:
while chunk := file.file.read(CHUNK): # never load the whole file
sha.update(chunk)
out.write(chunk)
return sha.hexdigest()
@app.post("/files")
async def save_file(file: UploadFile):
# Never trust file.filename for the path: generate our own name
suffix = Path(file.filename or "").suffix.lower()[:10]
dest = UPLOAD_DIR / f"{uuid.uuid4().hex}{suffix}"
digest = await run_in_threadpool(save_to_disk, file, dest)
return {"original": file.filename, "saved_as": dest.name[:8] + "..." + suffix,
"bytes": dest.stat().st_size, "sha256": digest[:16]}
client = TestClient(app)
big = bytes(range(256)) * 12_000 # about 3 MB
r = client.post("/files", files={"file": ("../../etc/report.bin", big)})
print(r.status_code, r.json())
print("expected sha256:", hashlib.sha256(big).hexdigest()[:16])
print("files on disk:", len(list(UPLOAD_DIR.iterdir())))
shutil.rmtree(UPLOAD_DIR)
Output:
200 {'original': '../../etc/report.bin', 'saved_as': 'ef73e7b2....bin', 'bytes': 3072000, 'sha256': '4b946083e4726eb8'}
expected sha256: 4b946083e4726eb8
files on disk: 1
The 3 MB file was written in 1 MiB chunks, its SHA-256 matches the original, and the hostile name ../../etc/report.bin had no effect on where the file was stored: only the .bin suffix survived. Keep the original name in your database if you need to show it, but never use it as a path. If you prefer plain functions, declare the endpoint with def instead of async def; FastAPI then runs the whole function in a thread, which we use in step 6.
Step 4: validate the real file type
Validation should happen in layers. First an allowlist of extensions, then a check of the first bytes of the file (the "magic number" that real PNG, JPEG and PDF files start with), and for images a final decode with Pillow. The content_type header is useless for security because the client chooses it; in the test below every file claims to be image/png.
import io
from pathlib import Path
from fastapi import FastAPI, HTTPException, UploadFile, status
from fastapi.testclient import TestClient
from PIL import Image
ALLOWED = {".png": b"\x89PNG\r\n\x1a\n", ".jpg": b"\xff\xd8\xff",
".jpeg": b"\xff\xd8\xff", ".pdf": b"%PDF-"}
app = FastAPI()
async def check_upload(file: UploadFile) -> str:
ext = Path(file.filename or "").suffix.lower()
if ext not in ALLOWED:
raise HTTPException(status.HTTP_415_UNSUPPORTED_MEDIA_TYPE, f"{ext or 'no extension'} not allowed")
head = await file.read(8)
await file.seek(0)
if not head.startswith(ALLOWED[ext]): # the client-sent content_type can lie
raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, "file content does not match extension")
return ext
@app.post("/avatar")
async def avatar(file: UploadFile):
ext = await check_upload(file)
if ext == ".pdf":
raise HTTPException(415, "avatar must be an image")
try:
img = Image.open(file.file)
img.verify() # raises if the image data is broken
except Exception:
raise HTTPException(422, "not a valid image")
return {"ok": True, "format": img.format, "size": img.size}
def png(w, h):
buf = io.BytesIO()
Image.new("RGB", (w, h), "teal").save(buf, "PNG")
return buf.getvalue()
client = TestClient(app)
tests = {
"photo.png": png(320, 240),
"script.exe": b"MZ\x90\x00",
"fake.png": b"<?php echo 1; ?>",
"doc.pdf": b"%PDF-1.7 ...",
"broken.png": png(64, 64)[:60],
}
for name, data in tests.items():
r = client.post("/avatar", files={"file": (name, data, "image/png")})
print(f"{name:11} {r.status_code} {r.json()}")
Output:
photo.png 200 {'ok': True, 'format': 'PNG', 'size': [320, 240]}
script.exe 415 {'detail': '.exe not allowed'}
fake.png 422 {'detail': 'file content does not match extension'}
doc.pdf 415 {'detail': 'avatar must be an image'}
broken.png 422 {'detail': 'not a valid image'}
Each bad file was stopped at a different layer: the .exe by the allowlist (415 Unsupported Media Type), the PHP code disguised as a PNG by the magic-byte check, the PDF by the endpoint rule and the truncated image by Image.verify() (422). Remember to call await file.seek(0) after peeking so later code reads the file from the start. For a reusable version, move check_upload into a dependency with Depends, as shown in our FastAPI dependency injection guide, and to resize or watermark accepted photos see resizing, cropping and watermarking images with Pillow.
Step 5: limit body size and form parts (new in FastAPI 0.164 and 0.165)
Until this month, limiting upload size in FastAPI meant writing your own middleware or relying on Nginx's client_max_body_size. FastAPI 0.164.0 added a max_body_size setting and 0.165.0 added form_limits, both on the app, on an APIRouter, in include_router() and on a single path operation. The most specific limit wins, so you can keep JSON endpoints tight at 1 MiB and allow bigger bodies only where uploads happen.
from typing import Annotated
from fastapi import APIRouter, FastAPI, Form, UploadFile
from fastapi.testclient import TestClient
MiB = 1024 * 1024
# New in FastAPI 0.164 / 0.165: body size and form parsing limits
app = FastAPI(max_body_size=1 * MiB, form_limits={"max_files": 3, "max_part_size": 512 * 1024})
uploads = APIRouter(prefix="/uploads", max_body_size=20 * MiB)
@app.post("/notes")
async def note(text: Annotated[str, Form()]):
return {"chars": len(text)}
@uploads.post("/video")
async def video(file: UploadFile):
return {"filename": file.filename, "MiB": round(file.size / MiB, 1)}
@uploads.post("/avatar", max_body_size=2 * MiB)
async def avatar(file: UploadFile):
return {"filename": file.filename, "MiB": round(file.size / MiB, 1)}
@uploads.post("/batch")
async def batch(files: list[UploadFile]):
return {"count": len(files)}
app.include_router(uploads)
client = TestClient(app)
def show(r):
try:
return r.json()
except ValueError:
return r.text
def send(path, name, mib):
r = client.post(path, files={"file": (name, b"x" * int(mib * MiB))})
print(f"{path:17} {mib:>4} MiB -> {r.status_code} {show(r)}")
send("/uploads/video", "clip.mp4", 12)
send("/uploads/avatar", "me.png", 1.5)
send("/uploads/avatar", "huge.png", 5)
r = client.post("/notes", data={"text": "a" * 700_000})
print(f"{'/notes':17} 700 KB -> {r.status_code} {show(r)}")
four = [("files", (f"f{i}.txt", b"hi")) for i in range(4)]
r = client.post("/uploads/batch", files=four[:3])
print(f"{'/uploads/batch':17} 3 files -> {r.status_code} {show(r)}")
r = client.post("/uploads/batch", files=four)
print(f"{'/uploads/batch':17} 4 files -> {r.status_code} {show(r)}")
Output:
/uploads/video 12 MiB -> 200 {'filename': 'clip.mp4', 'MiB': 12.0}
/uploads/avatar 1.5 MiB -> 200 {'filename': 'me.png', 'MiB': 1.5}
/uploads/avatar 5 MiB -> 413 Content Too Large
/notes 700 KB -> 400 {'detail': 'Field exceeded maximum size of 512KB.'}
/uploads/batch 3 files -> 200 {'count': 3}
/uploads/batch 4 files -> 400 {'detail': 'Too many files. Maximum number of files is 3.'}
The 12 MiB video passed because the router allows 20 MiB, while the avatar endpoint overrides that with its own 2 MiB limit and returned 413 Content Too Large for 5 MiB. FastAPI counts the bytes it actually reads, so the limit also works when a client sends the body in chunks without a Content-Length header, and it stops reading as soon as the limit is crossed. The form_limits settings protect the multipart parser itself: max_files (default 1,000), max_fields (default 1,000) and max_part_size for each text field (default 1 MiB). Breaking them returns 400, as the 700 KB note field and the fourth file show. Note that max_body_size covers the whole body, including all files and multipart overhead, so set it a little above your largest real file. Combine it with request rate limits from our rate limiting and security headers article so one client cannot flood you with many medium-sized uploads.
Step 6: a real server with upload and download
To finish, we run the app with Uvicorn in a background thread, upload a real 1.8 MB CSV from disk with an httpx client (which streams the open file instead of reading it all), download it again with FileResponse and compare hashes. Path(name).name strips any directory parts, which blocks path traversal in both endpoints.
import hashlib
import threading
import time
from pathlib import Path
import httpx
import uvicorn
from fastapi import FastAPI, HTTPException, UploadFile
from fastapi.responses import FileResponse
STORE = Path("store")
STORE.mkdir(exist_ok=True)
app = FastAPI(max_body_size=50 * 1024 * 1024)
@app.post("/files")
def upload(file: UploadFile): # plain def runs in a worker thread
name = Path(file.filename or "file").name # strip any directories
with (STORE / name).open("wb") as out:
while chunk := file.file.read(1024 * 1024):
out.write(chunk)
return {"stored": name, "bytes": (STORE / name).stat().st_size}
@app.get("/files/{name}")
def download(name: str):
path = STORE / Path(name).name
if not path.is_file():
raise HTTPException(404, "not found")
return FileResponse(path, filename=path.name, media_type="application/octet-stream")
server = uvicorn.Server(uvicorn.Config(app, port=8765, log_level="warning"))
threading.Thread(target=server.run, daemon=True).start()
while not server.started:
time.sleep(0.05)
src = Path("sales_2026.csv")
src.write_text("month,revenue\n" + "".join(f"{m},{m * 1250}\n" for m in range(1, 13)) * 20_000)
with httpx.Client(base_url="http://127.0.0.1:8765") as http:
with src.open("rb") as f:
r = http.post("/files", files={"file": (src.name, f, "text/csv")})
print("upload :", r.status_code, r.json())
r = http.get(f"/files/{src.name}")
print("download:", r.status_code, r.headers["content-disposition"], len(r.content), "bytes")
same = hashlib.sha256(r.content).digest() == hashlib.sha256(src.read_bytes()).digest()
print("identical:", same)
print("missing :", http.get("/files/nope.txt").status_code)
server.should_exit = True
src.unlink()
for p in STORE.iterdir():
p.unlink()
STORE.rmdir()
Output:
upload : 200 {'stored': 'sales_2026.csv', 'bytes': 1840014}
download: 200 attachment; filename="sales_2026.csv" 1840014 bytes
identical: True
missing : 404
The downloaded file is byte-for-byte identical, the Content-Disposition: attachment header makes browsers save it with the right name, and a missing file gives a clean 404. FileResponse streams from disk and supports HTTP range requests, so it is also fine for large media files.
Quick reference
| Task | Code |
|---|---|
| Single file | file: UploadFile |
| Small file as bytes | data: Annotated[bytes, File()] |
| Multiple files | files: list[UploadFile] |
| Form field next to files | title: Annotated[str, Form()] |
| Read in chunks | while chunk := file.file.read(1024 * 1024): ... |
| Peek then rewind | await file.read(8) then await file.seek(0) |
| Total body limit | FastAPI(max_body_size=10 * 1024 * 1024) |
| Per route limit | @router.post("/x", max_body_size=...) |
| Parser limits | form_limits={"max_files": 3, "max_part_size": 512 * 1024} |
| Send a file back | FileResponse(path, filename="report.csv") |
Common errors and fixes
Form data requires "python-multipart" to be installed: runpip install python-multipartor installfastapi[standard].- 422 with
loc: ["body", "file"]: the form field name sent by the client does not match the parameter name, or the request is notmultipart/form-data. With JavaScript, do not set theContent-Typeheader yourself when sendingFormData; the browser adds the boundary. - Server memory grows during uploads: you are calling
await file.read()on large files. Copy in chunks as in step 3. - Saved file is empty or corrupt: you read part of the file for validation and forgot
await file.seek(0). - 413 Content Too Large: the request crossed
max_body_size. Remember that the limit counts every file in the request plus multipart overhead, and that a proxy such as Nginx may have its own lower limit. - 400 Too many files / Field exceeded maximum size: a
form_limitssetting was hit; raise it for that route only.
Production checklist
Set a global max_body_size and raise it only on upload routes. Validate extension, magic bytes and, for images, decode them. Generate your own filenames and store files outside the web root or in object storage such as S3, saving the original name, size, hash and owner in the database. Run heavy work such as virus scanning, thumbnails or OCR in a background job after the upload returns, and protect upload endpoints with authentication and rate limits. Finally, log rejected uploads, because a burst of 415 and 413 responses is often the first sign of someone probing your API.
Summary
FastAPI file uploads come down to a few building blocks: UploadFile for each file, list[UploadFile] and Form() for richer forms, chunked copying for large files, layered validation that never trusts the client, and since November 2026 built-in max_body_size and form_limits settings that finally make size limits a one-line configuration. With these patterns you can safely accept photos, documents and datasets in any FastAPI project.