In this blog post, we're going to dive into a Python script that fetches the top tracks of a specified artist from Spotify using the Spotify Web API. We'll explore each component of the script to understand how it works together to accomplish this task. Most of the help was from this youtube video from @TechWithTim.

Overview of the Script

The script performs the following key tasks:

  • Loads environment variables.
  • Authenticates with the Spotify API to obtain an access token.
  • Prompts the user to input an artist's name.
  • Searches for the artist on Spotify.
  • Retrieves and prints the top tracks of the specified artist.

Here's a breakdown of each part of the script:

Imports and Setup

The script begins with importing necessary libraries:

import requests
from dotenv import load_dotenv
import os
import base64
from requests import post, get
import json
        

requests: For making HTTP requests to the Spotify API.
dotenv: For loading environment variables from a .env file.
os: For accessing environment variables.
base64: For encoding credentials.
json: For handling JSON responses.

Main Function

The main function orchestrates the sequence of operations:

def main():
    configure()
    token = get_token()
    artist_name = get_artist()
    artist_id = search_for_artist(token, artist_name)
    songs = get_songs_by_artist(token, artist_id)

    for idx, song in enumerate(songs):
        print(f"{idx + 1}. {song['name']}")
        

1. Configuration: Loads environment variables.
2. Get Token: Fetches an access token from Spotify.
3. Get Artist: Prompts the user for an artist name.
4. Search for Artist: Finds the artist's Spotify ID.
5. Get Songs: Retrieves the artist's top tracks and prints them.

Configuration

The configure function loads environment variables:

def configure():
    load_dotenv()
        

This is how I use client_id and client_secret without entering it into my python script. It's saved into a .env file and I load the variables into this python script.

Authentication

The get_token function handles Spotify API authentication:

def get_token():
    client_id = os.getenv('client_id')
    client_secret = os.getenv('client_secret')

    auth_string = client_id + ":" + client_secret
    auth_bytes = auth_string.encode("utf-8")
    auth_base64 = str(base64.b64encode(auth_bytes), "utf-8")

    url = "https://accounts.spotify.com/api/token"
    headers = {
        "Authorization": "Basic " + auth_base64,
        "Content-Type": "application/x-www-form-urlencoded"
    }
    data = {"grant_type": "client_credentials"}
    result = post(url, headers=headers, data=data)
    json_result = json.loads(result.content)
    token = json_result["access_token"]
    return(token)
        

- Retrieves the client ID and secret from environment variables.
- Encodes these credentials in base64.
- Makes a POST request to Spotify's token endpoint to obtain an access token.

Helper Functions

Creating Authorization Header:

def get_auth_header(token):
    return {"Authorization": "Bearer " + token}
        

This function generates the authorization header needed for subsequent API requests.

User Input:

def get_artist():
    return(input("What artist do you want to know more about?"))
        

Prompts the user for an artist's name.

Spotify API Requests

Search for Artist:

def search_for_artist(token, artist_name):
    url = "https://api.spotify.com/v1/search"
    headers = get_auth_header(token)
    query = f"?q={artist_name}&type=artist&limit=1"

    query_url = url + query
    result = get(query_url, headers=headers)
    json_result = json.loads(result.content)["artists"]["items"]
    if len(json_result) == 0:
        print("No artist with this name exists")
        return None
    artist_id = json_result[0]["id"]
    return(artist_id)
        

- Constructs the search query URL.
- Makes a GET request to search for the artist.
- Parses the response to extract the artist's ID.

Get Songs by Artist:

def get_songs_by_artist(token, artist_id):
    url = f"https://api.spotify.com/v1/artists/{artist_id}/top-tracks?country=US"
    headers = get_auth_header(token)
    result = get(url, headers=headers)
    json_result = json.loads(result.content)["tracks"]
    return(json_result)
        

- Constructs the URL to fetch the artist's top tracks.
- Makes a GET request to retrieve the tracks.
- Parses the response to extract the track information.

Conclusion

This Python script demonstrates how to interact with the Spotify Web API to fetch and display an artist's top tracks. It's bare bones, but authentication and starting the process is the hard part. Everything else is just requesting and handling JSON. Happy coding.