Bird
0
0

Consider this FastAPI endpoint:

medium📝 component behavior Q4 of 15
FastAPI - File Handling
Consider this FastAPI endpoint:
from fastapi import FastAPI, UploadFile, File
app = FastAPI()

@app.post('/upload')
async def upload(file: UploadFile = File(...)):
    content = await file.read()
    return {'name': file.filename, 'length': len(content)}

What will this endpoint return after a file upload?
AA JSON with the uploaded file's name and its size in bytes
BA JSON with the file's content as a string
CAn error because UploadFile cannot be read asynchronously
DA JSON with only the file's name but no size information
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the code

    The endpoint reads the entire file asynchronously using await file.read().
  2. Step 2: Understand the return statement

    It returns a dictionary with the filename and the length of the content in bytes.
  3. Final Answer:

    A JSON with the uploaded file's name and its size in bytes -> Option A
  4. Quick Check:

    UploadFile.read() returns bytes; length gives size [OK]
Quick Trick: UploadFile.read() returns bytes; length is file size [OK]
Common Mistakes:
MISTAKES
  • Assuming file.read() returns a string instead of bytes
  • Thinking UploadFile cannot be read asynchronously

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes