| 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)}) |