We check files to make sure they are safe and the right kind before saving or using them.
File validation (size, type) in FastAPI
Start learning this pattern below
Jump into concepts and practice - no test required
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.
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)}
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)}
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.
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)})
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.
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.
Practice
Solution
Step 1: Understand file validation purpose
File validation ensures that only files meeting size and type rules are accepted.Step 2: Recognize security and performance reasons
Validating prevents harmful files and avoids server overload from large files.Final Answer:
To ensure only allowed file types and sizes are accepted for security and performance -> Option AQuick Check:
File validation = security and performance [OK]
- Thinking validation changes file content
- Assuming validation speeds upload without checks
- Ignoring security risks of unvalidated files
Solution
Step 1: Identify FastAPI file upload type
FastAPI uses UploadFile with File(...) to handle async file uploads.Step 2: Check parameter types
Only UploadFile supports async file handling, bytes or str do not.Final Answer:
def upload(file: UploadFile = File(...)): -> Option AQuick Check:
UploadFile + File(...) = async file upload [OK]
- Using bytes or str instead of UploadFile
- Missing File(...) dependency
- Using int type for file parameter
from fastapi import FastAPI, File, UploadFile, HTTPException
app = FastAPI()
@app.post('/upload')
async def upload(file: UploadFile = File(...)):
if file.content_type not in ['image/png', 'image/jpeg']:
raise HTTPException(status_code=400, detail='Invalid file type')
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)}Solution
Step 1: Check file type condition
The file is PNG, which is allowed, so no error here.Step 2: Check file size condition
The file size is 5MB (5,000,000 bytes), exceeding 2,000,000 limit, so it raises 'File too large'.Final Answer:
Raises HTTPException with 'File too large' -> Option BQuick Check:
File size > 2MB = 'File too large' error [OK]
- Confusing file type error with size error
- Not reading file contents before size check
- Assuming no error for large files
from fastapi import FastAPI, File, UploadFile, HTTPException
app = FastAPI()
@app.post('/upload')
async def upload(file: UploadFile = File(...)):
if file.content_type != 'image/png' or file.content_type != 'image/jpeg':
raise HTTPException(status_code=400, detail='Invalid file type')
contents = await file.read()
if len(contents) > 1_000_000:
raise HTTPException(status_code=400, detail='File too large')
return {'filename': file.filename}Solution
Step 1: Analyze file type condition logic
The condition uses 'or' with != checks, so it is always true (a file can't be both types).Step 2: Understand consequence of condition
This causes the error to always raise, rejecting all files incorrectly.Final Answer:
The file type condition always raises error due to incorrect logic -> Option CQuick Check:
Incorrect 'or' with != always true = logic error [OK]
- Using 'or' instead of 'and' in file type checks
- Forgetting to await file.read()
- Misunderstanding UploadFile usage
Solution
Step 1: Check file type validation
Correct snippet uses != 'application/pdf' to reject invalid types before reading contents. Distractors misuse operators like 'or' instead of 'and' or check type after reading.Step 2: Check file size validation
After type approval, read contents once and raise if len > 3_000_000. Combined conditions fail due to incorrect logic.Final Answer:
Separate type (!=) and size (> 3MB) checks -> Option DQuick Check:
!= type reject + read then > size reject [OK]
- Using 'or' instead of 'and' in conditions
- Reading file multiple times causing empty content
- Incorrect comparison operators in conditions
