0
0
FastAPIframework~10 mins

File upload (single file) 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 correct FastAPI class.

FastAPI
from fastapi import [1]
app = [1]()
Drag options to blanks, or click blank then click option'
AUploadFile
BRequest
CFile
DFastAPI
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request instead of FastAPI.
Using UploadFile or File to create the app.
2fill in blank
medium

Complete the code to define a POST endpoint that accepts a file upload.

FastAPI
@app.post("/upload")
async def upload_file(file: [1]):
    return {"filename": file.filename}
Drag options to blanks, or click blank then click option'
AUploadFile
BRequest
CFile
Dstr
Attempts:
3 left
💡 Hint
Common Mistakes
Using str instead of UploadFile for the file parameter.
Using File directly as the parameter type.
3fill in blank
hard

Fix the error in the code to correctly declare the file parameter with File dependency.

FastAPI
from fastapi import UploadFile, File

@app.post("/upload")
async def upload_file(file: UploadFile = [1]):
    return {"filename": file.filename}
Drag options to blanks, or click blank then click option'
AUploadFile()
BFile()
CFile
DUploadFile
Attempts:
3 left
💡 Hint
Common Mistakes
Using File without parentheses.
Using UploadFile() instead of File().
4fill in blank
hard

Fill both blanks to read the uploaded file content as bytes and return its size.

FastAPI
@app.post("/upload")
async def upload_file(file: UploadFile = File()):
    content = await file.[1]()
    return {"size": len(content) [2] 0}
Drag options to blanks, or click blank then click option'
Aread
B+
C-
D*
Attempts:
3 left
💡 Hint
Common Mistakes
Using read without parentheses.
Using subtraction or multiplication instead of addition.
5fill in blank
hard

Fill all three blanks to save the uploaded file content to disk with the original filename.

FastAPI
import shutil

@app.post("/upload")
async def upload_file(file: UploadFile = File()):
    with open([1], "wb") as buffer:
        shutil.[2](file.[3], buffer)
    return {"filename": file.filename}
Drag options to blanks, or click blank then click option'
Afile.filename
Bcopyfileobj
Cfile
Dwrite
Attempts:
3 left
💡 Hint
Common Mistakes
Using write instead of copyfileobj.
Using file.read() instead of file.file.
Using a string literal instead of file.filename.