FastAPI Download Files

  • Last updated Apr 25, 2024

To download files in FastAPI, you can create an endpoint that sends the file as a response.

Here's an example of an endpoint that handles files download in FastAPI:

from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse
import uvicorn
import os

app = FastAPI()

@app.get("/downloads/{file_name}")
def download_file(file_name: str):
    file_path = f"uploads/{file_name}" #Change this path to the directory where your files are stored
    if os.path.exists(file_path):
        return FileResponse(file_path, headers={"Content-Disposition": f"attachment; filename={file_name}"})
    else:
        raise HTTPException(status_code=404, detail="File not found")
    
if __name__ == '__main__':
    uvicorn.run(app, host='127.0.0.1', port=8005)
    print("running...")