0
0
FastAPIframework~5 mins

File validation (size, type) in FastAPI

Choose your learning style9 modes available
Introduction

We check files to make sure they are safe and the right kind before saving or using them.

When users upload profile pictures and you want only images under 2MB.
When accepting documents but only want PDFs or Word files.
When limiting file size to avoid using too much server space.
When preventing harmful files like executables from being uploaded.
Syntax
FastAPI
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import JSONResponse

app = FastAPI()

@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
    # Check file size and type here
    pass

Use UploadFile to handle uploaded files efficiently.

File size must be checked by reading the file content or using headers.

Examples
This example checks if the file is a JPEG or PNG and smaller than 2MB.
FastAPI
from fastapi import FastAPI, File, UploadFile, HTTPException

app = FastAPI()

@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
    if file.content_type not in ["image/jpeg", "image/png"]:
        raise HTTPException(status_code=400, detail="Only JPEG or PNG files allowed")
    contents = await file.read()
    if len(contents) > 2_000_000:
        raise HTTPException(status_code=400, detail="File too large")
    return {"filename": file.filename, "size": len(contents)}
This example allows only PDF files up to 5MB.
FastAPI
from fastapi import FastAPI, File, UploadFile, HTTPException

app = FastAPI()

@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
    allowed_types = ["application/pdf"]
    if file.content_type not in allowed_types:
        raise HTTPException(status_code=400, detail="Only PDF files allowed")
    contents = await file.read()
    max_size = 5_000_000  # 5MB
    if len(contents) > max_size:
        raise HTTPException(status_code=400, detail="File too large")
    return {"filename": file.filename, "size": len(contents)}
Sample Program

This FastAPI app has one endpoint /upload/. It accepts a file upload, checks if the file is a JPEG or PNG, and ensures it is smaller than 2MB. If checks fail, it sends an error. Otherwise, it returns the file name and size.

FastAPI
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import JSONResponse

app = FastAPI()

@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
    allowed_types = ["image/jpeg", "image/png"]
    max_size = 2_000_000  # 2MB

    if file.content_type not in allowed_types:
        raise HTTPException(status_code=400, detail="Only JPEG or PNG files allowed")

    contents = await file.read()
    if len(contents) > max_size:
        raise HTTPException(status_code=400, detail="File too large")

    return JSONResponse(content={"filename": file.filename, "size": len(contents)})
OutputSuccess
Important Notes

Always check file.content_type to verify file type before reading content.

Reading the whole file with await file.read() lets you check size but can use memory for big files.

For very large files, consider streaming or chunk reading to avoid memory issues.

Summary

File validation helps keep uploads safe and within limits.

Check both file type and size before accepting files.

FastAPI's UploadFile makes it easy to handle uploaded files asynchronously.