FastAPI
Create REST API using FastAPI in Python
Building Bigger FastAPI Applications with Multiple Separate Files in Python
Secure FastAPI Application with Oauth2 JWT
How to Upload Files using FastAPI
How to Download Files using FastAPI
How to Zip Mulitiple Files in Python for Download using FastAPI
Create REST API to perform CRUD Operations using FastAPI and MongoDB
Create REST API to perform CRUD Operations using FastAPI and MySQL
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...")