Working with the Spotify API in Powershell

So today i was looking for something to play around with in Powershell and remembered a Reddit Post which listed things that people automated with Powershell. One of the redditors had the great idea to automate generating playlists in Spotify for Artists of his choosing. So in this post i will look into getting data from the Spotify API.

First i had to setup credentials to be able to authenticate to the API and actually send requests, for this i had to create an App in the Spotify Developer Dashboard. There is a neat Getting Started guide in the documentation which helped me to get this done with a few clicks. Once this was done, i added the ClientID and ClientSecret to my SecretsVault to be able to access them in my Script/Module easily. Next i had to get an access token that i can include with my requests, this can be done like this:

PowerShell
Function Get-SpotifyPSAccessToken {
    param (
        [Parameter(Mandatory = $true)]
        [string]$ClientID,
        [Parameter(Mandatory = $true)]
        [securestring]$ClientSecret
    )
    $body = @{ 
        'grant_type' = 'client_credentials'
    }

    $credential = New-Object System.Management.Automation.PSCredential ($ClientID, $ClientSecret)
    $token = Invoke-RestMethod -Method Post -Uri 'https://accounts.spotify.com/api/token' -Body $body -ContentType 'application/x-www-form-urlencoded' -Credential $credential -Authentication Basic

    return $token
}

With the bearer token available i can actually start getting data about artists, albums, etc. from the API – so next i wrote a function to get data about artists, unfortunately for this to work we need the ID of the particular Artist. I got the ID easily from the Client looking up an artist and copying the link from the “Share” function the client provides. To make it easy for myself i created a script scoped hashtable in the module holding the token.

Function Get-SpotifyPSArtist {
    param (
        [Parameter(Mandatory = $false)]
        [string]$ArtistID = '0DbbnkFMhhDvinDYIiHhGS'
    )
    $AuthHeader = @{
        Authorization = "$($ModuleVars.Token.token_type) $($ModuleVars.Token.access_token)"
    }
    $result = Invoke-WebRequest -Method Get -Uri "https://api.spotify.com/v1/artists/$ArtistID" -Headers $AuthHeader
    return $result.Content | ConvertFrom-Json
}

And this is what i get back:

external_urls : @{spotify=https://open.spotify.com/artist/0DbbnkFMhhDvinDYIiHhGS}
followers     : @{href=; total=204711}
genres        : {swedish alternative rock, swedish garage rock}
href          : https://api.spotify.com/v1/artists/0DbbnkFMhhDvinDYIiHhGS
id            : 0DbbnkFMhhDvinDYIiHhGS
images        : {@{height=640; url=https://i.scdn.co/image/ab6761610000e5eb36181a1f1b7b9c67da2dca6e; width=640}, @{height=320; url=https://i.scdn.co/image/ab6761610000517436181a1f1b7b9c67da2dca6e; width=320}, @{height=160;     
                url=https://i.scdn.co/image/ab6761610000f17836181a1f1b7b9c67da2dca6e; width=160}}
name          : Royal Republic
popularity    : 53
type          : artist
uri           : spotify:artist:0DbbnkFMhhDvinDYIiHhGS

Cool. so next i want to be able to look for stuff so that i don’t have to get the id manually, so i looked up the search endpoint and how to use it to search for artists. I build a result object holding the name and id for the artists i found:

Function Get-SpotifyPSArtistID {
    Param(
        [Parameter(Mandatory = $true)]
        [string]$ArtistLookupValue
    )

    $authHeader = @{
        Authorization = "$($ModuleVars.Token.token_type) $($ModuleVars.Token.access_token)"
    }
    $query = [System.Web.HttpUtility]::UrlEncode("artist:$ArtistLookupValue")
    $result = Invoke-WebRequest -Method Get -Uri "https://api.spotify.com/v1/search?q=$query&type=artist" -Headers $authHeader
    $resultJson = $result.Content | ConvertFrom-Json

    $resultPsObj = @()
    $resultJson.artists.items | ForEach-Object {
        $resultPsObj += [pscustomobject]@{
            ArtistName = $_.name
            ArtistID   = $_.id
        }
    }
  
    return $resultPsObj
}

a search for the beatles gets me this result:

ArtistName                                                        ArtistID
----------                                                        --------
The Beatles                                                       3WrFJ7ztbogyGnTHbHJFl2
The New Beatles                                                   3vuYd8ifdPWL3TgjPXgfgF
The Beatles Complete On Ukulele                                   5o723EMxNulM5ydXRh7Qkk
The Beatles Piano Covers                                          2HPX6LgKluE3jv3Q6ZKVyX
The Beatless                                                      1o87i8ILTqu19oPNCsWTIo
The Silver Beatles                                                5WTOPRu5W51m3TEU4BupIR
I Hate The Beatles                                                5Pi3viYqawZx95Gan2dyC3
The Sex Beatles                                                   4e8OA3QHzatg40g3Fbe4X1
The Beatles on Piano                                              4s0XGFVyR7iLaxdxbuKygy
the beatles featuring mark pearson                                4PCfEqDs3CzWQu4l98pBIR
Barack Obama with The Beatles Complete On Ukulele Community Choir 1c4dcJh2dBjZgPDLid6Cxl
The Tape-beatles                                                  1UarLtyjvxGiRTsfFXxtnA
Better Than The Beatles                                           5qW4j3RXhL3aRytG86jLtW
The Tijunana Beatles Cover Band                                   7ksuU2G5UFiLIQNqTVhUul
The Beatles Revival Band                                          3Jee0nDYfCqDBV98n5gLhY
The Beatles Recovered Band                                        0WQ4jRVGAgNcYI3PmKfcbu
The Norwegian Beatles                                             6ea6bBvg2oAmtRJ5aHRATP
The Beatles - Piano Instrumentals                                 0mT4n79LmygTCWxdtQTA9b
The Beatles Revival Band                                          0zRgwHorAZPeYVdTW9F5OX
The Beatles Tribute Band                                          0rhGLV687CCwGfeJYXd176

Hm, i guess for this to be even better i have to improve the filtering of the results… anyway with these basics in place i can start thinking about something to actually automate for my spotify account – maybe i create myself some playlists as well, but this is a topic for another day !

Scroll to Top