import refresh_token
import requests
import os
import base64
import json
from requests import post
def get_token():
desired_scope = 'ugc-image-upload playlist-modify-private playlist-modify-public user-
read-currently-playing'
id = os.environ.get('client_id')
secret = os.environ.get('client_secret')
url = "http://localhost:8000/callback/"
auth_string = f'{os.environ.get("client_id")}:{os.environ.get("client_secret")}'
auth_bytes = auth_string.encode("utf-8")
auth_base64 = str(base64.b64encode(auth_bytes), "utf-8")
url = "https://accounts.spotify.com/api/token"
headers = {"Authorization": "Basic " + auth_base64,"Content-Type": "application/x-www-
form-urlencoded"}
data = {"grant_type": "client_credentials"}
result = post(url, headers=headers,data=data)
json_result = json.loads(result.content)
token = json_result["access_token"]
print(token)
return token
def get_currently_playing(token):
headers = {'Authorization': 'Bearer ' + token,}
url = 'https://api.spotify.com/v1/me/player/currently-playing'
response = requests.get(url, headers=headers)
print(response.json())
if response.status_code == 200:
response_json = response.json()
if response_json['is_playing']:
track_name = response_json['item']['name']
artist_name = response_json['item']['artists'][0]['name']
album_name = response_json['item']['album']['name']
return f'You are currently listening to {track_name} by {artist_name} from the album {album_name}.'
else:
return 'You are not currently listening to any music.'
else:
return 'Unable to get currently playing track.'
access_token = get_token()
song = get_currently_playing(access_token)
print(song)
This code will produce the error {'error': {'status': 404, 'message': 'Invalid username'}} and print Unable to get currently playing track.
When I run the code I get this 404 error which says I have an invalid username. I don't understand, are you suppost to add your username somewhere? I've tried adding username to headers but nothing seems to work
That's because you are using client credentials. To use player API you need to use server sided authorization (OAuth), take a look at this Spotify guide.