DEV Community

Cover image for Day 6 : File Uploads & Form Handling in FastAPI
Utkarsh Rastogi
Utkarsh Rastogi

Posted on • Edited on

Day 6 : File Uploads & Form Handling in FastAPI

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 
Enter fullscreen mode Exit fullscreen mode

πŸ› οΈ 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 } 
Enter fullscreen mode Exit fullscreen mode

✨ This endpoint:

  • βœ… Accepts a file through UploadFile
  • 🧾 Accepts form fields: username (required) and description (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 
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ 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)

Input

Input Entered

Output1

πŸ“ Files Saved Where?

Uploaded files are saved inside the uploads/ folder, created using:

UPLOAD_DIR = "uploads"

Output Saved


πŸ’‘ 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