File download responses let your web app send files to users so they can save or open them on their device.
0
0
File download responses in FastAPI
Introduction
When you want users to download reports or documents from your app.
When providing images or videos for users to save.
When letting users download generated files like PDFs or CSVs.
When sharing software or data files through your API.
When allowing users to export their data from your app.
Syntax
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.
Examples
Sends a PDF file named
monthly_report.pdf for download.FastAPI
return FileResponse("files/report.pdf", media_type="application/pdf", filename="monthly_report.pdf")
Sends a JPEG image named
vacation.jpg for download.FastAPI
return FileResponse("images/photo.jpg", media_type="image/jpeg", filename="vacation.jpg")
Sends a CSV file named
data_export.csv for download.FastAPI
return FileResponse("data/export.csv", media_type="text/csv", filename="data_export.csv")
Sample Program
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.
FastAPI
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")
OutputSuccess
Important Notes
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.
Summary
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.