MalikSahib1's picture
Upload 3 files
2297f47 verified
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware # Import the CORS middleware
from yt_dlp import YoutubeDL
import json
app = FastAPI()
# --- CORS Configuration ---
# This is the part you need to add.
# It allows your API to be called from any website.
# List of origins that are allowed to make requests to your API.
# Using ["*"] allows all origins, which is simple for a public API.
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"], # Allows all methods (GET, POST, etc.)
allow_headers=["*"], # Allows all headers
)
# --- End of CORS Configuration ---
@app.get("/")
async def root():
return {"message": "Welcome to the All-In-One Downloader API!"}
@app.get("/download")
async def download_media(url: str):
if not url:
raise HTTPException(status_code=400, detail="URL parameter is required.")
# These options are fine. No changes needed here.
ydl_opts = {
'noplaylist': True,
'quiet': True,
'dump_single_json': True,
'format': 'best' # You can add this to prefer the best quality format
}
try:
with YoutubeDL(ydl_opts) as ydl:
# The 'download=False' is correct. It just extracts info.
info_dict = ydl.extract_info(url, download=False)
# Returning the JSON response is also correct.
return JSONResponse(content=info_dict)
# Your error handling is good. No changes needed here.
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))