0
0
FastapiHow-ToBeginner · 3 min read

How to Return File Response in FastAPI: Simple Guide

In FastAPI, you can return a file response using FileResponse from fastapi.responses. This sends the file directly to the client with proper headers for download or display.
📐

Syntax

The FileResponse class is used to send files in FastAPI. You provide the file path as a string to the constructor. Optionally, you can set the media_type to specify the file's MIME type and filename to suggest a download name.

  • path: The file path on the server.
  • media_type: The MIME type like application/pdf or image/png.
  • filename: The name shown to the user when downloading.
python
from fastapi.responses import FileResponse

FileResponse(path: str, media_type: str = None, filename: str = None)
💻

Example

This example shows a FastAPI app that returns a PDF file when you visit /download. The file is sent with the correct content type and a suggested filename for download.

python
from fastapi import FastAPI
from fastapi.responses import FileResponse

app = FastAPI()

@app.get("/download")
async def download_file():
    file_path = "./sample.pdf"  # Make sure this file exists in your project folder
    return FileResponse(path=file_path, media_type="application/pdf", filename="example.pdf")
Output
When you visit http://localhost:8000/download, the browser will prompt to download 'example.pdf' or display it if supported.
⚠️

Common Pitfalls

Common mistakes when returning files in FastAPI include:

  • Using a wrong or non-existent file path causes a 404 error.
  • Not setting media_type can lead to incorrect file handling by browsers.
  • Forgetting to set filename if you want the file to download with a specific name.
  • Trying to return large files without streaming can cause performance issues.
python
from fastapi import FastAPI
from fastapi.responses import FileResponse
import os

app = FastAPI()

# Wrong way: file path does not exist
@app.get("/bad-download")
async def bad_download():
    return FileResponse(path="./missing.pdf")  # This will cause 404 error

# Right way: check file exists and set media_type
@app.get("/good-download")
async def good_download():
    file_path = "./sample.pdf"
    if not os.path.exists(file_path):
        return {"error": "File not found"}
    return FileResponse(path=file_path, media_type="application/pdf", filename="example.pdf")
📊

Quick Reference

ParameterDescriptionExample
pathFile path on the server"./files/report.pdf"
media_typeMIME type of the file"application/pdf"
filenameSuggested download name"report.pdf"

Key Takeaways

Use FileResponse with the file path to return files in FastAPI.
Set media_type to help browsers handle the file correctly.
Use filename to suggest a download name to users.
Always verify the file exists to avoid errors.
For large files, consider streaming to improve performance.