Form Data & File Uploads in Python
From the FastAPI cheat sheet ยท Form Data & File Uploads ยท verified Jul 2026
Form Data & File Uploads
Receive form fields and uploaded files in endpoints.
python
from fastapi import FastAPI, File, Form, UploadFile
@app.post("/login/")
async def login(username: str = Form(), password: str = Form()):
return {"username": username}
@app.post("/upload/")
async def upload(file: UploadFile):
contents = await file.read()
return {"filename": file.filename, "size": len(contents)}๐ก Use Form() for form fields and File()/UploadFile for file uploads โ not Pydantic models
โก UploadFile streams to disk โ use it for large files; bytes = File() loads into memory
๐ You cannot mix JSON body (Pydantic) with form/file data in the same endpoint
๐ข Install python-multipart for form/file support: pip install python-multipart
formsfilesupload