File size: 1,185 Bytes
9529fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, Query
from fastapi.responses import JSONResponse
import subprocess
import json

app = FastAPI()

@app.get("/")
def root():
    return {"message": "Welcome to yt-dlp API (FastAPI)"}

@app.get("/download")
def download_info(url: str = Query(..., description="Video URL")):
    try:
        result = subprocess.run(
            ["yt-dlp", "-J", url],
            capture_output=True, text=True, timeout=20
        )
        if result.returncode != 0:
            return JSONResponse(status_code=500, content={"error": result.stderr})

        data = json.loads(result.stdout)
        return {
            "title": data.get("title"),
            "uploader": data.get("uploader"),
            "duration": data.get("duration"),
            "formats": [
                {
                    "format_id": f["format_id"],
                    "ext": f["ext"],
                    "resolution": f.get("resolution") or f"{f.get('height')}p",
                    "url": f["url"]
                }
                for f in data.get("formats", [])
            ]
        }
    except Exception as e:
        return JSONResponse(status_code=500, content={"error": str(e)})