I'm trying to to get the track ID in Python for a track in Spotify (https://open.spotify.com/track/track_id) after returning search results for a track using artist and track name but just keep getting key errors.
I think I have my query correct and if I just return and print the json result, it appears to be returning usable information but if I try to strip out the id:
track_id = result["id"]
Then I only get key errors. I've tried all sorts but I cannot figure it out for the life of me. Using "href" instead of "id" (track_id = result["href"]) is the only thing that seems to return anything other than a key error. Any help would be most appreciated and my code is as follows (I'm using Mutagen to strip out metadata from files for the search). Any help would be massively appreciated. This is my first time using Python so ELI5 😅
def search_for_track(token, artist_name, track_name):
url = "https://api.spotify.com/v1/search"
headers = get_auth_header(token)
query = f"?q=track:{track_name} artist:{artist_name}&type=track&limit=1"
query_url = url + query
result = get(query_url, headers=headers)
json_result = json.loads(result.content)["tracks"]
return (json_result)
ext = (".aiff", ".mp3", ".wma", ".ogg", ".flac", ".ape", \
".mpc", ".opus", ".tta", ".wv", ".ofr", ".ofs", \
".off", ".asf", ".vob", ".oga")
def open_dir():
dirname = filedialog.askdirectory()
for entry in os.scandir(dirname):
if entry.is_file() and entry.name.endswith(tuple(ext)):
#print(entry.path)
audio = mutagen.File(entry.path, easy=True)
artist = audio.get('artist', ['Unknown'])[0]
title = audio.get('title', ['Unknown'])[0]
#print(f"Artist: {artist}")
#print(f"Title: {title}")
token = get_token()
result = search_for_track(token, artist, title)
track_id = result["id"]
print(track_id)