Hint: Use List[UploadFile] = File(...) for multiple files param [OK]
Common Mistakes:
Using UploadFile without List for multiple files
Using List[str] which is incorrect for files
Assigning UploadFile(...) instead of File(...)
3. Given this FastAPI endpoint code, what will be the output if two files named 'a.txt' and 'b.txt' are uploaded?
from fastapi import FastAPI, File, UploadFile
from typing import List
app = FastAPI()
@app.post('/upload')
async def upload(files: List[UploadFile] = File(...)):
return {"filenames": [file.filename for file in files]}
medium
A. {"filenames": ["a.txt", "b.txt"]}
B. {"filenames": ["files", "files"]}
C. {"filenames": []}
D. Runtime error due to wrong type
Solution
Step 1: Understand the endpoint logic
The endpoint returns a dictionary with a list of filenames extracted from the uploaded files.
Step 2: Check the uploaded files names
Two files named 'a.txt' and 'b.txt' are uploaded, so their filenames will be returned in the list.
Final Answer:
{"filenames": ["a.txt", "b.txt"]} -> Option A
Quick Check:
Returned filenames list matches uploaded files [OK]
Hint: Returned filenames list matches uploaded files names [OK]
Common Mistakes:
Expecting file content instead of filenames
Confusing parameter name with file names
Assuming empty list if files uploaded
4. What is wrong with this FastAPI endpoint for multiple file uploads?
from fastapi import FastAPI, File, UploadFile
from typing import List
app = FastAPI()
@app.post('/upload')
async def upload(files: UploadFile = File(...)):
return {"count": len(files)}
medium
A. File(...) should be replaced with UploadFile(...)
B. Missing async keyword in function definition
C. len(files) is invalid because files is a string
D. files should be List[UploadFile] to accept multiple files
Solution
Step 1: Check parameter type for multiple files
The parameter 'files' is typed as UploadFile, which accepts only one file.
Step 2: Correct type for multiple files
To accept multiple files, it must be List[UploadFile].
Final Answer:
files should be List[UploadFile] to accept multiple files -> Option D
Quick Check:
Multiple files need List[UploadFile] type [OK]
Hint: Use List[UploadFile] for multiple files, not UploadFile alone [OK]
Common Mistakes:
Using UploadFile instead of List[UploadFile] for multiple files
Confusing File(...) with UploadFile(...)
Forgetting async keyword (though present here)
5. You want to create a FastAPI endpoint that accepts multiple files and returns a JSON with each file's name and size in bytes. Which code snippet correctly implements this?
hard
A. async def upload(files: List[str] = File(...)):
return [{"name": f, "size": 0} for f in files]