Python:Spotify API Post调用?

时间:2015-05-31 12:27:02

标签: python api post spotify

使用Python,我按照链接https://developer.spotify.com/web-api/authorization-guide/#client_credentials_flow上的客户端凭证流程段下的说明尝试对Spotify API进行POST调用,这是我提出的代码。但是,当我运行它时,我得到了响应[415]。有谁能告诉我出了什么问题?

import pprint
import requests
import urllib2
import json
import base64

client_id='b040c4e03217489aa647c055265d0ac'
client_secret='2c2928bb7d3e43278424002d2e8bda46b'
authorization_param='Basic ' + base64.standard_b64encode(client_id + ':' + client_secret)
grant_type='client_credentials'

#Request based on Client Credentials Flow from https://developer.spotify.com/web-api/authorization-guide/

#Header must be a base 64 encoded string that contains the client ID and client secret key. 
#The field must have the format: Authorization: Basic <base64 encoded client_id:client_secret>
header_params={'Authorization' : authorization_param}

#Request body parameter: grant_type Value: Required. Set it to client_credentials
 body_params = {'grant_type' : grant_type}

url='https://accounts.spotify.com/api/token'

response=requests.post(url, header_params,    body_params) # POST request takes both headers and body parameters
print response

1 个答案:

答案 0 :(得分:8)

Spotify请求的身份验证类型只是基本的HTTP身份验证。这是一种标准化的身份验证形式,您可以阅读有关here的更多信息。请求库支持基本身份验证,而无需您自己创建标头。有关信息,请参阅python requests documentation

以下代码使用请求库身份验证连接到Spotify API。

import requests

client_id = # Enter your client id here
client_secret = # Enter your client secret here

grant_type = 'client_credentials'

#Request based on Client Credentials Flow from https://developer.spotify.com/web-api/authorization-guide/

#Request body parameter: grant_type Value: Required. Set it to client_credentials
body_params = {'grant_type' : grant_type}

url='https://accounts.spotify.com/api/token'

response=requests.post(url, data=body_params, auth = (client_id, client_secret)) 
print response

我使用Spotify创建了一个测试帐户,并创建了一个测试客户端ID和客户端密码,可以找到它。我使用python 2.7.6获得了200响应并请求2.2.1。