如何在 Python 中格式化我对 Spotify Web API 的 GET 请求?
How do I format my GET request to the Spotify Web API in Python?
我是 API 的新手。我正在尝试创建一个脚本,该脚本将从 Spotify 输出 public 播放列表的曲目。我在早期遇到了障碍:我不确定如何准确格式化我的 GET 请求 以检索相关播放列表的曲目以及我将 OAuth 访问令牌放在哪里。我当前的尝试 returns 一个 401 状态代码。
到目前为止我做了什么:
- 我已经在 Spotify 开发者网站仪表板上创建了一个应用程序。
- 我已将仪表板中的 client_id 和 client_secret 保存到脚本中 ("spotifysecrets.py")。
- 我的主脚本中有 运行 以下代码:
import requests
from spotifysecrets import client_id as cid, client_secret as cs
AUTH_URL = "https://accounts.spotify.com/api/token"
token_req = requests.post(AUTH_URL, {
"grant_type": "client_credentials",
"client_id": cid,
"client_secret": cs
})
access_token = token_req.json()["access_token"]
到目前为止一切似乎都运行良好。问题出现在下一步。
- 获得令牌后,我在尝试发出曲目请求时收到 401 错误。我写的代码如下:
pl_id = "…" # I have elided the actual playlist ID for the purposes of this question
tracks = "https://api.spotify.com/v1/playlists/{}/tracks".format(pl_id)
songs_req = requests.get(tracks, {
"Authorization": "Basic {}".format(access_token)
})
编辑
我试过使用
songs_req = requests.get(tracks, headers={
"Authorization": "Basic {}".format(access_token)
})
相反,但这会产生 400 错误。
我查看了 api,我认为你有一个语法错误:
songs_req = requests.get(tracks, {
"Authorization": "Basic {}".format(access_token)
})
应该是:
songs_req = requests.get(tracks, {
"Authorization": "Bearer {}".format(access_token)
})
我是 API 的新手。我正在尝试创建一个脚本,该脚本将从 Spotify 输出 public 播放列表的曲目。我在早期遇到了障碍:我不确定如何准确格式化我的 GET 请求 以检索相关播放列表的曲目以及我将 OAuth 访问令牌放在哪里。我当前的尝试 returns 一个 401 状态代码。
到目前为止我做了什么:
- 我已经在 Spotify 开发者网站仪表板上创建了一个应用程序。
- 我已将仪表板中的 client_id 和 client_secret 保存到脚本中 ("spotifysecrets.py")。
- 我的主脚本中有 运行 以下代码:
import requests
from spotifysecrets import client_id as cid, client_secret as cs
AUTH_URL = "https://accounts.spotify.com/api/token"
token_req = requests.post(AUTH_URL, {
"grant_type": "client_credentials",
"client_id": cid,
"client_secret": cs
})
access_token = token_req.json()["access_token"]
到目前为止一切似乎都运行良好。问题出现在下一步。
- 获得令牌后,我在尝试发出曲目请求时收到 401 错误。我写的代码如下:
pl_id = "…" # I have elided the actual playlist ID for the purposes of this question
tracks = "https://api.spotify.com/v1/playlists/{}/tracks".format(pl_id)
songs_req = requests.get(tracks, {
"Authorization": "Basic {}".format(access_token)
})
编辑
我试过使用
songs_req = requests.get(tracks, headers={
"Authorization": "Basic {}".format(access_token)
})
相反,但这会产生 400 错误。
我查看了 api,我认为你有一个语法错误:
songs_req = requests.get(tracks, {
"Authorization": "Basic {}".format(access_token)
})
应该是:
songs_req = requests.get(tracks, {
"Authorization": "Bearer {}".format(access_token)
})