0
0
FastapiHow-ToBeginner · 3 min read

How to Use UploadFile in FastAPI: Simple File Upload Guide

In FastAPI, use UploadFile to receive files in your API endpoints by declaring it as a parameter with File(). This allows efficient file handling with async support and access to file metadata and content.
📐

Syntax

The basic syntax to use UploadFile in FastAPI is to declare a function parameter with type UploadFile and use File() from fastapi to mark it as a file input.

Example parts:

  • file: UploadFile - declares the parameter as an uploaded file.
  • = File(...) - tells FastAPI this parameter is required and comes from the file upload.
python
from fastapi import FastAPI, UploadFile, File

app = FastAPI()

@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename, "content_type": file.content_type}
💻

Example

This example shows a FastAPI endpoint that accepts a file upload, reads its content asynchronously, and returns the filename and size in bytes.

python
from fastapi import FastAPI, UploadFile, File

app = FastAPI()

@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
    content = await file.read()  # Read file content asynchronously
    return {
        "filename": file.filename,
        "content_type": file.content_type,
        "size_bytes": len(content)
    }
Output
{"filename": "example.txt", "content_type": "text/plain", "size_bytes": 1234}
⚠️

Common Pitfalls

Common mistakes when using UploadFile include:

  • Not using async and await when reading the file content, which can block the server.
  • Using bytes type instead of UploadFile, which loads the whole file into memory and is inefficient for large files.
  • Forgetting to import File from fastapi to mark the parameter as a file input.

Wrong way (blocking read):

def upload_file(file: UploadFile = File(...)):
    content = file.file.read()  # blocking call, not async
    return {"size": len(content)}

Right way (async read):

async def upload_file(file: UploadFile = File(...)):
    content = await file.read()  # async read
    return {"size": len(content)}
📊

Quick Reference

Tips for using UploadFile in FastAPI:

  • Use UploadFile for efficient file handling with async support.
  • Always use await file.read() to read file content asynchronously.
  • Access file.filename and file.content_type for metadata.
  • Use File(...) to mark the parameter as required file input.
  • Close the file with await file.close() if you finish early to free resources.

Key Takeaways

Use UploadFile with File() in FastAPI endpoints to handle file uploads efficiently.
Always read file content asynchronously with await file.read() to avoid blocking.
Access file metadata like filename and content_type directly from UploadFile.
Avoid using bytes type for large files to prevent memory issues.
Remember to import File from fastapi and mark file parameters properly.