Error 401 unauthorized on /me request but not /search request Python
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Plan
Premium
Country
United Kingdom
Operating System
(Windows 11)
IDE
Pycharm
My Question or Issue
I've tried searching through the topics to find the solution and while there do appear to be solutions relating to my issue, they are either not using Python so it's hard for me as a beginner to interpret or they appear to be laid out the same as mine and maybe there's something really simple I'm not noticing.
My /me request keeps returning this error: {'error': {'status': 401, 'message': 'Unauthorized.'}} When I run the /search request I get all the information no issue so I don't think there's a problem with my API token. My goal is to create a playlist and populate it with songs from a list within the program. The create playlist function needs the user_id but this just doesn't want to work for me.... Any help would be appreciated!
class Spotify:
def __init__(self😞
self.CLIENT_ID = "CLIENT_ID"
self.CLIENT_SECRET = "CLIENT_SECRET"
self.spotify_api_endpoint = "https://accounts.spotify.com/api/token"
self.spotify_endpoint = "https://api.spotify.com/v1"
self.access_token = self.get_token()
self.authorization = {"Authorization": f"Bearer {self.access_token}"}
self.uri_code = ""
self.user_id = self.get_user_id()
def get_token(self😞
auth_string = self.CLIENT_ID + ":" + self.CLIENT_SECRET
auth_bytes = auth_string.encode("utf-8")
auth_base64 = str(base64.b64encode(auth_bytes), "utf-8")
headers = {
"Authorization": "Basic " + auth_base64,
"Content-Type": "application/x-www-form-urlencoded"
}
data = {
"grant_type": "client_credentials",
}
response = requests.post(self.spotify_api_endpoint, headers=headers, data=data)
json_data = json.loads(response.content)
return json_data["access_token"]
def get_user_id(self😞
url = f"{self.spotify_endpoint}/me"
print(self.authorization)
response = requests.get(url, headers=self.authorization)
user_data = response.json()
print(f"User data requested:\n{user_data}")
return user_data["id"]
def get_song_codes(self, artist, song):
query = f"?q={artist}%20track:{song}&type=track&limit=1"
query_url = f"{self.spotify_endpoint}/search{query}"
response = requests.get(query_url, headers=self.authorization)
song_data = json.loads(response.content)
self.uri_code = song_data["tracks"]["items"][0]["uri"]
print(song_data)
- Labels:
-
Possible Bug
- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page