The refresh token allows you to access the Spotify API on behalf of the authenticated user without the need for manual authorization.
Before proceeding, make sure you have the following prerequisites:
- Python 3 installed on your machine.
- You don't need premium account to get refresh token.
-
Go to the Spotify Developer Dashboard and log in with your Spotify account credentials.
-
Click on the Create an App button and fill in the necessary details, such as the app name and app description.
-
Once your app is created, you will be redirected to the app dashboard. Note down the Client ID and Client Secret. You will need these later.
-
In the app dashboard, click on Edit Settings and add a redirect URI. Set it to https://localhost:8888 for this example.
-
Save the changes.
Setting up a virtual environment helps isolate the project dependencies and avoids conflicts with other Python projects. Follow these steps to set up a Python virtual environment:
Open a command prompt or terminal.
-
Navigate to the directory where you want to create the virtual environment.
-
Run the following command to create a new virtual environment named "spotify-env":
- For Windows:
python -m venv spotify-env
- For macOS/Linux:
python3 -m venv spotify-env
- Activate the virtual environment:
For Windows:
.\spotify-env\Scripts\activate
For macOS/Linux:
source spotify-env/bin/activate
You will see the virtual environment name (e.g., "spotify-env") in your command prompt or terminal.
- Clone this repository to your local machine.
git clone https://github.com/arnvgh/get-spotify-refresh-token
- Navigate to the project directory.
cd get-spotify-refresh-token
- Install the required dependencies.
pip install -r requirements.txt
- Create a .env file in the project directory. (either manually or by below command)
touch .env
- Open the .env file and add the following lines:
SPOTIFY_CLIENT_ID=your_client_id
SPOTIFY_CLIENT_SECRET=your_client_secret
SPOTIFY_REDIRECT_URI=https://localhost:8888
(Make sure that you have port :8888
avaiable in your system.)
- Replace the values of
SPOTIPY_CLIENT_ID
andSPOTIPY_CLIENT_SECRET
with the values you noted down in Step 1.
- Run the script.
- For Windows:
python main.py
- For macOS/Linux:
python3 main.py
-
You will be redirected to a Spotify authorization page. Click on Agree to authorize the app.
-
You will be redirected to a page that says "You can close this window now". Close the window.
-
You will see a new file named
.cache
in the project directory. This file contains your refresh token (also an access token with expiration time).
Congratulations! You have successfully stored your Spotify refresh token using Spotipy. Now you can use this token to access the Spotify API on behalf of the authenticated user.
Please note that it's important to keep the .env file containing your credentials and the .cache file secure and not share them with others.
If you have any further questions, feel free to ask !