Bird
Raised Fist0
FastAPIframework~10 mins

File responses in FastAPI - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the correct class for sending a file response in FastAPI.

FastAPI
from fastapi import FastAPI
from fastapi.responses import [1]

app = FastAPI()
Drag options to blanks, or click blank then click option'
AHTMLResponse
BJSONResponse
CRedirectResponse
DFileResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Importing JSONResponse or HTMLResponse instead of FileResponse.
Forgetting to import any response class.
2fill in blank
medium

Complete the code to return a file named 'example.txt' from the '/download' route.

FastAPI
from fastapi import FastAPI
from fastapi.responses import FileResponse

app = FastAPI()

@app.get('/download')
async def download_file():
    return [1]('example.txt')
Drag options to blanks, or click blank then click option'
AJSONResponse
BHTMLResponse
CFileResponse
DRedirectResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Returning JSONResponse or HTMLResponse instead of FileResponse.
Forgetting to specify the filename.
3fill in blank
hard

Fix the error in the code to correctly send a file with a custom filename 'report.pdf' in the response.

FastAPI
from fastapi import FastAPI
from fastapi.responses import FileResponse

app = FastAPI()

@app.get('/report')
async def get_report():
    return FileResponse('files/report.pdf', [1]='report.pdf')
Drag options to blanks, or click blank then click option'
Afile
Bfilename
Cname
Dfile_name
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'file_name' or 'name' instead of 'filename'.
Passing the filename as a positional argument.
4fill in blank
hard

Fill both blanks to send a file with media type 'application/pdf' and enable HTTP caching.

FastAPI
from fastapi import FastAPI
from fastapi.responses import FileResponse

app = FastAPI()

@app.get('/pdf')
async def get_pdf():
    return FileResponse('docs/sample.pdf', media_type=[1], [2]='max-age=3600')
Drag options to blanks, or click blank then click option'
A'application/pdf'
Bbackground
Ccache_control
Duse_cache
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong media type strings.
Using incorrect parameter names for caching.
5fill in blank
hard

Fill all three blanks to send a file with custom filename, media type, and set background task to delete the file after sending.

FastAPI
from fastapi import FastAPI
from fastapi.responses import FileResponse
from fastapi.background import BackgroundTask
import os

app = FastAPI()

def remove_file(path: str):
    os.remove(path)

@app.get('/tempfile')
async def send_temp_file():
    path = 'temp/data.txt'
    return FileResponse(path, filename=[1], media_type=[2], background=BackgroundTask([3], path))
Drag options to blanks, or click blank then click option'
A'data.txt'
B'text/plain'
Cremove_file(path)
Dremove_file
Attempts:
3 left
💡 Hint
Common Mistakes
Calling remove_file(path) instead of passing remove_file.
Using wrong media type strings.
Not setting the filename parameter.

Practice

(1/5)
1. What is the main purpose of FileResponse in FastAPI?
easy
A. To send files from the server to the client
B. To upload files from the client to the server
C. To delete files on the server
D. To read file contents as text

Solution

  1. Step 1: Understand the role of FileResponse

    FileResponse is designed to send files from the server to the client in FastAPI.
  2. Step 2: Differentiate from other file operations

    Uploading or deleting files are handled differently; FileResponse specifically sends files.
  3. Final Answer:

    To send files from the server to the client -> Option A
  4. Quick Check:

    FileResponse sends files [OK]
Hint: FileResponse is for sending files to users [OK]
Common Mistakes:
  • Confusing FileResponse with file upload handling
  • Thinking FileResponse reads file content as text
  • Assuming FileResponse deletes files
2. Which of the following is the correct way to import FileResponse in FastAPI?
easy
A. from fastapi.responses import file_response
B. from fastapi import FileResponse
C. import FileResponse from fastapi.responses
D. from fastapi.responses import FileResponse

Solution

  1. Step 1: Recall correct import syntax

    FastAPI's FileResponse is imported from fastapi.responses using Python's standard import syntax.
  2. Step 2: Check each option's correctness

    from fastapi.responses import FileResponse uses correct syntax and casing. from fastapi import FileResponse misses the submodule. import FileResponse from fastapi.responses uses wrong syntax. from fastapi.responses import file_response uses wrong casing.
  3. Final Answer:

    from fastapi.responses import FileResponse -> Option D
  4. Quick Check:

    Correct import is from fastapi.responses [OK]
