Bird
Raised Fist0
FastAPIframework~20 mins

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

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

Practice

(1/5)
1. What is the main purpose of validating file size and type in a FastAPI upload endpoint?
easy
A. To ensure only allowed file types and sizes are accepted for security and performance
B. To automatically convert files to a specific format
C. To speed up the file upload process by skipping checks
D. To store files directly in the database without validation

Solution

  1. Step 1: Understand file validation purpose

    File validation ensures that only files meeting size and type rules are accepted.
  2. Step 2: Recognize security and performance reasons

    Validating prevents harmful files and avoids server overload from large files.
  3. Final Answer:

    To ensure only allowed file types and sizes are accepted for security and performance -> Option A
  4. Quick Check:

    File validation = security and performance [OK]
Hint: File validation protects server and users from bad files [OK]
Common Mistakes:
  • Thinking validation changes file content
  • Assuming validation speeds upload without checks
  • Ignoring security risks of unvalidated files
2. Which of the following is the correct way to declare a file upload parameter in a FastAPI endpoint to accept files asynchronously?
easy
A. def upload(file: UploadFile = File(...)):
B. def upload(file: str):
C. def upload(file: bytes):
D. def upload(file: int):

Solution

  1. Step 1: Identify FastAPI file upload type

    FastAPI uses UploadFile with File(...) to handle async file uploads.
  2. Step 2: Check parameter types

    Only UploadFile supports async file handling, bytes or str do not.
  3. Final Answer:

    def upload(file: UploadFile = File(...)): -> Option A
  4. Quick Check:

    UploadFile + File(...) = async file upload [OK]
Hint: Use UploadFile with File(...) for async uploads [OK]
Common Mistakes:
  • Using bytes or str instead of UploadFile
  • Missing File(...) dependency
  • Using int type for file parameter
3. Given this FastAPI code snippet, what will happen if a user uploads a 5MB PNG file?
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)}
medium
A. Returns filename and size successfully
B. Raises HTTPException with 'File too large'
C. Raises HTTPException with 'Invalid file type'
D. Raises a syntax error

Solution

  1. Step 1: Check file type condition

    The file is PNG, which is allowed, so no error here.
  2. 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'.
  3. Final Answer:

    Raises HTTPException with 'File too large' -> Option B
  4. Quick Check:

    File size > 2MB = 'File too large' error [OK]
Hint: Check size limit after reading file contents [OK]
Common Mistakes:
  • Confusing file type error with size error
  • Not reading file contents before size check
  • Assuming no error for large files
4. Identify the error in this FastAPI file validation code:
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}
medium
A. The file size check uses wrong comparison operator
B. UploadFile should not be used with File(...)
C. The file type condition always raises error due to incorrect logic
D. Missing await keyword before file.read()

Solution

  1. 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).
  2. Step 2: Understand consequence of condition

    This causes the error to always raise, rejecting all files incorrectly.
  3. Final Answer:

    The file type condition always raises error due to incorrect logic -> Option C
  4. Quick Check:

    Incorrect 'or' with != always true = logic error [OK]
Hint: Use 'and' when checking multiple 'not equals' conditions [OK]
Common Mistakes:
  • Using 'or' instead of 'and' in file type checks
  • Forgetting to await file.read()
  • Misunderstanding UploadFile usage
5. You want to create a FastAPI endpoint that accepts only PDF files smaller than 3MB. Which code snippet correctly implements this validation?
hard
A. async def upload(file: UploadFile = File(...)): contents = await file.read() if file.content_type == 'application/pdf' or len(contents) < 3_000_000: return {'filename': file.filename} raise HTTPException(400, 'Invalid file')
B. async def upload(file: UploadFile = File(...)): if file.content_type == 'application/pdf' or len(await file.read()) < 3_000_000: return {'filename': file.filename} raise HTTPException(400, 'Invalid file')
C. async def upload(file: UploadFile = File(...)): if file.content_type == 'application/pdf' or len(await file.read()) > 3_000_000: raise HTTPException(400, 'Invalid file') return {'filename': file.filename}
D. async def upload(file: UploadFile = File(...)): if file.content_type != 'application/pdf': raise HTTPException(400, 'Invalid type') contents = await file.read() if len(contents) > 3_000_000: raise HTTPException(400, 'Too large') return {'filename': file.filename}

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    Separate type (!=) and size (> 3MB) checks -> Option D
  4. Quick Check:

    != type reject + read then > size reject [OK]
Hint: Check type and size separately with correct logic [OK]
Common Mistakes:
  • Using 'or' instead of 'and' in conditions
  • Reading file multiple times causing empty content
  • Incorrect comparison operators in conditions