AdamRusted.me

Spotify Track of the Day in Power Automate

Posted 3 months ago to Power Automate (7 min read)
Photo by Junior Teixeira @ PexelsSemi-opened Laptop Computer Turned-on on Table

Power Automate is an incredibly powerful tool, not only for businesses - but also for personal use! This is the first in a series of posts about fun Power Automate flows I create either for my own use, or as internal tools for my company.

The first flow I'm going to talk you through is my 'Track of the Day' generator using Spotify's API, a Custom Connector, and a Recurring Flow.

Custom Connector

Spotify Application

To start with - we need to gain access to the Spotify API. This is what we're going to use to select a random track. Head to the Spotify Developer Portal and create an Application. Give it a sensible name and description.

From the next page we'll need the Client ID and Client Secret. Make a note of these, as we'll need them shortly.

Spotify API

Next on the agenda is to head to the Spotify API docs to look at how we'll build up our API URL. For this bot - we'll use the search endpoint with a few parameters. Add or remove as many as you like, but you should end up with a URL like the below.

https://api.spotify.com/v1/search?type=track&q=T&offset=5&limit=1&market=GB

I only want to search for tracks - and although eventually I'll provide a random query and offset - for now let's set them to T and 5 respectively. I'm also only interested in music I can listen to here in the UK - hence the addition of market to the end of the query.

Now we've got that endpoint URL - we can move on to…

Creating the Custom Connector

To make the Spotify API available within Power Apps - you can use a Custom Connector. This basically functions as any other Trigger/Step would within a flow - but lets you define which API is being polled.

Within the make.powerapps.com UI - head to Dataverse -> Custom Connectors and create a new connector from scratch.

Creating a custom connector within make.powerapps.com

Now we need the host and the base URL. While we could be super specific at this point - I'm going to leave the options pretty open, as I might want to do other things with this connector in the future! Set the host to api.spotify.com and the base URL to /v1 Hit next to move on to Security.

When asked which Authentication Type you'd like to use - pick OAuth 2.0. You can then select Spotify from the dropdown list of providers. Remember the Client ID and Client Secret we saved earlier? Now is the time to enter those into their corresponding fields. Once you've entered those - head to the top right of the page and hit Create Connector. Once it's saved - you'll be given a Redirect URL. Copy this and head back to Spotify.

Back on the Spotify Developer Dashboard, you can hit Edit Settings for your application, and paste the URL into a new Redirect URI. Scroll down and hit save.

Connector Definition

Now you've successfully linked the Spotify API and your Custom Connector, it's time to do some fun stuff with it! Back in the Custom Connector - head to the Definition tab.

I found this page quite daunting when I first started looking into Custom Connectors, but the only bit we need to worry about is Actions. Let's create one now!

General tab when creating a custom connector

Once you've got the basic information above set up, head to Request and import one from a sample. We've already built the URL with query parameters above - so set the method to GET and paste the URL in. Hitting Import will generate the request. You can go into each query parameter in turn here and give it a description and summary if you plan on sharing this connector - but let's leave them be for now.

