Bird
Raised Fist0
FastAPIframework~20 mins

File upload (single file) in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
FastAPI File Upload Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when a single file is uploaded using FastAPI's UploadFile?

Consider this FastAPI endpoint that accepts a single file upload:

from fastapi import FastAPI, File, UploadFile

app = FastAPI()

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

What will be the output if a file named example.txt with 100 bytes is uploaded?

FastAPI
from fastapi import FastAPI, File, UploadFile

app = FastAPI()

@app.post('/upload')
async def upload_file(file: UploadFile = File(...)):
    content = await file.read()
    return {'filename': file.filename, 'size': len(content)}
A{"filename": "example.txt", "size": 100}
B{"filename": "file", "size": 100}
C{"filename": "example.txt", "size": 0}
DTypeError: object of type 'UploadFile' has no len()
Attempts:
2 left
💡 Hint

Remember that file.filename gives the original file name and await file.read() reads the file content bytes.

📝 Syntax
intermediate
2:00remaining
Which option correctly declares a FastAPI endpoint to accept a single file upload?

Choose the correct way to declare a FastAPI POST endpoint that accepts a single file upload using UploadFile and File.

A
@app.post('/upload')
async def upload(file: UploadFile):
    return {'filename': file.filename}
B
@app.post('/upload')
def upload(file: UploadFile = File(...)):
    return {'filename': file.filename}
C
@app.post('/upload')
async def upload(file: bytes = File(...)):
    return {'filename': file.filename}
D
@app.post('/upload')
async def upload(file: UploadFile = File(...)):
    return {'filename': file.filename}
Attempts:
2 left
💡 Hint

Remember that file uploads should be declared with UploadFile and File(...) to mark the parameter as required.

🔧 Debug
advanced
2:00remaining
Why does this FastAPI file upload endpoint raise an error?

Given this FastAPI endpoint:

@app.post('/upload')
async def upload(file: UploadFile = File(...)):
    content = file.read()
    return {'size': len(content)}

What error will occur when uploading a file and why?

FastAPI
@app.post('/upload')
async def upload(file: UploadFile = File(...)):
    content = file.read()
    return {'size': len(content)}
ANo error, returns file size correctly
BTypeError: object of type 'UploadFile' has no attribute 'read'
CRuntimeWarning: coroutine 'UploadFile.read' was never awaited
DValueError: file parameter missing
Attempts:
2 left
💡 Hint

Check if file.read() is awaited properly in async functions.

state_output
advanced
2:00remaining
What is the value of 'file_content' after this FastAPI upload endpoint runs?

Consider this FastAPI endpoint:

@app.post('/upload')
async def upload(file: UploadFile = File(...)):
    file_content = await file.read()
    await file.seek(0)
    second_read = await file.read()
    return {'first_read_size': len(file_content), 'second_read_size': len(second_read)}

What will be the returned JSON if the uploaded file has 50 bytes?

FastAPI
@app.post('/upload')
async def upload(file: UploadFile = File(...)):
    file_content = await file.read()
    await file.seek(0)
    second_read = await file.read()
    return {'first_read_size': len(file_content), 'second_read_size': len(second_read)}
ARuntimeError: seek() not supported
B{"first_read_size": 50, "second_read_size": 50}
C{"first_read_size": 0, "second_read_size": 50}
D{"first_read_size": 50, "second_read_size": 0}
Attempts:
2 left
💡 Hint

Think about what seek(0) does to the file pointer before the second read.

🧠 Conceptual
expert
2:00remaining
Which statement about FastAPI's UploadFile is TRUE?

Choose the correct statement about UploadFile in FastAPI.

A<code>UploadFile</code> provides a file-like async interface and stores the file on disk or in memory depending on size.
B<code>UploadFile</code> stores the entire file content in memory as bytes immediately upon upload.
C<code>UploadFile</code> can only be used synchronously and does not support async methods.
D<code>UploadFile</code> automatically saves the uploaded file permanently to a fixed server directory.
Attempts:
2 left
💡 Hint

Consider how UploadFile manages file data and async support.

Practice

(1/5)
1. In FastAPI, which parameter type is used to accept a single uploaded file in an endpoint?
easy
A. List[UploadFile]
B. str
C. UploadFile
D. int

Solution

  1. Step 1: Understand FastAPI file upload types

    FastAPI uses UploadFile to handle file uploads efficiently.
  2. Step 2: Identify single file upload parameter

    For a single file, the parameter type is UploadFile, not a list or primitive type.
  3. Final Answer:

    <code>UploadFile</code> -> Option C
  4. Quick Check:

    Single file upload uses UploadFile [OK]
Hint: Use UploadFile for single file upload in FastAPI [OK]
Common Mistakes:
  • Using str or int instead of UploadFile
  • Using List[UploadFile] for single file
  • Not importing UploadFile from fastapi
