Hey everyone, I’m having a weird issue with the Spotify API through spotipy. Yesterday I was working on a script that makes lots of API calls and I think I hit their rate limit because everything just started hanging. After sleeping on it, I rewrote my code to add delays between requests and set retries to 0 so it would actually throw errors instead of hanging forever.
But now I’m getting 429 errors constantly. I can make exactly one successful request and then every request after that fails with a 429 error. Even when I wait several minutes between attempts, it still happens.
Here’s my current code:
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import time
def setup_spotify_client():
client = spotipy.Spotify(
retries=0,
auth_manager=SpotifyOAuth(
client_id='client_id_here',
client_secret='secret_here',
scope='playlist-read-private playlist-modify-public',
redirect_uri='http://localhost:8888/callback'
)
)
return client
class SpotifyHandler:
def __init__(self, username):
self.last_call = time.time()
self.client = setup_spotify_client()
self.username = username
def fetch_tracks_from_playlist(self, playlist_id, start_offset, attempt_count=0):
time_passed = time.time() - self.last_call
if time_passed > 1:
try:
result = self.client.user_playlist_tracks(self.username, playlist_id, offset=start_offset, limit=100)
self.last_call = time.time()
return result
except spotipy.exceptions.SpotifyException as error:
if error.http_status == 429:
print(f"Rate limited: {error}")
wait_time = (2 ** attempt_count) * 3
print(f"Waiting {wait_time} seconds before retry...")
time.sleep(wait_time)
return self.fetch_tracks_from_playlist(playlist_id, start_offset, attempt_count + 1)
else:
raise error
else:
time.sleep(1 - time_passed)
return self.fetch_tracks_from_playlist(playlist_id, start_offset)
handler = SpotifyHandler('my_username')
def collect_all_tracks(playlist_id):
current_offset = 0
all_tracks = []
while True:
print('Making API call...')
batch_result = handler.fetch_tracks_from_playlist(playlist_id, current_offset)
print('Response received')
for item in batch_result['items']:
all_tracks.append(item['track'])
if not batch_result["next"]:
break
current_offset += 100
return all_tracks
if __name__ == '__main__':
tracks = collect_all_tracks('playlist_id_here')
print(f"Found {len(tracks)} tracks")
What’s confusing me is that according to Spotify’s docs, the rate limit is based on a 30 second window. If I’m waiting minutes between requests, there shouldn’t be any issues. The fact that I can make one successful request makes me think it’s not a complete ban, but I can’t figure out what’s going wrong.
I’ve tried using different app credentials from my developer dashboard but get the same problem. Has anyone else run into this? Is there something wrong with how I’m handling the rate limiting?