How to download a file using fastapi?

Member

by deron , in category: Third Party Scripts , 15 days ago

How to download a file using fastapi?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , 14 days ago

@deron 

To download a file using FastAPI, you can create a route that returns a FileResponse with the file you want to download. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import FileResponse
import shutil

app = FastAPI()

@app.get("/download-file")
async def download_file():
    file_path = "path/to/your/file.txt"
    return FileResponse(path=file_path, filename="file.txt")


In this example, when you make a GET request to "/download-file", it will return the file located at "path/to/your/file.txt" for download with the name "file.txt".


Make sure to change the file path and name to match the file you want to download.