-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
28 lines (24 loc) · 1.18 KB
/
Copy pathapp.py
File metadata and controls
28 lines (24 loc) · 1.18 KB
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
from fastapi import FastAPI, HTTPException, Response, Query
import requests, random
app = FastAPI(title="Deezer 30s Preview API 🎵", version="1.0")
DEEZER_SEARCH_URL="https://api.deezer.com/search"
@app.get("/")
def home():
return {"message":"🎧 Welcome to Deezer Music Preview API!","usage":"/preview?query={judul_lagu}"}
@app.get("/preview")
def get_preview(query: str = Query(...)):
try:
res=requests.get(DEEZER_SEARCH_URL, params={"q":query})
data=res.json()
if "data" not in data or len(data["data"])==0:
raise HTTPException(status_code=404, detail="Lagu tidak ditemukan di Deezer.")
track=random.choice(data["data"])
title=track["title"]
artist=track["artist"]["name"]
preview_url=track.get("preview")
if not preview_url:
raise HTTPException(status_code=404, detail="Lagu tidak punya preview 30 detik.")
audio_data=requests.get(preview_url).content
return Response(content=audio_data, media_type="audio/mpeg", headers={"X-Track-Title":title,"X-Artist-Name":artist})
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))