0
0
FastAPIframework~10 mins

File validation (size, type) in FastAPI - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - File validation (size, type)
Receive file upload request
Check file size <= max allowed?
NoReject: File too large
Yes
Check file type in allowed types?
NoReject: Invalid file type
Yes
Accept file and process/save
Response sent
The server receives a file, checks its size and type, rejects if invalid, otherwise accepts and processes it.
Execution Sample
FastAPI
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) > 1024 * 1024:
        raise HTTPException(status_code=400, detail="File too large")
    return {"filename": file.filename, "size": len(contents)}
This code checks if the uploaded file is PNG or JPEG and smaller than 1MB, else rejects it.
Execution Table
StepActionCheckResultNext Step
1Receive file uploadN/AFile receivedCheck file type
2Check file typefile.content_type in ['image/png', 'image/jpeg']TrueRead file contents
3Read file contentsN/AFile bytes loadedCheck file size
4Check file sizelen(contents) <= 1048576TrueAccept file
5Accept fileN/AReturn filename and sizeEnd
6Receive file uploadN/AFile receivedCheck file type
7Check file typefile.content_type in ['image/png', 'image/jpeg']FalseReject: Invalid file type
8Reject fileN/ARaise HTTPException 400End
9Receive file uploadN/AFile receivedCheck file type
10Check file typefile.content_type in ['image/png', 'image/jpeg']TrueRead file contents
11Read file contentsN/AFile bytes loadedCheck file size
12Check file sizelen(contents) <= 1048576FalseReject: File too large
13Reject fileN/ARaise HTTPException 400End
💡 Execution stops when file is accepted or rejected due to type or size check failure.
Variable Tracker
VariableStartAfter Step 3After Step 4Final
file.content_typeN/Aimage/png or image/jpeg or otherSameSame
contents (bytes)N/ALoaded bytes of fileSameSame
len(contents)N/AFile size in bytesCompared to 1048576Same
Key Moments - 3 Insights
Why do we check file type before reading contents?
Checking file type first (see execution_table step 2) avoids unnecessary reading of large files if type is invalid.
What happens if file size exceeds the limit?
At step 12 in execution_table, if size is too big, the code raises an HTTPException rejecting the file.
Why do we use await when reading file contents?
Because reading file is asynchronous in FastAPI, await ensures we get the full content before size check (step 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what happens at step 7 if the file type is not allowed?
AThe file is accepted and processed
BThe file is rejected with HTTP 400 error
CThe file size is checked next
DThe file contents are read
💡 Hint
Check row with Step 7 in execution_table for action on invalid file type
At which step does the code check if the file size is within the allowed limit?
AStep 2
BStep 11
CStep 12
DStep 4
💡 Hint
Look for size check condition in execution_table rows 4 and 12
If the file size is 2MB, what will be the result according to the execution flow?
AFile rejected due to size too large
BFile rejected due to invalid type
CFile accepted and filename returned
DFile size check skipped
💡 Hint
Refer to execution_table step 12 where size check fails and file is rejected
Concept Snapshot
FastAPI file validation:
- Use UploadFile and File(...) in endpoint
- Check file.content_type for allowed types
- Read file bytes asynchronously with await
- Check size with len(contents) <= max bytes
- Raise HTTPException(400) if invalid
- Return info if valid
Full Transcript
This visual execution shows how FastAPI handles file validation by first receiving the file upload request. It checks the file type against allowed types like image/png or image/jpeg. If the type is invalid, it rejects immediately with an error. If valid, it reads the file contents asynchronously. Then it checks the file size to ensure it is within the allowed limit (1MB in this example). If the file is too large, it rejects with an error. Otherwise, it accepts the file and returns its filename and size. Variables like file.content_type and contents change during execution. Key moments include why type is checked before reading contents, and why await is used for reading. The quiz questions help reinforce understanding of the flow and checks.