0
0
FastAPIframework~10 mins

File validation (size, type) in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the FastAPI class.

FastAPI
from fastapi import [1]
app = [1]()
Drag options to blanks, or click blank then click option'
AFastAPI
BFile
CRequest
DUploadFile
Attempts:
3 left
💡 Hint
Common Mistakes
Importing UploadFile instead of FastAPI
Using Request instead of FastAPI
2fill in blank
medium

Complete the code to accept a file upload in the endpoint.

FastAPI
@app.post('/upload')
async def upload_file(file: [1]):
    return {'filename': file.filename}
Drag options to blanks, or click blank then click option'
Astr
BUploadFile
CFile
Dbytes
Attempts:
3 left
💡 Hint
Common Mistakes
Using str or bytes instead of UploadFile
Using File as a type instead of UploadFile
3fill in blank
hard

Fix the error in the code to limit file size to 1MB.

FastAPI
from fastapi import File, UploadFile

@app.post('/upload')
async def upload_file(file: UploadFile = File(..., [1]=1048576)):
    return {'filename': file.filename}
Drag options to blanks, or click blank then click option'
Amax_file_size
Bmax_length
Cmax_size
Dmax_bytes
Attempts:
3 left
💡 Hint
Common Mistakes
Using max_length or max_file_size which are invalid
Using max_bytes which is not recognized
4fill in blank
hard

Fill both blanks to check the uploaded file's content type and reject if not an image.

FastAPI
from fastapi import HTTPException

@app.post('/upload')
async def upload_file(file: UploadFile):
    if file.content_type != [1]:
        raise HTTPException(status_code=400, detail=[2])
    return {'filename': file.filename}
Drag options to blanks, or click blank then click option'
A'image/png'
B'Invalid file type'
C'application/pdf'
D'File type not allowed'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for wrong content type like 'application/pdf'
Using incorrect error messages
5fill in blank
hard

Fill all three blanks to create a file validation that accepts only JPEG images under 2MB.

FastAPI
from fastapi import File, UploadFile, HTTPException

@app.post('/upload')
async def upload_file(file: UploadFile = File(..., [1]=2097152)):
    if file.content_type != [2]:
        raise HTTPException(status_code=400, detail=[3])
    return {'filename': file.filename}
Drag options to blanks, or click blank then click option'
Amax_size
B'image/jpeg'
C'Only JPEG images under 2MB are allowed'
D'image/png'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong max_size parameter
Checking for 'image/png' instead of 'image/jpeg'
Incorrect error messages