File validation (size, type) with FastAPI
📖 Scenario: You are building a simple web API that accepts file uploads. To keep your server safe and efficient, you want to check that uploaded files are not too large and are of allowed types.
🎯 Goal: Create a FastAPI app that accepts a file upload and validates the file size and type before accepting it.
📋 What You'll Learn
Create a FastAPI app instance named
appCreate an endpoint
/upload that accepts a file upload using UploadFileAdd a configuration variable
MAX_FILE_SIZE set to 1_000_000 bytes (1 MB)Check the uploaded file's content type is either
image/jpeg or image/pngCheck the uploaded file's size does not exceed
MAX_FILE_SIZEReturn a JSON response with a success message if validations pass
💡 Why This Matters
🌍 Real World
File upload validation is essential for web apps that accept user files to prevent server overload and security risks.
💼 Career
Backend developers often implement file validation to ensure safe and efficient file handling in APIs.
Progress0 / 4 steps