File size: 1,648 Bytes
33509a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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)}")