Using pagination with the Spotify search API
Question:
I’m working on a program that pulls up random songs within a specified genre on Spotify. Each track is denoted by an random ‘offset’ inside the search query, per the Spotify docs here. But I’m unable to put a number higher than 999 in this (like the total number of songs marked under a genre), otherwise the request 404’s.
They talk about using offset "with limit to get the next page of search results" in the docs above, but changing limit to any number 1-50 still returns the same song, it’s the offset that matters.
Here’s a snippet of my code where I make the final request:
random_offset = str(random.randint(0, 999))
if (int(random_offset) > total):
random_offset = str(random.randint(1, total))
url = BASE_URL + '?q=genre%3A%22%20' + rand_genre + '%22&type=track&offset=' + random_offset + '&limit=1'
genre_results = requests.get(url, headers=headers)
genre_results_json = genre_results.json()
Is there anything I can do to use pagination to perhaps randomly iterate through pages of results if Spotify has any, or am I limited to 1000 tracks in my query?
Answers:
Couldn’t you copy the code you have but change the random integer limits?
It turned out that Spotify’s API just doesn’t allow for more than the first 1000 results to be queried, so I stuck with using 0-999 for my program’s random integers.
I’m working on a program that pulls up random songs within a specified genre on Spotify. Each track is denoted by an random ‘offset’ inside the search query, per the Spotify docs here. But I’m unable to put a number higher than 999 in this (like the total number of songs marked under a genre), otherwise the request 404’s.
They talk about using offset "with limit to get the next page of search results" in the docs above, but changing limit to any number 1-50 still returns the same song, it’s the offset that matters.
Here’s a snippet of my code where I make the final request:
random_offset = str(random.randint(0, 999))
if (int(random_offset) > total):
random_offset = str(random.randint(1, total))
url = BASE_URL + '?q=genre%3A%22%20' + rand_genre + '%22&type=track&offset=' + random_offset + '&limit=1'
genre_results = requests.get(url, headers=headers)
genre_results_json = genre_results.json()
Is there anything I can do to use pagination to perhaps randomly iterate through pages of results if Spotify has any, or am I limited to 1000 tracks in my query?
Couldn’t you copy the code you have but change the random integer limits?
It turned out that Spotify’s API just doesn’t allow for more than the first 1000 results to be queried, so I stuck with using 0-999 for my program’s random integers.