0
0
FastAPIframework~5 mins

File responses in FastAPI

Choose your learning style9 modes available
Introduction

File responses let your web app send files like images or documents to users. This helps users download or view files directly from your app.

When you want users to download a report or PDF from your website.
To send images or videos stored on your server to users.
When serving static files like manuals or guides through your API.
To allow users to download generated files like CSV exports.
When you want to stream large files without loading them fully in memory.
Syntax
FastAPI
from fastapi import FastAPI
from fastapi.responses import FileResponse

app = FastAPI()

@app.get("/file")
async def get_file():
    return FileResponse("path/to/your/file.txt")

Use FileResponse to send files from your server to the client.

The file path must be accessible by your app and include the full or relative path.

Examples
Sends a PDF file named report.pdf located in the /files folder.
FastAPI
return FileResponse("/files/report.pdf")
Sends a JPEG image and explicitly sets the media type for the browser to understand the file type.
FastAPI
return FileResponse("images/photo.jpg", media_type="image/jpeg")
Sends a text file but suggests the browser save it as UserManual.txt.
FastAPI
return FileResponse("docs/manual.txt", filename="UserManual.txt")
Sample Program

This example creates a FastAPI app with one route /download-report. When visited, it sends the report.pdf file from the files folder. The browser will download it as AnnualReport.pdf.

FastAPI
from fastapi import FastAPI
from fastapi.responses import FileResponse

app = FastAPI()

@app.get("/download-report")
async def download_report():
    # Sends the report.pdf file to the user
    return FileResponse("./files/report.pdf", media_type="application/pdf", filename="AnnualReport.pdf")
OutputSuccess
Important Notes

Make sure the file path is correct and the file exists to avoid errors.

Use media_type to help browsers handle the file correctly.

Setting filename controls the name users see when downloading.

Summary

File responses let your app send files to users easily.

Use FileResponse with the file path to send files.

Set media type and filename for better user experience.