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