Forms and File Uploads
Receive HTML form fields with Form() and files with UploadFile. Build a profile-photo upload that checks the size and the real file type, saves under its own name, and works from a real browser and curl. Tested with a text file pretending to be a PNG, a 2 MB file and a filename that tries to escape the folder.
What you will be able to do
- Receive form fields with Form(), and a whole form as a model
- Receive one or many files with UploadFile
- Check a file’s size and real type before keeping it
- Save uploads safely under your own file name
- Send forms and files with TestClient, curl and an HTML form
- Know why JSON and files do not mix in one request
The idea, in plain English
Until now clients sent JSON. But an HTML form - a login page, a "change profile" page - sends its fields in another format. And files cannot travel inside JSON at all. Both arrive as form data; with files, the format is called multipart/form-data.
In FastAPI a form field is an argument with Form(), and a file is an argument typed UploadFile. FastAPI checks them like everything else - missing or wrong values give 422. But a file’s name and type are written by the client, so you must check the file yourself.
We build a profile form with a photo, attack it with bad files, and use it from TestClient, curl and a real browser. FastAPI 0.143.0, python-multipart 0.0.32 (it comes with fastapi[standard]).
Worked example: A profile form with a name, a city and a photo - from TestClient, from curl and from a real browser.
1 - A real photo
ravi.png, 105 bytes, starts with the PNG signature. Saved under a new name.
Every photo passes the same checks before it is saved. Real results from our profile form.
Words you will see in this lesson
A few words about forms and files.
Form dataFields sent like name=Ravi&city=Hyderabad (application/x-www-form-urlencoded) - what a plain HTML form sends.multipart/form-dataThe format for forms with files: the body has one part per field or file.UploadFileFastAPI’s object for an uploaded file: name, type, size and the bytes.MIME typeA file type name like image/png or text/csv. For uploads, the client chooses it.File signatureThe first bytes of a file that show its real type. Every PNG starts with \x89PNG.UUIDA long random id, like 4477a56bbbdf4f22a0cc25f46030e926 - good for file names.An everyday example: a passport photo at the office
You hand in a form and a photo at a government office:
- The clerk reads the boxes on the form - those are form fields.
- You say "this is a passport photo". The clerk does not just believe you - they look at it. That is checking the real type, not the content_type.
- Too big? It is refused at once - a size limit.
- Your photo is filed under the office’s own number, not the name you wrote on the back - a UUID file name.
Example 1 - a profile form with a photo
Two endpoints and a page:
- login - two form fields with Form(). Without Form(), FastAPI would look for them in the query string.
- save_profile - name with Form(min_length=2), city optional, and photo: UploadFile.
- await photo.read() gives the bytes. First the size check (413), then the type check: do the bytes start with a PNG or JPEG signature? (400)
- The file is saved as uploads/<uuid>.png - our name, with the extension from the real type.
- gallery - list[UploadFile] takes many files under one field name.
- form_page - a tiny HTML form. enctype="multipart/form-data" is required for files.
import uuid
from pathlib import Path
from typing import Annotated
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from fastapi.responses import HTMLResponse
app = FastAPI()
UPLOADS = Path("uploads")
UPLOADS.mkdir(exist_ok=True)
MAX_BYTES = 1_000_000 # 1 MB
SIGNATURES = {b"\x89PNG\r\n\x1a\n": ".png", b"\xff\xd8\xff": ".jpg"} # the first bytes of real images
@app.post("/login")
def login(username: Annotated[str, Form()], password: Annotated[str, Form()]):
return {"username": username, "password_length": len(password)}
@app.post("/profile")
async def save_profile(
name: Annotated[str, Form(min_length=2)],
photo: UploadFile, # a file from the form
city: Annotated[str | None, Form()] = None,
):
data = await photo.read()
if len(data) > MAX_BYTES:
raise HTTPException(status_code=413, detail="Photo is larger than 1 MB")
ext = next((e for sig, e in SIGNATURES.items() if data.startswith(sig)), None)
if ext is None:
raise HTTPException(status_code=400, detail="Only PNG or JPEG photos")
saved = UPLOADS / f"{uuid.uuid4().hex}{ext}" # OUR name, never the client's
saved.write_bytes(data)
return {"name": name, "city": city, "sent_as": photo.filename,
"content_type": photo.content_type, "size": photo.size, "saved_as": saved.name}
@app.post("/gallery")
async def gallery(photos: list[UploadFile]): # many files under one name
return [{"file": p.filename, "size": p.size} for p in photos]
@app.get("/", response_class=HTMLResponse)
def form_page():
return """<form action="/profile" method="post" enctype="multipart/form-data">
<input name="name" placeholder="Name"> <input name="city" placeholder="City">
<input type="file" name="photo"> <button>Save</button>
</form>"""from fastapi.testclient import TestClient
from profile import app
c = TestClient(app)
def show(label, r):
print(f"{label:<20} -> {r.status_code} {r.text[:230]}")
show("login (form)", c.post("/login", data={"username": "ravi", "password": "s3cret"}))
show("login (JSON)", c.post("/login", json={"username": "ravi", "password": "s3cret"}))
png = open("ravi.png", "rb").read()
show("good photo", c.post("/profile", data={"name": "Ravi", "city": "Hyderabad"},
files={"photo": ("ravi.png", png, "image/png")}))
show("no city", c.post("/profile", data={"name": "Ravi"}, files={"photo": ("ravi.png", png, "image/png")}))
show("text as image/png", c.post("/profile", data={"name": "Ravi"},
files={"photo": ("photo.png", open("notes.txt", "rb").read(), "image/png")}))
show("2 MB file", c.post("/profile", data={"name": "Ravi"},
files={"photo": ("big.png", open("big.png", "rb").read(), "image/png")}))
show("no photo", c.post("/profile", data={"name": "Ravi"}))
show("name too short", c.post("/profile", data={"name": "R"}, files={"photo": ("ravi.png", png, "image/png")}))
show("tricky filename", c.post("/profile", data={"name": "Ravi"},
files={"photo": ("../../main.py", png, "image/png")}))
show("gallery", c.post("/gallery", files=[("photos", ("a.png", png, "image/png")),
("photos", ("b.png", png, "image/png"))]))Reading the output
- login (form) worked. login (JSON) gave 422 "Field required" for both fields - a form endpoint does not read JSON.
- good photo - UploadFile told us sent_as "ravi.png", content_type "image/png" and size 105, and the file was saved under a random name.
- no city - fine, it is optional (null).
- text as image/png - the client claimed image/png, but the bytes were "not a photo" - 400.
- 2 MB file - 413.
- no photo or a short name - normal 422s with loc ["body", ...].
- tricky filename - the client sent "../../main.py" as the name and FastAPI passed it on exactly. We never used it for the path, so nothing happened.
login (form) -> 200 {"username":"ravi","password_length":6}
login (JSON) -> 422 {"detail":[{"type":"missing","loc":["body","username"],"msg":"Field required","input":null},{"type":"missing","loc":["body","password"],"msg":"Field required","input":null}]}
good photo -> 200 {"name":"Ravi","city":"Hyderabad","sent_as":"ravi.png","content_type":"image/png","size":105,"saved_as":"4477a56bbbdf4f22a0cc25f46030e926.png"}
no city -> 200 {"name":"Ravi","city":null,"sent_as":"ravi.png","content_type":"image/png","size":105,"saved_as":"f1d5bf4ab86146298794b34b01b0cdfa.png"}
text as image/png -> 400 {"detail":"Only PNG or JPEG photos"}
2 MB file -> 413 {"detail":"Photo is larger than 1 MB"}
no photo -> 422 {"detail":[{"type":"missing","loc":["body","photo"],"msg":"Field required","input":null}]}
name too short -> 422 {"detail":[{"type":"string_too_short","loc":["body","name"],"msg":"String should have at least 2 characters","input":"R","ctx":{"min_length":2}}]}
tricky filename -> 200 {"name":"Ravi","city":null,"sent_as":"../../main.py","content_type":"image/png","size":105,"saved_as":"33b770b432a44918bcdf944eac197888.png"}
gallery -> 200 [{"file":"a.png","size":105},{"file":"b.png","size":105}]Never trust the name or the type
Both filename and content_type are written by the client:
- A file name can contain ../ - saving to uploads/{photo.filename} could write outside the folder, even over your own code.
- A content_type of image/png says nothing about the bytes - our text file had it.
- So: decide the type from the first bytes (or with an image library), and save under a name YOU make - a uuid plus the real extension.
- Keep the client’s name only as a label in your database, if you need it.
Watch out: Never serve uploaded files from a folder where the server runs code, and do not send them back as text/html - an "image" with HTML inside could run scripts in your users’ browsers.
Size limits and where the file waits
We added /peek, which does not read the file, and sent two files:
- The 105-byte file was kept in memory; the 2 MB file was already on disk ("kept_on_disk": true). UploadFile keeps small files in memory and moves bigger ones (over 1 MB) to a temporary file.
- photo.size was 2000008 before our code read anything - the whole upload had arrived before the function ran.
- So our 1 MB check protects disk space and your later code, but the bytes were already received.
- Put a real body-size limit in front of the app too, in the proxy (for example nginx client_max_body_size) - Module 10.
peek small -> 200 {"size":105,"kept_on_disk":false}
peek 2 MB -> 200 {"size":2000008,"kept_on_disk":true}A whole form as a model - and why JSON and files do not mix
- Annotated[Signup, Form()] reads all form fields into a Pydantic model. "31" became 31 and "on" became True; "old" for age gave 422.
- mixed asked for a JSON model (info: Signup) and a file. A request can have only one body format, and with a file it is multipart - so info was "Field required".
- Need structured data with a file? Use form fields (or a form model), or send the file first and the JSON in a second request.
from typing import Annotated
from fastapi import FastAPI, Form, UploadFile
from pydantic import BaseModel
app = FastAPI()
class Signup(BaseModel): # form fields described as a model
username: str
age: int
newsletter: bool = False
@app.post("/signup")
def signup(data: Annotated[Signup, Form()]):
return data
@app.post("/mixed")
async def mixed(info: Signup, photo: UploadFile): # a JSON model AND a file: does not work
return {"ok": True}
@app.post("/peek")
async def peek(photo: UploadFile): # does not read the file
return {"size": photo.size, "kept_on_disk": photo.file._rolled}signup form -> 200 {"username":"ravi","age":31,"newsletter":true}
signup bad age -> 422 {"detail":[{"type":"int_parsing","loc":["body","age"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"old"}]}
mixed -> 422 {"detail":[{"type":"missing","loc":["body","info"],"msg":"Field required","input":null}]}
peek small -> 200 {"size":105,"kept_on_disk":false}
peek 2 MB -> 200 {"size":2000008,"kept_on_disk":true}From a real browser and from curl
We ran the app with uvicorn. A real browser (Playwright) opened the form page, typed the name and city, picked ravi.png and clicked Save. curl -F sent the same form from the terminal.
- Both saved a photo - the uvicorn log shows two POST /profile with 200.
- The browser ended on /profile, showing our JSON. In a real site, answer a form with a 303 redirect to a normal page (Lesson 3.3), so a refresh does not send the form again.
- curl -F name=Ravi sends a field; -F photo=@ravi.png sends a file (the @ means "read this file").
browser now at: /profile
page shows: {"name":"Ravi","city":"Hyderabad","sent_as":"ravi.png","content_type":"image/png","size":105,"saved_as":"f180e6fff4504b9ca231559163d84863.png"}$ curl -s -F name=Ravi -F city=Hyderabad -F photo=@ravi.png http://127.0.0.1:8334/profile
{"name":"Ravi","city":"Hyderabad","sent_as":"ravi.png","content_type":"image/png","size":105,"saved_as":"d70a42cca69a4118b614b09cbc3fa511.png"}Forms and files at a glance
Form fieldNot JSON.
name: Annotated[str, Form(min_length=2)]
Form modelAll fields at once.
data: Annotated[Signup, Form()]
One fileName, type, size, bytes.
photo: UploadFile data = await photo.read()
Many filesSame field name.
photos: list[UploadFile]
Real typeCheck the first bytes.
data.startswith(b"\x89PNG\r\n\x1a\n")
Safe nameNever the client’s.
f"{uuid.uuid4().hex}.png"Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Run fastapi dev profile.py, open /docs and upload a photo with "Try it out". What does Swagger show for the photo field?”
“Upload a real .jpg from your computer. Which extension does saved_as get?”
“Rename a .txt file to .png and upload it. What happens, and why?”
“Send three photos to /gallery with curl: -F photos=@a.png -F photos=@b.png ...”
What usually goes wrong
A name like ../../main.py can escape the folder.
✗ open(f"uploads/{photo.filename}", "wb")✓ name = f"{uuid.uuid4().hex}{ext}"Our text file said image/png. Check the bytes.
✗ if photo.content_type == "image/png": ...✓ if data.startswith(b"\x89PNG\r\n\x1a\n"): ...Form() reads form data only - JSON gave 422 "Field required".
The request is multipart, so the JSON model is always missing. Use form fields.
Without enctype="multipart/form-data" the browser sends only the file name, not the file.
Practice
Write these yourself before opening anything. Getting them wrong first is most of how this sticks.
Add POST /documents that accepts a title (form field, 3-80 characters) and a PDF file (it must start with the bytes %PDF, at most 2 MB). Save it as uploads/<uuid>.pdf and return the title, size and saved name. Then add GET /documents/{saved_name} that sends the file back with FileResponse - checking the name safely (Lesson 3.3).
Show hintHide hint
data.startswith(b"%PDF"). For the download, only allow names that match a uuid pattern, or check the resolved path.
Key points
- Form() reads form fields; a Pydantic model with Form() reads a whole form.
- UploadFile gives filename, content_type, size and the bytes (await read()).
- Small uploads stay in memory; bigger ones go to a temporary file.
- filename and content_type come from the client - never trust them.
- Check the size and the first bytes, and save under your own uuid name.
- One request has one body format: JSON or form data, not both.
- Form and File need python-multipart, which fastapi[standard] installs.
Quick check before you move on
Interview questions
How do you handle file uploads securely?
Limit body size at the proxy and in the app, verify type from content (magic bytes or a parser), generate server-side names, store outside the web root or in object storage, never serve uploads as HTML, and scan if needed.
UploadFile or bytes = File()?
UploadFile streams to a spooled temp file and exposes metadata, so it suits anything non-trivial; bytes loads the whole file into memory and suits only small payloads.
How would you accept large files (hundreds of MB)?
Avoid reading them into memory: stream chunks to storage, or let clients upload directly to object storage with pre-signed URLs and send the API only the resulting key.
Quiz
- 1.
Why did /mixed say info was missing?
- 2.
Why do we save photos under a uuid?
- 3.
Does the 1 MB check stop a 2 MB upload from being received?
- 4.
What must an HTML form have to send files?
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...