Complete the code to import the FastAPI class.
from fastapi import [1] app = [1]()
The FastAPI class is imported to create the app instance.
Complete the code to accept a file upload in the endpoint.
@app.post('/upload') async def upload_file(file: [1]): return {'filename': file.filename}
UploadFile is used to receive uploaded files in FastAPI endpoints.
Fix the error in the code to limit file size to 1MB.
from fastapi import File, UploadFile @app.post('/upload') async def upload_file(file: UploadFile = File(..., [1]=1048576)): return {'filename': file.filename}
The correct parameter to limit file size in File() is max_size.
Fill both blanks to check the uploaded file's content type and reject if not an image.
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}
We check if the file's content_type is 'image/png' and raise an error with message 'Invalid file type' if not.
Fill all three blanks to create a file validation that accepts only JPEG images under 2MB.
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}
max_size limits file size to 2MB, content_type is checked for 'image/jpeg', and error message explains the restriction.
