0
votes

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
1
Please make sure you reproduce your indentation accurately when posting Python code. Otherwise you are introducing new problems into the code you are showing to people.khelwood
@khelwood Sorry and thanks for the remark.nellydesu
what is the error code (status code) of the response? that's a good first clue. have a look at python's requests to get it.FuzzyAmi
@FuzzyAmi NameError: global name 'list' is not definednellydesu

1 Answers

0
votes

Looks like it might help to learn a bit more about python scoping. The reason that list[0] is undefined inside get_track is that it's only accessible in get_id where you've defined it. A small change in get_track would give you access to the id inside get_track:

def get_track(artist):
    # get the ID here so that you have access to it
    ide = get_id(artist)
    can = requests.get("https://api.spotify.com/v1/artists/"+ ide + "/top-tracks?country=ES", headers=headers)
    return can

Hope that helps!