pythondjangospotifyspotipy

Getting tracks from a playlist using Spotipy is slow


I'm interacting with the Spotify Web API for a django project that allows users to upload their playlists for them to be ranked according to certain parameters, namely audio features spotify assigns to all tracks.

I'm using the Spotipy library to query the spotify API with python. It's lightning fast for user and playlist data, but following the Spotipy tutorials on how to get tracks from a playlist, I'm finding the response is extremely slow.

The wait time for tracks is about proportional to the length of the playlist in tracks.. I'm thinking it has something to do with an inefficiency in how the spotipy library packages up and sends requests.

Has anyone ever come across a similar bottleneck with regards to getting tracks and speed?


Solution

  • Spotipy is not slow at all.

    Anyway, you can try making requests yourself.

    import requests
    import json
    

    then get your desired endpoint: (refer to: Spotify Web API Endpoint Reference)

    SEARCH_PLAYLIST_ENDPOINT ='https://api.spotify.com/v1/search?type=playlist'
    AUDIO_FEATURES_ENDPOINT = 'https://api.spotify.com/v1/audio-features/{id}'
    

    And provided you have an access token, filter playlist by name:

    def search_playlist(name):
        path = 'token.json'
        with open(path) as t:
            token = json.load(t)
        myparams = {'type': 'playlilst'}
        myparams['q'] = name
        resp = requests.get(SEARCH_PLAYLIST_ENDPOINT, params=myparams, headers={"Authorization": "Bearer {}".format(token)})
        return resp.json()
    

    obviously response time for querying playlist items depend on the number of playlist tracks, which can vary dramatically.

    Then you can use this function to get audio features:

    # https://developer.spotify.com/web-api/get-related-artists/
    def get_audio_features(track_id):
        path = 'token.json'
        with open(path) as t:
            token = json.load(t)
        url = AUDIO_FEATURES_ENDPOINT.format(id=track_id)
        resp = requests.get(url, headers={"Authorization": "Bearer {}".format(token)})
        return resp.json()
    

    Follow the same logic for other requests. Test this and compare with Spotipy speed.