Full answer
HTML forms and file uploads use application/x-www-form-urlencoded or multipart/form-data, not JSON. FastAPI needs the python-multipart package to parse them (included in fastapi[standard]).
Form fields:
@app.post("/login")
def login(username: Annotated[str, Form()], password: Annotated[str, Form()]): ...Since FastAPI 0.113 a Pydantic model can describe all form fields: data: Annotated[LoginForm, Form()].
Files:
file: UploadFile: recommended. Data is kept in memory up to a limit (1 MB by default), then spooled to a temporary file on disk, so a 200 MB upload does not fill RAM. Attributes:filename,content_type,size,file(the file-like object). Async methods:await file.read(),await file.seek(0),await file.close().file: Annotated[bytes, File()]: the whole file in memory as bytes. Fine for small files only.- Several files:
files: list[UploadFile]. - Optional file:
file: UploadFile | None = None.
You can mix Form() fields and files in one endpoint. You cannot mix them with a JSON body model, because the request has one content type. To send structured data with a file, send it as form fields or a JSON string field.
Security checks you must add yourself:
- Size: reject files over a limit (check
file.sizeor count bytes while reading in chunks). Set limits at the proxy too (client_max_body_sizein Nginx). - Type: do not trust
content_typeor the extension alone; inspect the first bytes ("magic numbers") for critical types. - Name: never use
filenamedirectly as a path; generate your own name to avoid path traversal (../../etc/passwd). - Store uploads in object storage, not the app server's disk.
from typing import Annotated
import uuid
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from fastapi.testclient import TestClient
app = FastAPI()
MAX_BYTES = 1_000_000
PDF_MAGIC = b"%PDF-"
@app.post("/assignments")
async def submit_assignment(
roll_no: Annotated[str, Form(min_length=3)],
subject: Annotated[str, Form()],
file: UploadFile,
):
head = await file.read(5)
if head != PDF_MAGIC:
raise HTTPException(status_code=415, detail="Only PDF files are accepted")
await file.seek(0)
data = await file.read(MAX_BYTES + 1)
if len(data) > MAX_BYTES:
raise HTTPException(status_code=413, detail="File larger than 1 MB")
stored_as = f"{uuid.uuid5(uuid.NAMESPACE_URL, roll_no + subject)}.pdf" # never reuse the client name
return {"roll_no": roll_no, "subject": subject, "original": file.filename,
"stored_as": stored_as, "bytes": len(data)}
@app.post("/avatar")
def small_file(file: Annotated[bytes, File()]):
return {"bytes": len(file)}
c = TestClient(app)
pdf = b"%PDF-1.7\n" + b"x" * 100
r = c.post("/assignments", data={"roll_no": "BCA-17", "subject": "DBMS"},
files={"file": ("../../etc/notes.pdf", pdf, "application/pdf")})
print(r.status_code, r.json())
r = c.post("/assignments", data={"roll_no": "BCA-17", "subject": "DBMS"},
files={"file": ("photo.pdf", b"\x89PNG....", "application/pdf")})
print(r.status_code, r.json())
print(c.post("/avatar", files={"file": ("a.png", b"12345", "image/png")}).json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Requires `pip install python-multipart`. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): 200 {'roll_no': 'BCA-17', 'subject': 'DBMS', 'original': '../../etc/notes.pdf', 'stored_as': 'a51efe6d-9640-5871-884e-05f7869166a6.pdf', 'bytes': 109} 415 {'detail': 'Only PDF files are accepted'} {'bytes': 5}
Key points
- Forms and files need python-multipart
- Form() for fields; UploadFile for files
- UploadFile spools large files to disk
- No JSON body together with form data
- Validate size, type and never trust filename
Common mistakes
- Forgetting to install python-multipart
- Using bytes = File() for large uploads and filling memory
- Trusting the client's content_type, extension or filename
- Trying to send JSON body and files in one request
- Saving uploads on the app server's local disk
Follow-ups
- How would you upload a 2 GB video without holding it in memory?
- How would you let clients upload straight to object storage?
- What is path traversal and how do you prevent it in uploads?
Tips
- Explain UploadFile versus bytes with the memory trade-off
- List the security checks you would add
- Mention python-multipart as a requirement