2. Which of the following is the correct way to declare a FastAPI endpoint parameter to accept a single file upload?
easy
A. file: str = File(...)
B. file: bytes = File(...)
C. file: UploadFile
D. file: UploadFile = File(...)

Solution

  1. Step 1: Check parameter declaration for file upload

    FastAPI requires File(...) to mark the parameter as a file upload.
  2. Step 2: Match type with File marker

    The type must be UploadFile combined with File(...) for single file upload.
  3. Final Answer:

    file: UploadFile = File(...) -> Option D
  4. Quick Check:

    UploadFile with File(...) is correct syntax [OK]
Hint: Use UploadFile = File(...) to accept single file [OK]
Common Mistakes:
  • Omitting File(...) marker
  • Using str or bytes instead of UploadFile
  • Not assigning default File(...)
3. What will be the output of this FastAPI endpoint when a file named 'test.txt' with content 'hello' is uploaded?
from fastapi import FastAPI, UploadFile, File
app = FastAPI()

@app.post('/upload')
async def upload(file: UploadFile = File(...)):
    content = await file.read()
    return {'filename': file.filename, 'content_type': file.content_type, 'size': len(content)}
medium
A. {'filename': 'test.txt', 'content_type': 'text/plain', 'size': 5}
B. {'filename': 'test.txt', 'content_type': 'application/octet-stream', 'size': 0}
C. {'filename': '', 'content_type': '', 'size': 5}
D. RuntimeError due to missing await

Solution

  1. Step 1: Read file content asynchronously

    The code uses await file.read() to get the file bytes, so content length is 5 for 'hello'.
  2. Step 2: Return file info correctly

    Filename is 'test.txt', content type is 'text/plain' (default for .txt), size is length of content (5).
  3. Final Answer:

    {'filename': 'test.txt', 'content_type': 'text/plain', 'size': 5} -> Option A
  4. Quick Check:

    File info returned matches uploaded file [OK]
Hint: Await file.read() to get content size correctly [OK]
Common Mistakes:
  • Not awaiting file.read() causing empty content
  • Assuming wrong content_type
  • Returning filename as empty string
4. Identify the error in this FastAPI endpoint code for single file upload:
from fastapi import FastAPI, UploadFile
app = FastAPI()

@app.post('/upload')
def upload(file: UploadFile = File(...)):
    content = file.read()
    return {'filename': file.filename, 'size': len(content)}
medium
A. Missing import of File from fastapi
B. All of the above
C. file.read() should be awaited in async function
D. Endpoint function must be async to await file.read()

Solution

  1. Step 1: Check imports and function signature

    The code misses importing File and the function is not async but calls file.read() which is async.
  2. Step 2: Identify async usage and await

    To read file content, function must be async and use await file.read().
  3. Final Answer:

    All of the above -> Option B
  4. Quick Check:

    Missing import, async, and await cause errors [OK]
Hint: Import File, make function async, await file.read() [OK]
Common Mistakes:
  • Forgetting to import File
  • Using sync function with async file.read()
  • Not awaiting file.read()
5. You want to create a FastAPI endpoint that accepts a single file upload and returns the file's name, content type, and first 10 bytes as a UTF-8 string. Which code snippet correctly implements this?
hard
A. from fastapi import FastAPI, UploadFile, File app = FastAPI() @app.post('/upload') async def upload(file: UploadFile = File(...)): content = await file.read() preview = content[:10].decode('utf-8') return {'filename': file.filename, 'content_type': file.content_type, 'preview': preview}
B. from fastapi import FastAPI, UploadFile app = FastAPI() @app.post('/upload') def upload(file: UploadFile): content = file.read() preview = content[:10].decode('utf-8') return {'filename': file.filename, 'content_type': file.content_type, 'preview': preview}
C. from fastapi import FastAPI, UploadFile, File app = FastAPI() @app.post('/upload') async def upload(file: bytes = File(...)): preview = file[:10].decode('utf-8') return {'filename': 'unknown', 'content_type': 'unknown', 'preview': preview}
D. from fastapi import FastAPI, UploadFile, File app = FastAPI() @app.post('/upload') async def upload(file: UploadFile = File(...)): content = await file.read() preview = content.decode('utf-8')[:10] return {'filename': file.filename, 'content_type': file.content_type, 'preview': preview}

Solution

  1. Step 1: Use async function with UploadFile and File(...)

    Correct signature is async def with parameter file: UploadFile = File(...).
  2. Step 2: Read file content and decode first 10 bytes

    Read content with await file.read(), then slice first 10 bytes and decode to UTF-8 string.
  3. Step 3: Return filename, content_type, and preview string

    Return dictionary with correct file info and preview snippet.
  4. Final Answer:

    Option A code snippet -> Option A
  5. Quick Check:

    Async read, slice, decode first 10 bytes [OK]
Hint: Await read, slice first 10 bytes, decode UTF-8 [OK]
Common Mistakes:
  • Using sync function without await
  • Decoding entire content before slicing
  • Using bytes type instead of UploadFile