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

Utkarsh Rastogi @awslearnerdaily

About: Cloud Developer | AWS Community Builder | I write about AI, serverless, DevOps & real-world cloud projects using AWS, Bedrock, LangChain & more to help others learn and build smarter solutions.

Location:
India
Joined:
Mar 22, 2025

Day 6 : File Uploads & Form Handling in FastAPI

Publish Date: Jun 14
1 1

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 🚀


Comments 1 total

Add comment