Application Programming Interface

I wanted to learn more about APIs so I played around with Spotify’s API. According to Red Hat, an API is a set of definitions and protocols for building and integrating application software. Spotify provides software and app developers access to their data about artists, playlists and track features through a Web API.

The common process for data extraction using APIs follows:

  1. Send a HTTP GET request to the API endpoint.
  2. Accept the response, which is mostly likely formatted in JSON.
  3. Parse the response and save it as a JSON or CSV file that you can load into a destination.

Before doing anything, you will need to create a Client ID and a Client Secret Code. This can be done by creating an app using your Spotify Developer account. You can log in using your existing Spotify account as well. The Spotify Web API is very well documented and you can view all the endpoints here. This link also goes through in depth on how to create your Client ID and Client Secret Code.

Going through one of my playlists

I was going through a tough time and curated a playlist to get me through. I am interested in this playlist because there was a sequence to adding a specific song to the playlist. The playlist has only 25 songs but I want to see how the audio features of the songs change throughout the playlist.

Playlist in question

Playlist in question

Getting an access token

To query the API and handle the response in Python, you will need the requests library. You can then use requests to query the API endpoint, get the response and print out the resulting JSON. To access any endpoints of the Spotify API, we need to have an access token. This access token needs to be saved after we POST a request with our client credentials: Client ID and Client Secret Code.

# Code snippet to get access token

# POST
AUTH_URL = '<https://accounts.spotify.com/api/token>'
auth_response = requests.post(AUTH_URL, {
	'grant_type': 'client_credentials',
	'client_id': CLIENT_ID,
	'client_secret': CLIENT_SECRET
})

# Convert the response to JSON
auth_response_data = auth_response.json()

# Save the access token
access_token = auth_response_data['access_token']

headers = {
	'Authorization': 'Bearer {token}'.format(token = access_token)
}