Hint: Import FileResponse from fastapi.responses [OK]
Common Mistakes:
  • Using wrong import syntax like 'import X from Y'
  • Importing directly from fastapi without .responses
  • Wrong casing like file_response instead of FileResponse
3. What will the following FastAPI endpoint return?
from fastapi import FastAPI
from fastapi.responses import FileResponse

app = FastAPI()

@app.get('/download')
async def download_file():
    return FileResponse('example.pdf', media_type='application/pdf', filename='report.pdf')
medium
A. Returns JSON with file path 'example.pdf'
B. Sends the file 'example.pdf' with download name 'report.pdf' and PDF media type
C. Raises an error because filename cannot be set
D. Sends 'report.pdf' file ignoring 'example.pdf'

Solution

  1. Step 1: Analyze FileResponse parameters

    The first argument is the file path to send ('example.pdf'). The media_type sets the content type to PDF. The filename sets the suggested download name.
  2. Step 2: Understand the endpoint behavior

    When called, the endpoint sends the file 'example.pdf' with content type 'application/pdf' and suggests the name 'report.pdf' for download.
  3. Final Answer:

    Sends the file 'example.pdf' with download name 'report.pdf' and PDF media type -> Option B
  4. Quick Check:

    FileResponse sends file with given path and filename [OK]
Hint: FileResponse(path, media_type, filename) sends file with custom name [OK]
Common Mistakes:
  • Thinking filename argument changes the file read
  • Expecting JSON response instead of file
  • Assuming filename cannot be set
4. Identify the error in this FastAPI endpoint that tries to send a file:
from fastapi import FastAPI
from fastapi.responses import FileResponse

app = FastAPI()

@app.get('/file')
async def get_file():
    return FileResponse(filepath='data.txt', media_type='text/plain')
medium
A. FileResponse does not accept a 'filepath' keyword argument
B. The media_type 'text/plain' is invalid
C. FileResponse requires a filename argument
D. The endpoint must be synchronous, not async

Solution

  1. Step 1: Check FileResponse constructor parameters

    FileResponse expects the file path as the first positional argument, not as a 'filepath' keyword argument.
  2. Step 2: Identify the error cause

    Passing 'filepath=' causes a TypeError because FileResponse does not have a 'filepath' parameter.
  3. Final Answer:

    FileResponse does not accept a 'filepath' keyword argument -> Option A
  4. Quick Check:

    FileResponse needs file path as first argument, no 'filepath=' [OK]
Hint: FileResponse takes file path as first argument, no 'filepath=' keyword [OK]
Common Mistakes:
  • Using 'filepath=' keyword instead of positional argument
  • Thinking filename is mandatory
  • Believing async is not allowed for endpoints
5. You want to create a FastAPI endpoint that sends a file only if it exists, otherwise returns a 404 error. Which code snippet correctly implements this behavior?
hard
A. from fastapi import FastAPI from fastapi.responses import FileResponse app = FastAPI() @app.get('/download') async def download(): return FileResponse('file.txt')
B. from fastapi import FastAPI from fastapi.responses import FileResponse app = FastAPI() @app.get('/download') async def download(): try: return FileResponse('file.txt') except FileNotFoundError: return {'error': 'File missing'}
C. from fastapi import FastAPI, HTTPException from fastapi.responses import FileResponse import os app = FastAPI() @app.get('/download') async def download(): if os.path.exists('file.txt'): return FileResponse('file.txt') else: raise HTTPException(status_code=404, detail='File not found')
D. from fastapi import FastAPI from fastapi.responses import FileResponse app = FastAPI() @app.get('/download') async def download(): if 'file.txt' in os.listdir('.'): return FileResponse('file.txt') else: return {'error': 'File not found'}

Solution

  1. Step 1: Check file existence properly

    Using os.path.exists('file.txt') correctly checks if the file exists before sending.
  2. Step 2: Return appropriate response on missing file

    Raising HTTPException with 404 status is the proper way to signal file not found in FastAPI.
  3. Final Answer:

    Code snippet B correctly checks file existence and raises 404 if missing -> Option C
  4. Quick Check:

    Check file with os.path.exists + raise HTTPException [OK]
Hint: Check file with os.path.exists, raise HTTPException 404 if missing [OK]
Common Mistakes:
  • Not checking file existence before sending
  • Returning JSON error instead of raising HTTPException
  • Using try-except without proper exception handling
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard