0
0
FastAPIframework~30 mins

File validation (size, type) in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
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 app
Create an endpoint /upload that accepts a file upload using UploadFile
Add 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/png
Check the uploaded file's size does not exceed MAX_FILE_SIZE
Return 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
1
Create FastAPI app and upload endpoint
Import FastAPI and UploadFile from fastapi. Create a FastAPI app instance called app. Define a POST endpoint /upload that accepts a parameter file of type UploadFile.
FastAPI
Need a hint?

Start by importing FastAPI and UploadFile. Then create the app and define the upload function with the correct decorator and parameter.

2
Add max file size configuration
Add a variable called MAX_FILE_SIZE and set it to 1_000_000 (1 million bytes).
FastAPI
Need a hint?

Define a constant variable for the maximum allowed file size in bytes.

3
Check file type and size
Inside the upload function, check if file.content_type is either image/jpeg or image/png. Then read the file content using await file.read() and check if its length is less than or equal to MAX_FILE_SIZE.
FastAPI
Need a hint?

Use an if statement to check the content type. Use await file.read() to get the file bytes and check its length.

4
Return success message
If the file passes both checks, return a dictionary with message key and value "File uploaded successfully".
FastAPI
Need a hint?

Return a success message dictionary if all validations pass.