【发布时间】:2020-10-21 09:53:32
【问题描述】:
所以我试图通过使用 API 的搜索端点搜索它来从 spotify API 中获取曲目(请参阅documentation)。首先,我授权自己,以便我可以发送 GET 请求。这没有问题,我添加了可重复性的代码。
import requests
CLIENT_ID = "your_id_here"
CLIENT_SECRET = "your_secret_here"
AUTH_URL = "https://accounts.spotify.com/api/token"
auth_response = requests.post(AUTH_URL, {
'grant_type': 'client_credentials',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
})
#Convert response to JSON
auth_response_data = auth_response.json()
#Save the access token
access_token = auth_response_data['access_token']
#Need to pass access token into header to send properly formed GET request to API server
headers = {
'Authorization': 'Bearer {token}'.format(token=access_token)
}
然后,我想使用 API 的搜索端点通过曲目名称 + 艺术家来查找曲目(我稍后需要曲目 ID)。当我使用文档中提供的示例时,一切正常,并使用以下查询返回 artist 对象:
BASE_URL = 'https://api.spotify.com/v1/'
r = requests.get(BASE_URL + 'search?q=tania%20bowra&type=artist', headers=headers)
r = r.json()
这是响应,与文档中的一模一样:
{'artists': {'href': 'https://api.spotify.com/v1/search?query=tania+bowra&type=artist&offset=0&limit=20',
'items': [{'external_urls': {'spotify': 'https://open.spotify.com/artist/08td7MxkoHQkXnWAYD8d6Q'},
'followers': {'href': None, 'total': 235},
'genres': [],
'href': 'https://api.spotify.com/v1/artists/08td7MxkoHQkXnWAYD8d6Q',
'id': '08td7MxkoHQkXnWAYD8d6Q',
'images': [{'height': 640,
'url': 'https://i.scdn.co/image/ab67616d0000b2731ae2bdc1378da1b440e1f610',
'width': 640},
{'height': 300,
'url': 'https://i.scdn.co/image/ab67616d00001e021ae2bdc1378da1b440e1f610',
'width': 300},
{'height': 64,
'url': 'https://i.scdn.co/image/ab67616d000048511ae2bdc1378da1b440e1f610',
'width': 64}],
'name': 'Tania Bowra',
'popularity': 1,
'type': 'artist',
'uri': 'spotify:artist:08td7MxkoHQkXnWAYD8d6Q'}],
'limit': 20,
'next': None,
'offset': 0,
'previous': None,
'total': 1}}
应用相同的逻辑,我尝试使用艺术家和曲目名称从 api 获取 track 对象,如下所示:
BASE_URL = 'https://api.spotify.com/v1/'
r = requests.get(BASE_URL + 'search?q=artist:queen%20track:bohemian%20rapsody&type=track', headers=headers)
r = r.json()
即使我确实收到了有效回复 (statuscode==200),但它似乎是空的:
{'tracks': {'href': 'https://api.spotify.com/v1/search?query=artist%3Aqueen+track%3Abohemian+rapsody&type=track&offset=0&limit=20',
'items': [],
'limit': 20,
'next': None,
'offset': 0,
'previous': None,
'total': 0}}
我的问题是:为什么会这样?
【问题讨论】:
-
未来读者请注意:我经常使用这个端点,有时当一首歌不在 Spotify 上时,它会抛出一个空响应。首先检查您的代码;但如果它不断抛出空响应(在搜索多个市场时),则可能表明该歌曲不在 spotify 上。可以通过使用Spotify客户端并搜索歌曲轻松检查。