Welcome to Day 6 of the FastAPI Zero to Hero ๐ series!
Today weโll cover an essential part of building web APIs: handling file uploads and form fields in a single POST request.
๐ง What Youโll Learn Today
- Accepting files using
POST /uploadfile
- Saving uploaded files locally
- Handling form data with file uploads
๐ฆ Step 1: Install Multipart Dependency
FastAPI depends on python-multipart
to process form and file data.
pip3 install python-multipart
๐ ๏ธ Step 2: Create File Upload Endpoint(test.py)
Hereโs a complete FastAPI snippet to accept a file and form fields:
from fastapi import FastAPI, File, UploadFile, Form
import shutil
import os
app = FastAPI()
# Create an uploads directory if it doesn't exist
UPLOAD_DIR = "uploads"
os.makedirs(UPLOAD_DIR, exist_ok=True)
@app.post("/uploadfile")
async def upload_file(
file: UploadFile = File(...),
username: str = Form(...),
description: str = Form(None)
):
file_location = f"{UPLOAD_DIR}/{file.filename}"
# Save uploaded file locally
with open(file_location, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
return {
"message": "File uploaded successfully!",
"filename": file.filename,
"content_type": file.content_type,
"uploaded_by": username,
"description": description
}
โจ This endpoint:
- โ
Accepts a file through
UploadFile
- ๐งพ Accepts form fields:
username
(required) anddescription
(optional) - ๐พ Saves the file to a local
uploads/
folder - ๐ค Returns a JSON response confirming the upload
๐ Test Your Endpoint
โ Run the Server
Make sure your test.py
file is saved, then run it using Uvicorn:
uvicorn test:app --host 0.0.0.0 --reload --port 9002
๐งช Try Uploading a File in Swagger UI
Head over to: http://localhost:9002/docs
Then test the /uploadfile
endpoint by providing:
-
username: Your name (e.g.,
utkarsh
) -
description (optional): Some detail about the file (e.g.,
My profile picture
) -
file: Upload any image or document (e.g.,
profile.jpg
,resume.pdf
)
๐ Files Saved Where?
Uploaded files are saved inside the uploads/
folder, created using:
UPLOAD_DIR = "uploads"
๐ก What Else Can You Do?
Here are a few ideas you can try next to level up your FastAPI file handling:
โ
Accept Multiple Files
Allow users to upload more than one file in a single request.
โ
Add File Size or Extension Validation
Use attributes like file.spool_max_size
or manually check extensions (e.g., .jpg
, .pdf
, .csv
) to ensure only supported files are uploaded.
โ
Upload to Cloud (S3, GCS, etc.)
Instead of saving locally, integrate with cloud storage platforms like Amazon S3 using boto3
, Google Cloud Storage, or even Azure Blob Storage for scalable storage solutions.
๐ Wrap-Up
๐ Thatโs it for Day 6! Youโve now learned how to:
- ๐ฅ Accept and process uploaded files
- ๐ Handle form fields in the same request
- ๐พ Save files on the server locally
๐ Credits
Huge thanks to the FastAPI Official Documentation by Sebastiรกn Ramรญrez (@tiangolo) โ the best place to learn and explore everything about FastAPI.
๐จโ๐ป About Me
Hey there! Iโm Utkarsh Rastogi, an AWS Community Builder and passionate cloud-native enthusiast who loves building scalable backend systems and sharing knowledge with the community.
๐ Connect with me: Utkarsh Rastogi
๐ฌ Share Your Thoughts โ I'd Love Your Feedback!
If you enjoyed today's post or learned something new, I'd truly appreciate it if you leave a comment or share your thoughts ๐
Your feedback, questions, or even a quick โ๐ฅ Loved this!โ keeps me motivated to continue this journey and share more in the upcoming #FastAPIDaily posts.
โ
What did you find most helpful?
โ
Anything you'd like explained in the next part?
โ
Suggestions for improvement? Iโm all ears! ๐
Letโs grow and learn together โ one FastAPI day at a time ๐
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more