2
votes

I'm trying to write a script that creates a playlist on my spotify account in python, from scratch and not using a module like spotipy.

My question is how do I authenticate with my client id and client secret key using the requests module or grab an access token using those credentials?

2
What have you tried so far? Please paste some codemarsnebulasoup

2 Answers

6
votes

Try this full Client Credentials Authorization flow.

First step – get an authorization token with your credentials:

CLIENT_ID = " < your client id here... > "
CLIENT_SECRET = " < your client secret here... > "

grant_type = '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)) 

token_raw = json.loads(response.text)
token = token_raw["access_token"]

Second step – make a request to any of the playlists endpoint. Make sure to set a valid value for <spotify_user>.

headers = {"Authorization": "Bearer {}".format(token)}
r = requests.get(url="https://api.spotify.com/v1/users/<spotify_user>/playlists", headers=headers)
print(r.text)
0
votes

As it is referenced here, you have to give the Bearer token to the Authorization header, and using requests it is done by declaring the "headers" optional:

r = requests.post(url="https://api.spotify.com/v1/users/{your-user}/playlists", 
                  headers={"Authorization": <token>, ...})

The details of how can you get the Bearer token of your users can be found here