from fastapi import FastAPI, HTTPException, Query from fastapi.responses import JSONResponse 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) filename = ydl.prepare_filename(info) if not os.path.exists(filename): raise HTTPException(status_code=500, detail="Failed to download the Reel.") # Construct the download link file_name = os.path.basename(filename) download_link = f"https://slimshadow-instagram-r-api.hf.space/files/{file_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")