【问题标题】:API Spotify show artistsAPI Spotify 表演艺术家
【发布时间】:2020-10-09 12:21:31
【问题描述】:

所以我试图在使用 API 方面做得更好。

我找到了一个练习,我必须在其中搜索艺术家,然后 api 会回复与该名称相关的所有艺术家。

我已经阅读了 spotify developer 上的文档,但我无法修复我的代码。

我总是收到与我的 API 链接不工作相同的错误。

谁能修复我的代码并解释需要做什么。 不要忘记更改 CLIENT ID 和 SECRET。

import urllib.parse
import requests

main_api = "https://accounts.spotify.com/api/token"
CLIENT_ID = "your client id"
CLIENT_SECRET = "your client secret"

auth_response = requests.post(main_api, {
    'grant_type': 'client_credentials',
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET,
})

auth_response_data = auth_response.json()

access_token = auth_response_data['access_token']

headers = {
    'Authorization': 'Bearer {token}'.format(token=access_token)
}

print(access_token)

BASE_URL = 'https://api.spotify.com/v1/'

artist_name = input("Give artist name: ")

r = requests.get(BASE_URL + 'search/' + artist_name + '/artists', headers=headers, params={'include_groups': 'artists', 'limit':50})

print("URL: " + str(r))

d = r.json()

print(BASE_URL + 'search/' + artist_name + "/artists")


print("Name")

for artists in d['items']:
    print(artists['name'], ' --- ', artists['genres'])

【问题讨论】:

    标签: python api spotify


    【解决方案1】:

    您一直在将请求发送到错误的端点(有点)并且带有无效的有效负载。根据docs,这是示例请求的样子:

    curl -X GET "https://api.spotify.com/v1/search?q=tania%20bowra&type=artist" -H "Authorization: Bearer {your access token}"

    下面是你在 Python 中的做法:

    from urllib.parse import urlencode
    import requests
    
    main_api = "https://accounts.spotify.com/api/token"
    auth_response = requests.post(main_api, {
        'grant_type': 'client_credentials',
        'client_id': 'YOUR_CLIENT_ID',
        'client_secret': "YOUR_CLIENT_SECRET",
    })
    
    access_token = auth_response.json()['access_token']
    headers = dict(Authorization=f"Bearer {access_token}")
    
    API_URL = "https://api.spotify.com/v1/"
    query = {
        "q": "justinbieber",
        "type": "artist",
        "limit": "5",
    }
    end_point = "search?"
    api_response = requests.get(f"{API_URL}{end_point}{urlencode(query)}", headers=headers).json()
    
    for artists in api_response["artists"]["items"]:
        print(f"{artists['name']} --- {artists['genres']}")
    
    

    输出:

    Justin Bieber  ---  ['canadian pop', 'dance pop', 'pop', 'post-teen pop']
    Justin Timberlake  ---  ['dance pop', 'pop']
    Justin Drew Bieber  ---  []
    Justin Bieber Tribute Team  ---  ['fake']
    Justin Bieber's Karaoke Band  ---  []
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      • 2018-05-11
      • 2013-04-11
      • 1970-01-01
      相关资源
      最近更新 更多