Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to import the FastAPI class.
FastAPI
from fastapi import [1] app = [1]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Importing UploadFile instead of FastAPI
Using Request instead of FastAPI
✗ Incorrect
The FastAPI class is imported to create the app instance.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using str or bytes instead of UploadFile
Using File as a type instead of UploadFile
✗ Incorrect
UploadFile is used to receive uploaded files in FastAPI endpoints.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using max_length or max_file_size which are invalid
Using max_bytes which is not recognized
✗ Incorrect
The correct parameter to limit file size in File() is max_size.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for wrong content type like 'application/pdf'
Using incorrect error messages
✗ Incorrect
We check if the file's content_type is 'image/png' and raise an error with message 'Invalid file type' if not.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong max_size parameter
Checking for 'image/png' instead of 'image/jpeg'
Incorrect error messages
✗ Incorrect
max_size limits file size to 2MB, content_type is checked for 'image/jpeg', and error message explains the restriction.