Help Wizard

Step 1

NEXT STEP

FAQs

Please see below the most popular frequently asked questions.

Loading article...

Loading faqs...

VIEW ALL

Ongoing Issues

Please see below the current ongoing issues which are under investigation.

Loading issue...

Loading ongoing issues...

VIEW ALL

Can't get result from spotify api

Can't get result from spotify api

Plan

Premium

Country

Netherlands

 

Device

PC

Operating System
Windows 10

 

My Question or Issue

I want to make a program that can create charts using the Spotify Api. The code initially worked without authorization and produced results, but then it began to produce a 401 error. I added authorization, but stopped receiving results. I will be glad if you help. I am attaching the code below. (Some values ​​under ### have been removed for safety)

import spotipy
from spotipy.oauth2 import SpotifyOAuth
import json

client_id = '###'
client_secret = '###'

scope = "user-library-read"
redirect_uri = "###"
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=client_id, 
                                               client_secret=client_secret, 
                                               redirect_uri=redirect_uri,
                                               scope=scope))

def get_artist_id(artist_name):
    result = sp.search(q=artist_name, type='artist', limit=1)
    items = result['artists']['items']
    if items:
        return items[0]['id']
    else:
        return None

def load_artists_from_json(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        data = json.load(f)
        return data.get("artists", [])

def get_top_tracks_for_all_artists(artists):
    all_tracks = []
    for artist_name in artists:
        artist_id = get_artist_id(artist_name)
        if artist_id:
            top_tracks = get_top_tracks(artist_id)
            all_tracks.extend(top_tracks)
        else:
            print(f"Artist {artist_name} didn't found.")
    return all_tracks

def get_top_tracks(artist_id):
    top_tracks = sp.artist_top_tracks(artist_id)
    return top_tracks['tracks']

def print_top_tracks(tracks):
    for i, track in enumerate(tracks, 1):
        print(f"{i}. {track['name']} ({track['artists'][0]['name']}) - {track['popularity']} ")

def save_top_tracks_to_file(tracks, file_path):
    with open(file_path, 'w', encoding='utf-8') as f:
        for i, track in enumerate(tracks, 1):
            f.write(f"{i}. {track['name']} ({track['artists'][0]['name']}) - {track['popularity']}\n")

if __name__ == "__main__":
    try:
        current_user = sp.current_user()
        print("Connection to Spotify API is successful.")
        print("User of Spotify:", current_user['display_name'])
    except Exception as e:
        print("Error with connection to Spotify API:", e)
        exit()

    artists = load_artists_from_json("artists.json")

    print("Gettin top-50 songs...")
    all_tracks = get_top_tracks_for_all_artists(artists)

    sorted_tracks = sorted(all_tracks, key=lambda x: x['popularity'], reverse=True)[:50]

    save_top_tracks_to_file(sorted_tracks, "final_chart.txt")

    print("Top-50 is successfully downloaded and was uploaded to 'final_chart.txt'.")

 

Reply
1 Reply

Hi DmitriMulle,

Your code runs fine for me.

It can help to delete the .cache file form where you run the code.

Let me know if this helps

Cheers,

XimzendRising Star
Help others find this answer and click "Accept as Solution".
If you appreciate my answer, maybe give me a Like.
Note: I'm not a Spotify employee.

Suggested posts