In this article/tutorial, I will explore how to build a simple Python application that uses the Spotify API to track the currently playing playlists on your Spotify account. This project is perfect for junior developers looking to understand how OAuth 2.0 works in real-world applications, as well as how to interact with APIs in Python. I will use the Spotify API, Python, Flask, and the OAuth 2.0 authorization flow to make it all work.
By the end of this tutorial, you’ll have a fully functioning Flask app (I will not spend time on the front page, only welcome message on the app) that can authenticate with Spotify, retrieve an access token, and use that token to get the currently playing track. You will also gain a solid understanding of how OAuth 2.0 is being used by many companies to grant secure access to their APIs.
You can copy codes from my GitHub to go through when you are learning this concept.
Prerequisites
Before we dive in, make sure you have the following set up:
- Basic knowledge of Python and Flask.
- A Spotify account.
- Spotify Developer credentials (Client ID and Client Secret). You can create an application on the Spotify Developer Dashboard.
- Python 3.x installed on your system.
- Flask installed in your Python environment. You can install Flask using pip: pip install Flask
Setting Up the Flask Application
I will start by creating a simple Flask application. Create a new directory or landing page for our project.
In the login route, I am building the URL to Spotify’s authorization page, where the user will be asked to log in and authorize our application. Once the user authorizes, they will be redirected to the /callback route with an authorization code.
In the callback route, I exchange this authorization code for an access token. This token is stored in the session and will be used to access the Spotify API.
Fetching the currently playing track
Now that we have the access token, let’s create a route to fetch the currently playing track from the Spotify API.
Codes are available on my GitHub. https://github.com/Regis7/Sportify_API
Learn more on the Spotify documentation.