There's also a Default Response that we can edit which also allows an import from a sample! You can call the endpoint yourself using a tool like Postman - or use my result below…

    "tracks": {
        "href": "https://api.spotify.com/v1/search?query=T&type=track&market=GB&offset=5&limit=1",
        "items": [
            {
                "album": {
                    "album_type": "album",
                    "artists": [
                        {
                            "external_urls": {
                                "spotify": "https://open.spotify.com/artist/3luonLzvSOxdU8ytCaEIK8"
                            },
                            "href": "https://api.spotify.com/v1/artists/3luonLzvSOxdU8ytCaEIK8",
                            "id": "3luonLzvSOxdU8ytCaEIK8",
                            "name": "IC3PEAK",
                            "type": "artist",
                            "uri": "spotify:artist:3luonLzvSOxdU8ytCaEIK8"
                        }
                    ],
                    "external_urls": {
                        "spotify": "https://open.spotify.com/album/2Ji9U33Ljqdm4RdlBKXteF"
                    },
                    "href": "https://api.spotify.com/v1/albums/2Ji9U33Ljqdm4RdlBKXteF",
                    "id": "2Ji9U33Ljqdm4RdlBKXteF",
                    "images": [
                        {
                            "height": 640,
                            "url": "https://i.scdn.co/image/ab67616d0000b2739ec81d99271804ba71e6300e",
                            "width": 640
                        },
                        {
                            "height": 300,
                            "url": "https://i.scdn.co/image/ab67616d00001e029ec81d99271804ba71e6300e",
                            "width": 300
                        },
                        {
                            "height": 64,
                            "url": "https://i.scdn.co/image/ab67616d000048519ec81d99271804ba71e6300e",
                            "width": 64
                        }
                    ],
                    "name": "До Свидания",
                    "release_date": "2020-04-24",
                    "release_date_precision": "day",
                    "total_tracks": 12,
                    "type": "album",
                    "uri": "spotify:album:2Ji9U33Ljqdm4RdlBKXteF"
                },
                "artists": [
                    {
                        "external_urls": {
                            "spotify": "https://open.spotify.com/artist/3luonLzvSOxdU8ytCaEIK8"
                        },
                        "href": "https://api.spotify.com/v1/artists/3luonLzvSOxdU8ytCaEIK8",
                        "id": "3luonLzvSOxdU8ytCaEIK8",
                        "name": "IC3PEAK",
                        "type": "artist",
                        "uri": "spotify:artist:3luonLzvSOxdU8ytCaEIK8"
                    },
                    {
                        "external_urls": {
                            "spotify": "https://open.spotify.com/artist/4G1zP5i0r57g1c1CxrPhfM"
                        },
                        "href": "https://api.spotify.com/v1/artists/4G1zP5i0r57g1c1CxrPhfM",
                        "id": "4G1zP5i0r57g1c1CxrPhfM",
                        "name": "ZillaKami",
                        "type": "artist",
                        "uri": "spotify:artist:4G1zP5i0r57g1c1CxrPhfM"
                    }
                ],
                "disc_number": 1,
                "duration_ms": 184000,
                "explicit": false,
                "external_ids": {
                    "isrc": "QM6MZ2019111"
                },
                "external_urls": {
                    "spotify": "https://open.spotify.com/track/4A0YuzcYuEEP8A3oEZTddL"
                },
                "href": "https://api.spotify.com/v1/tracks/4A0YuzcYuEEP8A3oEZTddL",
                "id": "4A0YuzcYuEEP8A3oEZTddL",
                "is_local": false,
                "is_playable": true,
                "name": "TRRST",
                "popularity": 66,
                "preview_url": "https://p.scdn.co/mp3-preview/b7566fbd093279b80b7dd4b54a9bc98e6cf5326c?cid=936141d3c27142c2bb4a82af14c5a9d3",
                "track_number": 9,
                "type": "track",
                "uri": "spotify:track:4A0YuzcYuEEP8A3oEZTddL"
            }
        ],
        "limit": 1,
        "next": "https://api.spotify.com/v1/search?query=T&type=track&market=GB&offset=6&limit=1",
        "offset": 5,
        "previous": "https://api.spotify.com/v1/search?query=T&type=track&market=GB&offset=4&limit=1",
        "total": 10180
    }
}

Again, this will generate a load of fields under the 'Response' which you could give titles to represent them better. Once this is done, hit Update Connector and head to the Test tab - and create a new connection. This will request access to your Spotify account - but we gave the application no scope, so it won't be able to read any of your personal data!

When your connection is created, navigate back to the Custom Connector's test tab - and fill out the information against the 'SpotifySearch' action. If the test succeeds - congratulations! You've just created a Custom Connector calling an external API.

Next up, let's build a flow to use that Connector!

The Flow

Now we've got the Custom Connector up and running - let's head back to make.powerapps.com and create a new Automated Flow from scratch!

For my trigger, I have a Recurrence set up as below. It will trigger every week day at 8:30am for my time - but feel free to tweak to suit your scenario!

Screenshot from within Power Automate

I then initialize two variables - one is just a string of every letter in the alphabet, and another which generates a random number between 1 and the length of your first variable - and then subtract 1 so we can correctly get the array index of the letter (see my syntax below).

sub(rand(1,length(variables('Alphabet'))),1)

You can then use a Substring operation along with the Alphabet and Index variables like the below screenshot to fetch a random letter!

Example of a substring PowerFX within Power Automate

Now we've got our random letter, you can either generate a random number, or (as I'll do here) use a static number for your 'offset'.

It's time to bring in our Custom Connector! Add a new step, head to the Custom tab and bring in your Search Spotify action. Fill out the fields as below - or mix it up for your flow!

Using a custom connector within Power Automate

For my flow, I'm only really interested in the Artist, Song Title, and the URL to the song - but the Spotify action returned a whole bunch of stuff! I've created three new string variables to pull that information using expressions. You can navigate around the JSON response from the server this way - and it's quite handy to pick specific items as opposed to having masses of data available.

Artist Name

outputs('Search_Spotify')?['body']?['tracks']?['items'][0]?['artists'][0]?['name']

Song Name

outputs('Search_Spotify')?['body']?['tracks']?['items'][0]?['name']

outputs('Search_Spotify')?['body']?['tracks']?['items'][0]?['external_urls']?['spotify']

All that is left to do then is share your track of the day! In this example, I've opted for a Teams message directly to me - but you could post it into a channel that is shared with other members of your team, or even style it as an Adaptive Card (as I did with our company one)!

Plain Text generated by this flow Result of flow styled as an adaptive card