from fastapi import FastAPI, HTTPException, Query from fastapi.responses import 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. Args: reel_url (str): The URL of the Instagram Reel. Returns: FileResponse: The path to the downloaded file. """ 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.") return FileResponse( path=filename, filename=os.path.basename(filename), media_type="video/mp4" ) except Exception as e: raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")