DEV Community

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

Posted on โ€ข Edited on

1

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 ๐Ÿš€


Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong ยท web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video ๐ŸŒถ๏ธ๐Ÿ”ฅ

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

DevCycle image

Ship Faster, Stay Flexible.

DevCycle is the first feature flag platform with OpenFeature built-in to every open source SDK, designed to help developers ship faster while avoiding vendor-lock in.

Start shipping

๐Ÿ‘‹ Kindness is contagious

Explore this insightful write-up embraced by the inclusive DEV Community. Tech enthusiasts of all skill levels can contribute insights and expand our shared knowledge.

Spreading a simple "thank you" uplifts creatorsโ€”let them know your thoughts in the discussion below!

At DEV, collaborative learning fuels growth and forges stronger connections. If this piece resonated with you, a brief note of thanks goes a long way.

Okay