【问题标题】:Problem sending post requests to spotify api in python在 python 中发送 post 请求以发现 api 的问题
【发布时间】:2022-01-11 00:04:36
【问题描述】:
def queue_song(session_id):
    song_uri='spotify:track:5RwV8BvLfX5injfqYodke9'
    tokens = get_user_tokens(session_id)
    headers = {'Content-Type': 'application/json',
               'Authorization': "Bearer " + tokens.access_token,
               }
    url = BASE_URL +'player/queue'
    data={
        'uri':song_uri
    }
    response = requests.post(url,headers=headers,data=data).json()
    print(response)

输出:

{'error': {'status': 400, 'message': 'Required parameter uri missing'}}

https://developer.spotify.com/documentation/web-api/reference/#/operations/add-to-queue

我不认为身份验证令牌有任何问题...因为“GET”请求工作正常

【问题讨论】:

    标签: python post request spotify http-status-code-400


    【解决方案1】:

    默认情况下,在requests.post() 中使用data= 会将内容类型设置为application/x-www-form-urlencoded,这使得正文类似于HTTP 表单请求。

    Spotify 的 API 是基于 JSON 的,因此您的数据需要是有效的 json 数据。

    您可以通过两种方式做到这一点:

    response = requests.post(url,headers=headers,data=json.dumps(data)).json()
    

    或者,更简单地说:

    response = requests.post(url,headers=headers,json=data).json()
    

    这样您也不需要手动设置application/json 标头。

    编辑: 在浏览了您链接的 API 文档后,您所做的调用存在更多错误。

    您在data 中发送参数 - 这是请求的正文。但是 Spotify API 指定了需要放入 Query 的参数,即 URI 的查询字符串。这意味着您的请求应该是:

    response = requests.post(url,headers=headers,params=data).json()  # set query string not body
    

    【讨论】:

    • 我是网络开发新手,无法从文档中理解我应该在 URL 中传递“song_uri”。我觉得你的解释真的帮助我理解了一些非常重要的事情。非常感谢您帮助这个新手,无法投票:(
    猜你喜欢
    • 1970-01-01
    • 2019-08-08
    • 2018-09-13
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 2017-10-16
    • 2019-10-19
    • 1970-01-01
    相关资源
    最近更新 更多