from fastapi import FastAPI from fastapi.responses import FileResponse app = FastAPI() @app.get('/download') async def download_file(): return FileResponse('example.txt', media_type='text/plain', filename='downloaded.txt')
The FileResponse sends the file content as a downloadable file. The filename parameter sets the name suggested to the client for saving the file. So the client downloads the content of 'example.txt' but the saved file name is 'downloaded.txt'.
from fastapi import FastAPI from fastapi.responses import FileResponse app = FastAPI() @app.get('/file') async def get_file(): return FileResponse('data.csv', media_type='text/csv', filename='data.csv')
Option D is missing a comma between media_type='text/csv' and filename='data.csv', causing a syntax error.
from fastapi import FastAPI from fastapi.responses import FileResponse app = FastAPI() @app.get('/getfile') async def get_file(): return FileResponse('files/report.pdf')
FileResponse raises FileNotFoundError if the file path is invalid or the file does not exist. Relative paths are allowed if the file exists relative to the working directory.
from fastapi import FastAPI from fastapi.responses import FileResponse app = FastAPI() @app.get('/download') async def download(): return FileResponse('image.png', filename='picture.png')
When the filename parameter is set, FileResponse sets the Content-Disposition header to attachment; filename=... to prompt download with that filename.
Option C correctly uses FileResponse with the file path, sets media_type and filename. FileResponse streams the file efficiently by default. Option C passes a file object which is not supported. Option C uses a non-existent chunk_size parameter. Option C lacks media_type and filename metadata.