from fastapi import FastAPI, HTTPException, Query from fastapi.responses import JSONResponse, FileResponse import os from yt_dlp import YoutubeDL # Define the FastAPI app app = FastAPI() # Directory to save downloaded videos DOWNLOAD_DIR = "downloads" os.makedirs(DOWNLOAD_DIR, exist_ok=True) @app.get("/") def read_root(): return {"message": "Welcome to the Instagram Reel Downloader API"} @app.get("/download/") def download_instagram_reel( reel_url: str = Query(..., description="The URL of the Instagram Reel to download"), ): """ Download an Instagram Reel using yt-dlp and provide a download link. Args: reel_url (str): The URL of the Instagram Reel. Returns: JSONResponse: A JSON object containing the download link. """ if not reel_url: raise HTTPException(status_code=400, detail="The 'reel_url' parameter is required.") # Define yt-dlp options ydl_opts = { "outtmpl": os.path.join(DOWNLOAD_DIR, "%(title)s.%(ext)s"), "quiet": True, # Suppress yt-dlp's output "merge_output_format": "mp4", } try: with YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(reel_url, download=True) original_filename = ydl.prepare_filename(info) # Ensure the file was created if not os.path.exists(original_filename): raise HTTPException(status_code=500, detail="Failed to download the Reel.") # Replace spaces with underscores in the filename base_name = os.path.basename(original_filename) sanitized_name = base_name.replace(" ", "_") sanitized_path = os.path.join(DOWNLOAD_DIR, sanitized_name) # Rename the file os.rename(original_filename, sanitized_path) # Construct the download link download_link = f"https://slimshadow-instagram-r-api.hf.space/files/{sanitized_name}" return JSONResponse(content={"download_link": download_link}) except Exception as e: raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}") @app.get("/files/{file_name}") def serve_file(file_name: str): """ Serve the downloaded file for users to download. """ file_path = os.path.join(DOWNLOAD_DIR, file_name) if not os.path.exists(file_path): raise HTTPException(status_code=404, detail="File not found.") return FileResponse(path=file_path, filename=file_name, media_type="video/mp4")