Bored of Libraries? Here’s How to Connect to the Spotify API Using Pure Python

How you can connect to the Spotify API using pure Python.

Sean Dutton-Jones
Python in Plain English

--

Photo by Thibault Penin on Unsplash

I often find myself carelessly installing Python libraries while writing code — mostly because Python libraries make life so easy (well, usually). However, this type of carelessness comes with a cost: I often find myself looking up how to code the easiest of tasks in Python. So, I’ve made a commitment to write more code myself and rely less on libraries. I’d like to bring you on this journey with me!

Introduction and Setup

Today, we’ll be walking through how to connect to the Spotify API using (mostly) pure Python. Spotify’s API gives access to a gargantuan amount of music and artist-related information. If you’re a music lover like myself, the API offers an excellent opportunity to explore your taste in music, listening patterns, popular songs, and a lot more.

To start, it’s always good practice to spin up a shiny new virtual environment for each Python project. This step is optional, however, so I’ll save you the bore of creating one and assume you have one ready to go. I would also recommend using Jupyter Notebook, but it’s not required for this tutorial.

Here is a list of Python libraries you’ll need for this tutorial:

The only library you’ll need to install is requests: pip install requests. The urllib library is installed with requests.

Okay, with that long list of libraries out of the way, let's get into it!

Creating a New Application on Spotify’s Developer Dashboard

First, you’ll want to head over to Spotify’s developer dashboard and create a new application.

Once you’re there, you’ll need to log in using your Spotify credentials:

Once you’ve logged in, you’ll see a screen similar to this:

We want to create a new application, so click the “Create an App” button. You’ll be prompted to input a name for your application and give it a short description.

I’ve named my app a very creative name: Medium Tutorial. Try to beat that creativity!

Once you’ve given your application a name and title, click the “Create” button. This will create a new application and bring you to the app’s dashboard. There isn’t much information on the app’s dashboard yet, but once you start querying Spotify’s API, more information will populate. I won’t go over all that today, but it's certainly worth checking out!

From the app’s dashboard, click the “Edit Settings” button. We need to add a callback URL. I will touch more on this later, but briefly, this callback URL will be used to obtain the authorization code, which will in turn be used to obtain our authorization token.

Clicking on the “Edit Settings” button will open a settings dialogue. Once there, scroll down until you see a section titled “Redirect URIs”. Enter this URL http://localhost:7777/callback I’ve chosen the localhost URL because it will make things more simple later on when we start writing code!

After you’ve entered that URL, click the “Add” button and then scroll all the way down and hit “Save”.

The final step we need to do before we start coding is to obtain our Client ID and our Client Secret codes. These codes are used to authenticate your application to Spotify’s API. A quick note, the Client ID is okay to share, but the Client Secret is a… secret! Make sure not to share it with anyone.

You can find these codes on your app’s dashboard:

For now, keep these codes handy because we’ll be using them when we write code.

Speaking of writing code, let's get into it!

Obtaining our Authorization Code

The first step is to retrieve our authorization code. We will use this code to obtain our authorization token. Why two different codes? The authorization code is a temporary code, which does not grant access to a user’s saved tracks. In order to obtain access to a user’s saved tracks, we need the authorization token. The authorization token is more permanent than the authorization code and can be used to make repeated requests to the API.

Remember the Client ID and Client Secret codes from a few moments ago? Okay good, because we’ll need them here.

I’ll highlight some of the important parts of the code above:

  • client_id and client_secret are where you should enter your codes from the Spotify Developer Dashboard.
  • auth_headers are the headers for this initial request to Spotify. Let’s go over each header:
  • client_id This is your client_id from above. It identifies you to Spotify.
  • response_type This field specifies that we want an authorization code from Spotify, hence the “code” part of it.
  • redirect_uri This is the callback URL we entered in the Spotify Developer Dashboard. When we make the request, your browser will open to this URL.
  • scope This field is for security purposes. In this case, we are requesting to read the user’s library. You can find a complete list of scopes on Spotify’s developer docs.

Finally, we run the linewebbrowser.open("https://accounts.spotify.com/authorize?" + urlencode(auth_headers)) This is where we actually make the request to Spotify for the authorization code. Your web browser will open and ask you to log in to Spotify using your credentials. Once logged in, it will ask you to Agree. You are agreeing to let Spotify read your library, which is where the scope field comes into play.

Once you’ve logged in and agreed, you’ll be redirected to a blank page. Don’t be alarmed! If you look at the URL of the blank page, you’ll see something similar to this:

This is the redirect URL from earlier, with our authorization code as a parameter. Copy that code (without the code= part) into a variable. The code is quite long, so make sure to copy the entire thing!

Wahoo! We’re halfway there! Now, we just need to use this authorization code to obtain our authorization token!

Obtaining our Authorization Token

The next step is to obtain our authorization token. Once we have the token, we can pass it to Spotify’s API and start querying our data!

Let me explain the code:

  • encoded_credentials Spotify requires us to provide our client_id and client_secret in a base64 encoded format to authorize us. The format is client_id:client_secret
  • token_headers We add our encoded_credentials to the Authorization field with "Basic " prepended. This format is required by Spotify.
  • token_data The grant_type field indicates we are going to be passing in our authorization code from the previous step. We enter the authorization code in the code field and supply our redirect URL in the redirect_uri field.

Finally, we run the line r = requests.post("https://accounts.spotify.com/api/token", data=token_data, headers=token_headers) which makes a request to the https://accounts.spotify.com/api/token endpoint with our token_headers and token_data attached.

Once that code has run, we get a response object (which is worth exploring) with our authorization token in the field: access_token .

Congratulations! We’ve successfully obtained our Spotify API authorization token. In theory, that’s the end of this tutorial, but I like concrete examples, so I’ll show you how to retrieve your saved tracks from the API using this token.

Concrete Example: Making a Request to Spotify’s “Track” Endpoint

Let me explain the code:

  • user_headers Here, we input our new authorization token and tell Spotify we want the response in a JSON encoded format
  • user_params This line tells Spotify how many results per page we want. Unfortunately, 50 is the maximum number of tracks we can query at once. If you wish to query all of your saved songs, you’ll need to loop through the response pages by adding the offset field in the user_params dictionary. The offset starts at 0, so to obtain the next 50 songs, you would set offset=50.

Finally, we make a request to the https://api.spotify.com/v1/me/tracks endpoint with our user_headers and user_params attached.

From there, you can explore the response object which contains your last 50 saved tracks and a bunch of other information!

Conclusion

That’s it! You can read more about Spotify’s API endpoints here.

Thanks for reading! I hope you learned something and had fun! You can find the full code (as a Jupyter Notebook) on my Github.

Note: If there is interest, I would love to make a data analysis tutorial to show off all the fantastic music insights we can gain from the Spotify API.

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Join our community Discord.

--

--

Simon Fraser University Undergraduate. An avid programmer and tech enthusiast. Constant learner.