更正 python 语法以在 Spotify 的搜索 API 中按艺术家搜索?

Correct python syntax to search by artist in Spotify's Search API?

使用 Spotify API 搜索艺术家的正确 python 语法是什么?也许我遗漏了一些明显的东西(盯着这个看太久了)

根据文档,header 'authorization' & param 'q' 和 'type' 是必需的。
https://developer.spotify.com/web-api/search-item/

我尝试过的:

artist_name = 'Linkin%20Park'
artist_info = requests.get('https://api.spotify.com/v1/search', header = {'access_token': access_token}, q = artist_name, type = 'artist')

ERROR: TypeError: requests() got an unexpected keyword argument 'q'

然后我想,也许参数必须作为列表发送?:

artist_info = requests.get('https://api.spotify.com/v1/search', header = {'access_token': access_token}, query = list(q = artist_name, type = 'artist'))

但是:

ERROR: TypeError: list() takes at most 1 argument (2 given)

列表就是列表,而不是像PHP中的map和list的混合体。 list() builtin accepts either 0 or 1 positional argument, which should be an iterable. I'd highly recommend you go through the official tutorial.

您可能正在使用 python-requests library. In order to pass query parameters such as the q parameter, you'd pass a dict of parameters as the params argument:

artist_info = requests.get(
    'https://api.spotify.com/v1/search',
    headers={ 'access_token': access_token },
    params={ 'q': artist_name, 'type': 'artist' })

请注意 headers 参数 must be in its plural form, not "header"

最后,您可能对 spotipy 感兴趣,它是一个简单的 Spotify 网络客户端 API。

@Ilja 的回答很好。或者,您可以将参数嵌入 URL 中(因为您只有两个参数而且都相对较短),例如:

artist_info = requests.get('https://api.spotify.com/v1/search?q={}&type={}'.format(artist_name, 'artist'), header = {'access_token': access_token})

@Ilja 和@alfasin 的回答提供了很好的指导,但似乎不再像现在这样有效了。

您必须将 headers 参数更改为 authorization 并添加字符串 Bearer

这对我有用:

artist_info = requests.get('https://api.spotify.com/v1/search',
    headers={ 'authorization': "Bearer " + token}, 
    params={ 'q': artist_name, 'type': 'artist' })