Reputation: 39
Using Python, I'm trying to do a POST call to the Spotify API by following the instructions under the paragraph Client Credentials Flow at the link https://developer.spotify.com/web-api/authorization-guide/#client_credentials_flow and this is the code I have come up with.
However, I get Response [415]
when I run it. Can anyone tell me what is wrong?
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
Upvotes: 3
Views: 5826
Reputation: 685
The type of authentication that Spotify is requesting is just basic HTTP authentication. This is a standardised form of authentication which you can read more about here. The requests library supports basic authentication without requiring you to create the headers yourself. See the python requests documentation for information.
The code below uses the request library authentication to connect to the 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
I created a test account with Spotify and created a test client id and client secret which worked find for this. I got a response 200 back using python 2.7.6 and requests 2.2.1.
Upvotes: 10