0
0
FastAPIframework~20 mins

File validation (size, type) in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
File Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when uploading a file larger than 1MB?
Consider this FastAPI endpoint that accepts a file upload and checks its size to be under 1MB. What will be the response if a user uploads a file of 2MB?
FastAPI
from fastapi import FastAPI, File, UploadFile, HTTPException

app = FastAPI()

@app.post('/upload')
async def upload_file(file: UploadFile = File(...)):
    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)}
AThe server returns a 400 error with detail 'File too large'.
BThe server crashes with a runtime error due to memory overflow.
CThe server accepts the file and returns its filename and size.
DThe server ignores the file and returns an empty response.
Attempts:
2 left
💡 Hint
Look at the condition that checks the file size after reading its contents.
📝 Syntax
intermediate
2:00remaining
Which option correctly validates file type as PNG?
You want to accept only PNG files in a FastAPI upload endpoint by checking the file's content type. Which code snippet correctly raises an error if the file is not a PNG?
FastAPI
from fastapi import FastAPI, File, UploadFile, HTTPException

app = FastAPI()

@app.post('/upload')
async def upload_file(file: UploadFile = File(...)):
    if ???:
        raise HTTPException(status_code=400, detail='Only PNG files allowed')
    return {'filename': file.filename}
Aif file.content_type != 'image/png':
Bif file.filename.endswith('.png'):
Cif file.content_type == 'image/png':
Dif file.content_type != 'application/png':
Attempts:
2 left
💡 Hint
Check the MIME type for PNG images.
🔧 Debug
advanced
2:00remaining
Why does this file size validation fail to limit uploads?
This FastAPI code tries to reject files larger than 1MB but still accepts bigger files. What is the cause?
FastAPI
from fastapi import FastAPI, File, UploadFile, HTTPException

app = FastAPI()

@app.post('/upload')
async def upload_file(file: UploadFile = File(...)):
    if file.spool_max_size < 1024 * 1024:
        raise HTTPException(status_code=400, detail='File too large')
    return {'filename': file.filename}
AThe code should use file.size instead of file.spool_max_size.
Bfile.spool_max_size gives the file size in kilobytes, so the check is wrong.
CThe file size must be checked after reading the file contents, not before.
Dfile.spool_max_size is a configuration attribute, not the actual file size.
Attempts:
2 left
💡 Hint
Look up what spool_max_size means in UploadFile.
state_output
advanced
2:00remaining
What is the output after uploading a valid JPEG file?
Given this FastAPI endpoint that accepts only PNG files and returns the filename and size, what is the output if a user uploads a JPEG file named 'photo.jpg' of 500KB?
FastAPI
from fastapi import FastAPI, File, UploadFile, HTTPException

app = FastAPI()

@app.post('/upload')
async def upload_file(file: UploadFile = File(...)):
    if file.content_type != 'image/png':
        raise HTTPException(status_code=400, detail='Only PNG files allowed')
    contents = await file.read()
    return {'filename': file.filename, 'size': len(contents)}
AReturns an empty JSON object {}.
BHTTP 400 error with detail 'Only PNG files allowed' is returned.
CReturns {'filename': 'photo.jpg', 'size': 0} because file.read() is not awaited.
DReturns {'filename': 'photo.jpg', 'size': 512000}.
Attempts:
2 left
💡 Hint
Check the content_type condition and what happens if it fails.
🧠 Conceptual
expert
3:00remaining
Why is reading the entire file to check size not ideal in FastAPI?
In FastAPI, to validate file size, some code reads the entire file content with await file.read() and then checks length. Why might this approach be problematic for large files?
AFile size can be checked from file.filename attribute without reading contents.
BFastAPI automatically limits file size, so manual size checks are redundant.
CReading the entire file into memory can cause high memory use and slow response for large files.
DReading file contents twice is required to validate size and type separately.
Attempts:
2 left
💡 Hint
Think about server resources and user experience with big uploads.