-
Notifications
You must be signed in to change notification settings - Fork 0
Broken code examples
This page includes code examples of how client code directly interfacing with the Spotify REST api ends up messy at best, and fragile at worst.
Client code requires understanding of Spotify ODM (object data model).
getReq = 'https://api.spotify.com/v1/playlists/' + id
r = requests.get(url=getReq, headers={'Authorization': 'Bearer ' + token})
tracks = r.json()['tracks']['items']For a while, this was the only way to retrieve playlists unassociated with users (Today’s Top Hits, for example). This has since been patched (it took 3 years to do it), which speaks to the incremental development process for the Spotipy api.
imageURL = tracks[0]['track']['album']['images'][1]['url']To fetch an image URL for an album cover given a list of tracks, you have to have an extremely keen understanding of the underlying JSON object representation.
Create a new object hierarchy that reflects a more logical ordering of the data provided by Spotify.
To make client code less fragile and survive changes in the REST api, have objects for songs, albums, playlists, etc. that handle processing of the JSON objects returned by the REST api. This will make ODM changes invisible to client code so that they will not need to change it as long as the api version is up to date.
Each object should wrap appropriate Spotify endpoints, making client code cleaner, and removing the need to understand the Spotify ODM.
-
Authentication tokens: how should they be refreshed in the case of a failure?
We have decided to have a top level objectsp = Spotifython()that manages authentication, reauthentication, and getting of other objects (such as tracks or users). All object gotten from the top levelSpotifythonobject will contain a reference to the internal auth token, so that if the client ever callssp.reauthenticate(TOKEN), all other objects will immediately have the correct token.
If a method call on any library object returns from Spotify with anunauthorizedexception, we will inform the client so that they can reauthenticate. -
Lazy loading of data: it is likely that most clients will not need all of the detailed information provided by the Spotify api calls. For example, tracks contain detailed analytics (such as BPM, the number of bars, confidence interval, see more at Get Audio Analysis for a Track) that not all users of the api will care about.
As such, we will only make REST api calls when that specific piece of information is needed by the api user.
In addition, Spotify rate limits requests, and recommends batching your requests to avoid being limited. If we design the implementation with lazy data fetching in mind, it’s possible to save our clients the hassle of retries (at least sometimes).