File download responses let your web app send files to users so they can save or open them on their device.
File download responses in FastAPI
from fastapi import FastAPI from fastapi.responses import FileResponse app = FastAPI() @app.get("/download") async def download_file(): return FileResponse("path/to/file.txt", media_type="text/plain", filename="file.txt")
FileResponse sends a file from your server to the user.
The filename parameter sets the name the user sees when saving.
monthly_report.pdf for download.return FileResponse("files/report.pdf", media_type="application/pdf", filename="monthly_report.pdf")
vacation.jpg for download.return FileResponse("images/photo.jpg", media_type="image/jpeg", filename="vacation.jpg")
data_export.csv for download.return FileResponse("data/export.csv", media_type="text/csv", filename="data_export.csv")
This FastAPI app has one route /download-text. When you visit it, the server sends the file example.txt for download with the same name.
from fastapi import FastAPI from fastapi.responses import FileResponse app = FastAPI() @app.get("/download-text") async def download_text_file(): # This will send the file 'example.txt' located in the current folder return FileResponse("example.txt", media_type="text/plain", filename="example.txt")
Make sure the file path is correct and the file exists on the server.
Use the correct media_type so browsers handle the file properly.
FileResponse streams the file efficiently without loading it all into memory.
File download responses let users save files from your FastAPI app.
Use FileResponse with the file path, media type, and filename.
Always check file paths and use correct media types for best results.
Practice
FileResponse in FastAPI?Solution
Step 1: Understand the role of FileResponse
FileResponseis designed to send files from the server to the client, enabling downloads.Step 2: Differentiate from other file operations
Uploading, deleting, or reading files are different operations and not handled byFileResponse.Final Answer:
To send a file to the client for download -> Option DQuick Check:
FileResponse sends files to clients [OK]
- Confusing file download with upload
- Thinking FileResponse reads file content internally
- Assuming FileResponse deletes files
FileResponse in a FastAPI app?Solution
Step 1: Recall correct import syntax
FastAPI'sFileResponseis located in thefastapi.responsesmodule and imported using Python's standard import syntax.Step 2: Check each option
from fastapi.responses import FileResponse uses correct syntax and casing. from fastapi import FileResponse misses the responses submodule. import FileResponse from fastapi.responses uses wrong import order. from fastapi.responses import file_response uses incorrect casing.Final Answer:
from fastapi.responses import FileResponse -> Option AQuick Check:
Correct import = from fastapi.responses import FileResponse [OK]
- Omitting the 'responses' submodule
- Using wrong import syntax order
- Incorrect capitalization of FileResponse
/download?
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get('/download')
async def download_file():
return FileResponse('files/report.pdf', media_type='application/pdf', filename='report.pdf')Solution
Step 1: Analyze FileResponse parameters
The path 'files/report.pdf' is given, media type is set to 'application/pdf', and filename is 'report.pdf'. This means the file will be sent as a PDF download named 'report.pdf'.Step 2: Understand client behavior
The client will receive the file content with correct media type and suggested filename, triggering a download.Final Answer:
The client downloads the file named 'report.pdf' with PDF content -> Option CQuick Check:
FileResponse sends file with given name and media type [OK]
- Assuming JSON response instead of file
- Thinking filename is the full path sent to client
- Ignoring media_type affects download behavior
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get('/getfile')
def get_file():
return FileResponse(path='myfile.txt', media_type='text/plain', filename=myfile.txt)Solution
Step 1: Check filename argument syntax
The filename argument is written asfilename=myfile.txtwithout quotes, so Python treats it as a variable, causing a NameError.Step 2: Verify other parts
The endpoint is synchronous which is allowed. Path can be a file path. FileResponse is imported correctly. So only filename syntax is wrong.Final Answer:
Filename argument is not a string (missing quotes) -> Option BQuick Check:
Filename must be a string literal [OK]
- Forgetting quotes around filename string
- Assuming async needed for FileResponse
- Confusing file path with URL
data.csv stored in static/files/. The file path may not exist sometimes. Which is the best way to handle this safely?Solution
Step 1: Understand file existence risk
Since the file may not exist, directly returningFileResponserisks server errors or confusing client errors.Step 2: Implement error handling
Using a try-except block to catchFileNotFoundErrorand returning a 404 response is best practice for user-friendly error handling.Final Answer:
Use FileResponse with a try-except block to catch file not found errors and return 404 -> Option AQuick Check:
Check file existence and handle errors gracefully [OK]
- Not handling missing files causing server errors
- Using StreamingResponse without reason
- Sending raw file content as string
Ready to prove it?
Pass the test and this pattern moves unknown
