【问题标题】:"Error parsing JSON" when using Spotify API使用 Spotify API 时“解析 JSON 时出错”
【发布时间】:2015-07-06 10:44:14
【问题描述】:

我正在学习 Python,我正在尝试使用 Spotify web api 创建一个播放列表,但收到 http 400 错误:解析 json 时出错。我想这与令牌中不正确的变量类型有关,但我很难调试它,因为我无法找到以原始格式查看发布请求的方法。

通过 API 发布需要授权,这是我为此创建的脚本:

import requests
import base64
requests.packages.urllib3.disable_warnings()

client_id = 'ID'
client_secret = 'SECRET'
redirect_uri = 'http://spotify.com/'
scope = 'playlist-modify-private playlist-read-private'

def request_token():

    #  1. Your application requests authorization
    auth_url = 'https://accounts.spotify.com/authorize'
    payload = {'client_id': client_id, 'response_type':'code','redirect_uri':redirect_uri}
    auth = requests.get(auth_url,params = payload)
    print '\nPlease go to this url to authorize ', auth.url

    #  2. The user is asked to authorize access within the scopes
    #  3. The user is redirected back to your specified URI
    resp_url = raw_input('\nThen please copy-paste the url you where redirected to: ')
    resp_code= resp_url.split("?code=")[1].split("&")[0]

    #  4. Your application requests refresh and access tokens
    token_url = 'https://accounts.spotify.com/api/token'
    payload = {'redirect_uri': redirect_uri,'code': resp_code, 'grant_type': 'authorization_code','scope':scope}
    auth_header = base64.b64encode(client_id + ':' + client_secret)
    headers = {'Authorization': 'Basic %s' % auth_header}
    req = requests.post(token_url, data=payload, headers=headers, verify=True)
    response = req.json()

    return response

这是实际尝试使用授权令牌创建播放列表的函数(import authorizer 是上面的函数):

import requests
import authorizer

def create_playlist(username, list_name):
    token = authorizer.request_token()
    access_token = token['access_token']
    auth_header = {'Authorization': 'Bearer {token}'.format(token=access_token), 'Content-Type': 'application/json'}
    api_url = 'https://api.spotify.com/v1/users/%s/playlists' % username
    payload = {'name': list_name, 'public': 'false'}
    r = requests.post(api_url, params=payload, headers=auth_header)

但无论我尝试什么,它只会导致 400 错误。谁能在这里指出我的错误?

【问题讨论】:

  • 你能提供更多的错误输出吗?你有错误发生的行号吗?
  • 你是怎么打电话给create_playlist的?
  • @Celeo,这是从 Web API 返回的响应,因此代码中没有任何内容引发错误。
  • 我怀疑要么 last_name 为空,要么公共值 'false' 需要是一个实际的布尔值而不是字符串。
  • @skyline75489 create_playlist('elissinger','testlist')

标签: python json api token spotify


【解决方案1】:

通过为输入添加 json.dumps 解决:json.dumps(payload) 并将负载更改为“数据”而不是请求中的“参数”。

所以新的功能请求等于:

r = requests.post(api_url, data=json.dumps(payload), headers=auth_header)

【讨论】:

  • 嗯,这很有趣。我对data=payload 的授权没有问题(我不需要调用json.dumps()),但我在创建播放列表时有它。幸运的是,您的解决方案有所帮助。谢谢。
猜你喜欢
  • 2021-12-29
  • 1970-01-01
  • 2020-07-19
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
  • 2012-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多