Handling Forms and File Uploads
📤 Handling Forms and File Uploads in FastAPI
đź§ľ Submitting Forms in FastAPI
FastAPI makes handling HTML form data easy using the Form class.
When a user submits a form, you can directly access the form fields inside your API endpoint — no extra parsing required.
Here’s a simple example:
from fastapi import FastAPI, Form
app = FastAPI(title="Form Handling Example")
@app.post("/submit-form")
async def submit_form(
username: str = Form(...),
email: str = Form(...),
feedback: str = Form(None)
):
"""
Handle form submissions from users.
"""
return {
"message": "Form data received!",
"user": username,
"email": email,
"feedback": feedback or "No feedback provided"
}
👉 How it works:
-
Form(...)tells FastAPI to expect that value from an HTML form. -
The
...(ellipsis) means the field is required, whileNonemeans optional. -
When you send form data (like from an HTML
<form>or a Postman request), FastAPI automatically parses it for you.
🗂️ Uploading Files in FastAPI
Handling file uploads is just as simple. FastAPI supports this out of the box with the File and UploadFile classes.
Here’s how you can create an endpoint that accepts image uploads:
from fastapi import FastAPI, File, UploadFile
app = FastAPI(title="File Upload Example")
@app.post("/upload-file/")
async def upload_file(file: UploadFile = File(...)):
"""
Accept a single file upload from the client.
"""
# Read file contents
contents = await file.read()
# Optionally, save the file
with open(file.filename, "wb") as f:
f.write(contents)
return {"filename": file.filename, "content_type": file.content_type}
👉 How it works:
-
UploadFilegives you access to file attributes likefilename,content_type, andfile(a real file-like object). -
Using
await file.read()reads the content asynchronously. -
You can easily save it to disk, a database, or cloud storage.
đź§ Final Thoughts
FastAPI’s native support for forms and file uploads makes it ideal for data-driven apps — whether you’re building an admin dashboard, a machine learning model uploader, or an image-processing API.