Lesson 35 of 59Product features
File Uploads and Object Storage
Accept files in FastAPI safely: real size limits, magic-byte checks, server-made keys, presigned POST uploads to S3, and a scan-then-ready pipeline.
This unit covers the features almost every product asks for sooner or later, each one built on the database, queue and auth pieces you already have. The first version of almost every upload feature looks the same: a route takes bytes, writes them to ./uploads/{filename}, and returns the path. It works in the demo. Then a customer uploads a 900 MB video and a worker runs out of memory, someone uploads ../../app/main.py, a "photo" turns out to be an HTML page that steals sessions, and the second server behind the load balancer cannot find files the first one saved. This lesson builds the version that survives production: how FastAPI really receives a file, how to limit it, how to tell what it actually is, where the bytes and the metadata go, and how to let large files skip your API entirely.
How FastAPI receives a file
Files arrive as multipart/form-data, the encoding an HTML form uses. FastAPI parses it with the python-multipart package, so install it (uv add python-multipart), or the app will refuse to start when a route declares a file. A file parameter is an UploadFile, and ordinary fields that travel with it are Form() parameters:
from typing import Annotated
from fastapi import APIRouter, File, Form, UploadFile
router = APIRouter()
@router.post("/documents")
async def upload_documents(
files: Annotated[list[UploadFile], File()],
title: Annotated[str, Form(max_length=200)],
) -> dict:
out = []
for f in files:
head = await f.read(16) # async read of the first bytes
await f.seek(0) # rewind before using it again
out.append({"name": f.filename, "declared": f.content_type, "size": f.size})
return {"title": title, "files": out}UploadFile wraps a Python SpooledTemporaryFile. Small files stay in memory, and anything over 1 MB rolls over to a temporary file on disk. You get async read, seek and write, plus .file (the underlying file object you can pass to libraries), .filename, .content_type, .size and .headers. Use list[UploadFile] for several files under one field name.
You could also declare file: Annotated[bytes, File()]. That hands you the whole file as one bytes object in memory, which is fine for a 20 KB CSV and a crash waiting to happen for anything a user picks. Prefer UploadFile.
Two facts surprise people. First, you cannot mix a JSON body with files in one request: multipart is form encoding, so other fields come as Form() fields (FastAPI also accepts a Pydantic model as Annotated[Meta, Form()], which validates the form fields as one object). Second, and more important: FastAPI parses the entire multipart body before your function runs. By the time your code reads f.size, every byte has already been received and spooled to disk. Any size check inside the route is too late to protect the server.
file: UploadFile. Your function's first line checks file.size and raises 413 if it is over 10 MB. What has already happened?Limits that actually work
Every upload endpoint needs three limits: total size, number of files, and time. Set each at more than one layer.
Size. The Content-Length header is whatever the client chose to send, and a chunked request has none at all, so you cannot trust it alone. Start at the reverse proxy: nginx's client_max_body_size (its default is only 1 MB, which is why uploads mysteriously fail with 413 behind nginx) or your load balancer's equivalent. Then enforce it in the app as well, because proxies get reconfigured and local runs have none. Starlette's form parser has limits (max_files, max_fields, and max_part_size for non-file fields), but none of them caps the size of a file part, and FastAPI calls the parser with the defaults. The reliable app-level fix is a small ASGI middleware that counts body bytes as they stream in and stops the moment the total passes the cap:
from fastapi import HTTPException
from starlette.types import ASGIApp, Message, Receive, Scope, Send
class MaxBodySize:
def __init__(self, app: ASGIApp, max_bytes: int) -> None:
self.app = app
self.max_bytes = max_bytes
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
return await self.app(scope, receive, send)
received = 0
async def counting_receive() -> Message:
nonlocal received
message = await receive()
if message["type"] == "http.request":
received += len(message.get("body", b""))
if received > self.max_bytes:
raise HTTPException(status_code=413, detail="Upload too large")
return message
await self.app(scope, counting_receive, send)
# app.add_middleware(MaxBodySize, max_bytes=10 * 1024 * 1024)It works for chunked requests too, because it counts real bytes rather than believing a header. FastAPI re-raises an HTTPException that happens while it reads the body, so the client gets a clean 413. If different routes need different caps, check scope["path"] inside the middleware.
Number of files. Check len(files) and reject early, and remember the parser accepts up to 1,000 parts by default. If you need a tight cap before parsing, parse yourself with await request.form(max_files=5, max_fields=20) in a route that takes Request.
Time. A client that sends one byte every few seconds ties up a connection for minutes (the slowloris pattern). Request body timeouts belong at the proxy (nginx client_body_timeout, your load balancer's idle timeout). This is one more reason big files should not go through your API at all, which is where this lesson is heading.
Never trust the name or the type
filename and content_type are both typed by the client. A browser fills them in honestly, and an attacker's script fills in whatever passes your check. So:
- Detect the type from the bytes. Real formats start with a signature, or "magic bytes": PNG files begin
\x89PNG, PDFs begin%PDF-. Libraries likefiletype(pure Python) orpython-magic(wraps libmagic) recognise hundreds. Keep an allow list of types you accept, and reject everything else. - Never build a path from the filename.
../../app/main.pyis a path traversal attack. Generate the storage key yourself and keep the original name only as display metadata. - Re-encode images. Open with Pillow, apply
ImageOps.exif_transpose, and save a fresh JPEG or PNG. That strips EXIF (including GPS coordinates of someone's home), and destroys "polyglot" files that are a valid image and a valid script at the same time. Pillow'sImage.MAX_IMAGE_PIXELSguard against decompression bombs (a tiny file that expands to gigapixels) should stay on. - Treat SVG and HTML as code. An SVG can contain
<script>. If you serve a user's SVG from your main domain, it runs with your cookies. Either refuse SVG, sanitise it, or serve user content from a separate domain (for exampleusercontent.example.com) withContent-Disposition: attachmentandX-Content-Type-Options: nosniff.
Here is the core of that logic using only the standard library. Read the output and decide whether you agree with each verdict:
Press Run (⌘ Enter) to see what happens.The "cat" was HTML, and the "PDF" was a zip. The traversal name collapsed to a harmless main.py, but notice the storage key never used it anyway: the extension comes from the sniffed type and the name from uuid4. Magic bytes are a strong first filter, not a guarantee (a file can start like a PDF and be malformed after that), which is why re-encoding and scanning come later.
Using safe_display_name from the block above, what does this print?
print(safe_display_name("résumé (final).pdf"))Metadata in Postgres, bytes in object storage
As Storage and Blobs explained, the bytes go to object storage and a row in your database describes them. On the FastAPI side that row is worth designing carefully, because it is what your authorization checks, listings and cleanup jobs read:
class Upload(Base):
__tablename__ = "uploads"
id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4)
owner_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
key: Mapped[str] = mapped_column(unique=True) # uploads/42/9f1c....png
original_name: Mapped[str] # display only
declared_type: Mapped[str] # what the client said
content_type: Mapped[str | None] # what we detected
size: Mapped[int | None]
sha256: Mapped[str | None]
status: Mapped[str] = mapped_column(default="pending") # pending, scanning, ready, rejected
created_at: Mapped[datetime] = mapped_column(server_default=func.now())Any S3-compatible store works with the same code: AWS S3, Cloudflare R2, Google Cloud Storage's interoperability mode, or MinIO in Docker locally (point endpoint_url at it). The catch is that boto3 is synchronous. Calling s3.upload_fileobj(...) inside an async def route blocks the event loop for every user while the bytes travel, exactly the trap from Background Tasks and Async. Either run it in the threadpool, or use an async client such as aioboto3:
import boto3
from fastapi.concurrency import run_in_threadpool
s3 = boto3.client("s3", endpoint_url=settings.s3_endpoint) # one client, created once
@router.post("/avatars", status_code=201)
async def upload_avatar(file: Annotated[UploadFile, File()], user: CurrentUser, db: DB):
head = await file.read(16)
content_type = sniff(head)
if content_type not in {"image/png", "image/jpeg"}:
raise HTTPException(415, "Only PNG or JPEG images")
await file.seek(0)
key = storage_key(user.id, content_type)
await run_in_threadpool(
s3.upload_fileobj, file.file, settings.bucket, key,
ExtraArgs={"ContentType": content_type},
)
upload = Upload(owner_id=user.id, key=key, original_name=file.filename or "file",
declared_type=file.content_type or "", content_type=content_type,
size=file.size, status="pending")
db.add(upload)
await db.commit()
return {"id": str(upload.id), "status": upload.status}A boto3 client is thread-safe, so create one at startup and share it. A boto3 Session is not, so do not share sessions between threads. Notice the order: bytes first, row second. If the row insert fails you have an orphan object, which a cleanup job can delete. The other order leaves a row pointing at nothing, which breaks users.
Direct uploads with a presigned POST
Routing bytes through FastAPI is fine for avatars. For videos, datasets and anything above a few tens of megabytes, let the client upload straight to storage, as Storage and Blobs showed with a presigned PUT. A PUT URL has a weakness: it cannot express "between 1 byte and 10 MB". An S3 presigned POST carries a signed policy with conditions, and S3 itself rejects an upload that breaks them:
@router.post("/uploads", status_code=201)
async def start_upload(body: StartUpload, user: CurrentUser, db: DB):
if body.content_type not in ALLOWED:
raise HTTPException(415, "Unsupported type")
key = storage_key(user.id, body.content_type)
upload = Upload(owner_id=user.id, key=key, original_name=body.filename,
declared_type=body.content_type, status="pending")
db.add(upload)
await db.commit()
post = s3.generate_presigned_post( # signs locally, no network call
Bucket=settings.bucket,
Key=key,
Fields={"Content-Type": body.content_type},
Conditions=[
["content-length-range", 1, 50 * 1024 * 1024],
{"Content-Type": body.content_type},
],
ExpiresIn=300,
)
return {"id": str(upload.id), "url": post["url"], "fields": post["fields"]}The browser sends a multipart form to url with every entry of fields plus the file last. Then you need to learn that it finished. Either the client calls POST /uploads/{id}/complete, or S3 sends an event notification (to SQS or EventBridge) that a worker consumes. In both cases verify, do not believe: call head_object on the key, check the real size and content type S3 recorded, and only then move the row on. A "complete" call is just the client's claim. For files over roughly 100 MB, use multipart uploads (each part gets its own presigned URL), covered in Storage and Blobs.
The API checks auth, the type allow list and the user's storage quota, then inserts a pending row.
Serving files back
Private files should not be public objects. For downloads, check that the user may see the row, then return a short-lived presigned GET (minutes, not days) and redirect to it. Pass ResponseContentDisposition="attachment; filename=..." in its Params so the browser downloads rather than renders anything risky. For public, heavily read files like product images, put a CDN in front, and use CDN signed URLs or signed cookies (CloudFront supports both) when the content is private but hot.
For small local cases, FastAPI has FileResponse, which streams a file from disk, sets Content-Disposition when you pass filename, and answers HTTP Range requests with 206 Partial Content, which video players and resumable downloads rely on. StreamingResponse streams any iterator, for example a generated CSV export. Neither should serve bytes you have not finished scanning.
Processing: pending to ready
Every upload is untrusted until a worker has looked at it. Model that explicitly with a status column and a small state machine, so no code path can serve a file that skipped a step:
A row exists and a URL was issued, but no bytes are proven. Nothing may read the object.
Make the worker idempotent, because queues deliver twice (Task Queues with Celery covered why). Processing the same key again should produce the same thumbnails and the same final status, not a duplicate.
Testing uploads
TestClient sends multipart for you. Pass files= as a dict or a list of tuples (field, (filename, bytes, content_type)), and form fields as data=:
def test_rejects_html_disguised_as_jpeg(client):
files = {"file": ("cat.jpg", b"<html><script>alert(1)</script>", "image/jpeg")}
r = client.post("/avatars", files=files)
assert r.status_code == 415
def test_rejects_oversized_body(client):
files = {"file": ("big.png", b"\x89PNG\r\n\x1a\n" + b"0" * (11 * 1024 * 1024), "image/png")}
assert client.post("/avatars", files=files).status_code == 413For storage, moto fakes AWS in memory (from moto import mock_aws, then create the bucket in a fixture), which is fast and good for unit tests. For integration tests, run MinIO in Docker, as Testing with Real Databases did for Postgres, because a fake cannot catch a wrong endpoint, region or policy.
Match each upload threat to the defence that stops it.
Put the direct-upload flow in order.
- Tap the steps below in the right order.
- UploadFile
- FastAPI's file parameter type: a spooled temporary file with async read and seek, plus filename, content type and size.
- multipart/form-data
- The request encoding for forms with files. Each field and file is a separate part with its own headers.
- magic bytes
- The fixed signature at the start of a file format, used to detect the real type regardless of name or header.
- path traversal
- Using
../in a user-supplied name to read or write outside the intended folder. - presigned POST
- A signed S3 form policy that lets a client upload directly, with conditions such as a size range and content type.
- head_object
- An S3 call that returns an object's metadata (size, type, ETag) without downloading it, used to verify an upload.
- polyglot file
- A file that is valid in two formats at once, such as an image that is also a script. Re-encoding destroys it.