Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download file using fastapi

I am looking through this, and I see the functions for uploading in an API? https://fastapi.tiangolo.com/tutorial/request-files/ There is no option to dl .. Am I missing something? I was hoping to create an api for a file download site. Is there a different api I should be using?

from typing import List
from fastapi import FastAPI, Query

app = FastAPI()
PATH "some/path"

@app.get("/shows/")
    def get_items(q: List[str] = Query(None)):
        '''
        Pass path to function.
        Returns folders and files.
        '''

        results = {}

        query_items = {"q": q}
        entry = PATH + "/".join(query_items["q"]) + "/"

        dirs = os.listdir(entry)
        results["folders"] = [val for val in dirs if os.path.isdir(entry+val)]
        results["files"] = [val for val in dirs if os.path.isfile(entry+val)]
        results["path_vars"] = query_items["q"]

        return results

Here is the sample bit of code for python to fetch files and dirs for a path, you can return the path as a list with a new entry in a loop to go deeper into a file tree. Passing a file name should trigger a download function, but I cant seem to get a download func going.

like image 820
ScipioAfricanus Avatar asked Mar 17 '20 05:03

ScipioAfricanus


People also ask

How can I read FastAPI files?

Read the file contents—using contents = file. file. read() , as shown in this answer (or for async reading/writing see here)—and then upload these bytes to your server, instead of a file object (if that is supported by the server).

How do I download a file from API?

In this article, I will use a demo Web API application in ASP.NET Core to show you how to transmit files through an API endpoint. In the final HTML page, end users can left-click a hyperlink to download the file or right-click the link to choose “ Save Link As ” in the context menu and save the file.

How do I return files on FastAPI?

To return a response with HTML directly from FastAPI, use HTMLResponse . Import HTMLResponse . Pass HTMLResponse as the parameter response_class of your path operation decorator.


1 Answers

This worked For me

from starlette.responses import FileResponse

return FileResponse(file_location, media_type='application/octet-stream',filename=file_name)

This will download the file with filename

like image 196
Avinash Ravi Avatar answered Sep 18 '22 08:09

Avinash Ravi