I'm learning to consume API with Python and Flask, I'm currently using the Spotify API, and I want to get Top Tracks from an artist with this endpoint: https://api.spotify.com/v1/artists/{id } / Top-tracks, as you can see, I need the artist's id to get their top-tracks, for that I used the SEARCH endpoint https://api.spotify.com/v1/search?q=name&type=artist, this give me a JSON with the data of the artist and from there I got the id.
My question is, now, how can I use the Top-Tracks endpoint, with the id I got from the Search endpoint? I create a variable called "ide" to store the artist's id and be able to concatenate it in the URL of the endpoint, but now I do not know where in my code goes the Top-Tracks URL, or if I need to make another function, how to call to my variable with the stored id.
Here's my code:
from flask import Flask, request, render_template, jsonify
import requests
app = Flask(__name__)
@app.route("/api/artist/<artist>")
def api_artist(artist):
params = get_id(artist)
return jsonify(params)
@app.route("/api/track/<artist>")
def api_track(artist):
params = get_track(artist)
return jsonify(params)
def get_id(artist):
headers = {
"client_id": "xXxXx",
"client_secret": "XxXxX"
}
response = requests.get("https://api.spotify.com/v1/search?q=" + artist +"&type=artist", headers=headers)
if response.status_code == 200:
print(response.text)
list=[]
response_dict = response.json()
results = response_dict["artists"]
items = results ["items"]
for value in items:
list.append(value["id"])
params = {
"id": list[0]
}
return list[0]
And here's the way I try to get the top-tracks, but it does not work.
def get_track(artist):
ide = list[0]
can = requests.get("https://api.spotify.com/v1/artists/"+ ide + "/top-tracks?country=ES", headers=headers)
return can