401 error

{'error': {'status': 401, 'message': 'Invalid access token'}}
What i need to do in this sutiation ?

import json
from dotenv import load_dotenv
import os
import base64
from requests import post, get

load_dotenv()

client_id = os.getenv('CLIENT_ID')
client_secret = os.getenv('CLIENT_SECRET')


def get_token():
auth_string = client_id + ':' + 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']
return token


def get_auth_header(token):
return {'Authorization': 'Bearer ' + token}


def search_for_artist(token, artist_name):
url = 'https://api.spotify.com/v1/search'
headers = get_auth_header(token)
query = f'?q={artist_name}&type=atrist&limit=1'

query_url = url + query
result = get(query_url, headers=headers)
json_result = json.loads(result.content)
print(json_result)


print(get_token())
token = get_token()
search_for_artist('token', 'ACDC')
Child Item
Child Item
Child Item

Accepted answers

All comments

Thanks for posting your code. I see a couple of issues in your code:

  1. Typo in the search_for_artist function. You have a typo in the type parameter. It should be 'artist' instead of 'atrist'.
  2. Incorrect function call in the last line. You are passing the string 'token' instead of the actual token variable.
Child Item
Child Item