Currently I'm struggling a bit with FastAPI and file serving.
In my project I have the following workflow. Client sends a payload containing the necessary payload to download a file from a third party provider.
I need to send a payload to the backend, it's necessary and since a resource is created (file downloaded), I assumed that POST would be the Method for this endpoint, but let me show you an example.
from fastapi import FastAPI, Form
from fastapi.responses import FileResponse
import os
app = FastAPI()
@app.post("/download_file")
async def download():
url = 'https://file-examples-com.github.io/uploads/2017/10/file-sample_150kB.pdf'
os.system('wget %s'%url)
return FileResponse("file-sample_150kB.pdf")
@app.get("/get_file")
async def get_file():
return FileResponse("/home/josec/stackoverflow_q/file-sample_150kB.pdf")
If I go to http://localhost:8000/get_file, I get the file displayed on the web page! However that's not what I'm looking for! I want the file to be downloaded on the client side, either be via a browser or via cli!
The following script does not download any file, except when you paste it in the browser where you can look at it.
import requests
url = "http://localhost:8000/get_file"
response = requests.request("GET", url)
print(response.json())
This one is not working as well!
import requests
url = "http://localhost:8000/download_file"
response = requests.request("POST", url)
print(response.json())
My questions are:
Should I just use GET? If yes how would I pass parameters, on the url? some strings that I'm sending with the post request can be very long, don't know if that could be an issue.
How can I return a file to the user? Download it immediatly to the user in a return statement of the function endpoint!
Can I do it with POST?
If you guys need anything else from me please do tell :-)
Best,
Jose