简体   繁体   中英

Can I transform a function result into a variable for another function in python/FLASK?

I'm learning Python 2.7 and FLASK. I have an exercise consuming the Spotify API, so with a function I get the ID of an artist.

Can I use the result of that function (the id) and store it as a variable so I can use it inside another API endpoint? Or how can I use that result?

Here's my code:

@app.route("/api/artist/<artist>")
def api_artist(artist):
    params = get_id(artist)
    return jsonify(params)

def get_id(artist):

    headers = {
        "client_id": "XxXXxxXXX",
        "cliente_secret": "XXXxxxxXXX"
    }

    response = requests.get("https://api.spotify.com/v1/search?q=" + artist +"&type=artist", headers=headers)


    if response.status_code == 200:
        print(response.text)
        lista=[]
        response_dict = response.json()
        results = response_dict["artists"]
        items = results ["items"]
        for value in items:
            lista.append(value["id"])




    params = {
        "id": lista[0]
    }

    return params

This is the Spotify endpoint I trying to use: https://api.spotify.com/v1/artists/{id}/top-tracks

REST API should be "stateless" and hence not a good idea as pointed out by @ cricket_007

So here's what you do: Make 2 REST API Calls and handle the personalization of the user artist preference on the client side

1.) Search the artist and get the ID and return it to the user(client) application

2.) Make a second REST API Call with the acquired id and fetch the top tracks

Hope this helps. Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM