首页 文章

如何使用2个spotify endpoints ,当一个补充另一个在Python?

提问于
浏览
0

我'm learning to consume API with Python and Flask, I'目前正在使用Spotify API,我希望从这个 endpoints 的艺术家那里得到Top Tracks: https://api.spotify.com/v1/artists/ / Top-tracks ,你可以看到,我需要艺术家的id来获得他们的顶级曲目,因为我使用了SEARCH endpoints https://api.spotify.com/v1/search?q=name&type=artist ,这给了我一个JSON与艺术家的数据,从那里我得到了ID .

我的问题是,现在,我如何使用Top-Tracks endpoints ,以及我从搜索 endpoints 获得的ID?我创建了一个名为“ide”的变量来存储艺术家的id并能够在 endpoints 的URL中连接它,但是现在我不知道我的代码在Top-Tracks URL中的位置,或者我是否需要创建另一个函数,如何使用存储的id调用我的变量 .

这是我的代码:

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]

这是我尝试获得顶级曲目的方式,但它不起作用 .

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 回答

  • 0

    看起来它可能有助于learn a bit more about python scoping . 在 get_tracklist[0] 未定义的原因是它只能在您定义它的 get_id 中访问 . get_track 中的一个小变化可以让您访问 get_track 中的id:

    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
    

    希望有所帮助!

相关问题