Spotify API Authentication Issue - Script Freezes During Data Collection

I’m building a Python application that extracts music data from Spotify playlists and saves it to CSV format. The program was working fine initially, processing all songs from multiple playlists successfully. However, after running for about an hour, it started freezing during track processing.

I think this might be related to token expiration, so I added functionality to refresh the token at the start of my script. But now, instead of throwing any error messages, the program gets stuck on the very first song. Previously, it would process hundreds of tracks before stopping, but now it halts immediately.

I attempted to switch from SpotifyOAuth to SpotifyClientCredentials assuming it may help with authentication, but the problem continues. The script just hangs without any error output, which complicates debugging.

Here’s my current implementation:

import csv
from datetime import datetime, timedelta
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import time

# Authentication setup
client_id = 'your_client_id'
client_secret = 'your_client_secret'

auth_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)
spotify_client = spotipy.Spotify(auth_manager=auth_manager)

# Playlist IDs to process
playlist_collection = ['37i9dQZF1DX4JAvHpjipBk', '37i9dQZF1DX0XUsuxWHRQd', '37i9dQZF1DXdwmD5Q7Gxah']

song_data = []

def update_token():
    spotify_client.auth_manager.get_access_token(as_dict=False, check_cache=False)

update_token()

# Process each playlist
for playlist_id in playlist_collection:
    playlist_info = spotify_client.playlist(playlist_id)
    track_results = spotify_client.playlist_tracks(playlist_id)
    
    position = 1
    
    for item in track_results['items']:
        current_track = item['track']
        print(f"Working on: {current_track['artists'][0]['name']} - {current_track['name']}")
        
        try:
            artist_details = spotify_client.artist(current_track['artists'][0]['id'])
            album_details = spotify_client.album(current_track['album']['id'])
            
            song_data.append({
                'performer': current_track['artists'][0]['name'],
                'title': current_track['name'],
                'release_date': current_track['album']['release_date'],
                'playlist_position': position,
                'artist_followers': artist_details['followers']['total'],
                'cover_image': current_track['album']['images'][0]['url'],
                'song_popularity': current_track['popularity'],
                'artist_popularity': artist_details['popularity'],
                'isrc_code': current_track['external_ids']['isrc'],
                'record_label': album_details['label'],
                'spotify_link': current_track['album']['external_urls']['spotify'],
                'playlist_id': playlist_id,
                'playlist_title': playlist_info['name']
            })
            position += 1
            
        except spotipy.exceptions.SpotifyException:
            update_token()
            continue
        except Exception as error:
            print(f"Error processing track: {error}")
            continue
    
    time.sleep(1)

# Save to CSV
with open('spotify_data.csv', 'w', newline='') as output_file:
    field_names = ['performer', 'title', 'release_date', 'playlist_position', 'artist_followers']
    csv_writer = csv.DictWriter(output_file, fieldnames=field_names)
    csv_writer.writeheader()
    
    for song in song_data:
        csv_writer.writerow(song)

Why is my script hanging without throwing any errors? How can I properly handle token refresh to keep the script running smoothly? Any suggestions for debugging this authentication issue would be really helpful.

I’ve hit the same freezing issue with Spotify API scripts. It’s usually rate limiting, not auth problems. The API has strict limits and spotipy doesn’t handle them well - you get silent hangs instead of proper errors.

Your script hammers the API with multiple calls per track (artist info, album info) and burns through the rate limit fast. Add exponential backoff with longer delays between requests. I fixed mine with a custom retry system that catches rate limit responses and waits progressively longer before trying again.

Also, that update_token() call in your exception handler might be causing problems. ClientCredentials tokens don’t expire as often as user tokens. Drop that call and implement proper rate limit handling with time.sleep() that increases when you hit limits.

Your hanging issue is probably Spotify’s API rate limiting you without sending proper HTTP 429 responses. Switching to ClientCredentials fixed the token refresh headache, but the rate limiting stuck around.

I’ve hit this same problem with large datasets. Your script makes 3 API calls per track (playlist_tracks, artist, album) and burns through the rate limit fast. Instead of failing cleanly, spotipy just hangs forever waiting for responses that’ll never come.

Wrap your API calls in a timeout using threading or subprocess - this forces the script to keep moving when requests hang. Also try batching differently: grab all track IDs first, then batch process artist and album data separately with bigger delays between batches.

Since it worked initially but dies right after restart, you’re probably hitting daily or hourly rate limits that reset over time.

Been there! Your issue is probably the Spotify API silently throttling you. Try adding a requests timeout to your spotipy client - something like requests_timeout=10 in the Spotify() constructor. Without timeouts, the script just waits forever when Spotify stops responding. Also consider caching artist/album data since you’re probably hitting the same artists multiple times across playlists.