1
votes

Using the documentation for authorisation, There are 2 steps in getting a Spotify OAuth Token

  1. App requests authorization and receives a authorization code.
  2. App posts a request to receive a OAuth Token. https://developer.spotify.com/documentation/general/guides/authorization-guide/

When I try to POST a request to receive an Oath Token I get a 400 error. The code is a a bit dirty, sorry about that.

import json
import requests
from urllib.parse import urlencode

#credentials
USER_ID = '31......fbq'
CLIENT_ID = '553b......9dd'
CLIENT_SECRET = '16c40......24067b'


# encodes and prints URL
auth_url = 'https://accounts.spotify.com/authorize'
scopes_params = urlencode({
    'client_id': CLIENT_ID,
    'scope': 'playlist-modify-private',
    'redirect_uri': 'http://localhost:8000',
    'response_type': 'code'
})

scope_url = auth_url + '?' + scopes_params
print(scope_url)

response = requests.get(scope_url)
# Authorization code is copy pasted here
authorization_code = input('Enter Authorization_Code: ')

request_body_token = json.dumps({
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET,
    'grant_type': 'authorization_code',
    'code': authorization_code,
    'redirect_uri': 'http://localhost:8000'
})

access_token_request = requests.post(url='https://accounts.spotify.com/api/token', 
data=request_body_token)
print(access_token_request.status_code)

This is the section of the authorization code I copy paste in from the redirect URI enter image description here

Let me know if any additional information is needed.

1

1 Answers

1
votes

I found out the issue. The request_body_token doesn't need to be converted from JSON to Python using json.dumps method, the dictionary can already be parsed in the data/body. Solution Below:

import json
import requests
from urllib.parse import urlencode

#credentials
USER_ID = '31ldam........w3wwfbq'
CLIENT_ID = '553bc4.........c0b3f09dd'
CLIENT_SECRET = '16c400........a24067b'

ENPOINT = f'https://api.spotify.com/v1/users/{USER_ID}/playlists'

# encodes and prints URL
auth_url = 'https://accounts.spotify.com/authorize'
scopes_params = urlencode({
    'client_id': CLIENT_ID,
    'scope': 'playlist-modify-private',
    'redirect_uri': 'http://localhost:8000',
    'response_type': 'code'
})

scope_url = auth_url + '?' + scopes_params
print(scope_url)

# Authorization code is copy pasted here
response = requests.get(scope_url)
authorization_code = input('Enter Authorization_Code: ')

# Here is where the error was, json.dump removed
request_body_token = {
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET,
    'grant_type': 'authorization_code',
    'code': authorization_code,
    'redirect_uri': 'http://localhost:8000'
}

access_token_request = requests.post(url='https://accounts.spotify.com/api/token', data=request_body_token)
print(access_token_request.status_code)
access_token = access_token_request.json()['access_token']