Friday 6 August 2021

How to retrieve a random YouTube video from a playlist with Power Automate

04:10 Posted by Benitez Here , , , , No comments

This is something fun that I had originally planned to do for the MVP Advent Calendar last year by the wonderful Megan V Walker but it didn't go ahead for good reasons. Months later I decided to do this as a WTF episode to share a way of how to motivate your peers/colleagues using the awesomeness of YouTube and Microsoft Teams with Power Automate.

The idea

Since most organisations have their workforce in a hybrid or 100% working from home placement, teams don't have much engagement with each other in-person anymore. There's also been a factor of being isolated indoors which reduced what we regarded as everyday activities such as going to evening classes for learning or to the gym or catching up with friends over a bite to eat.

I wanted to come up with a way of motivating teams to reignite their mind set. One thing that I thought of was sharing a random video from a YouTube playlist with a channel in Microsoft Teams. This can be sharing 
  • something that's related to a team's professional development such as videos from the official Microsoft Power Platform YouTube channel
  • or something that's not related to work such as at home exercises, cooking videos to try since people would be isolating indoors
A random YouTube video from a playlist can be shared using a schedule of choice. Examples are
  • Daily at 12pm
  • Every Friday at 4pm for weekend motivation
  • Once a month on Tuesdays
With Power Automate cloud flows you can motivate the team using an automated schedule with a random YouTube video from a playlist.

And that is how and why this episode came to life 😊 Keep reading if you're interested and want to try this out within your organisation.

The use case

I want to share a random video from a playlist on a weekly basis to help educate or motivate my team so that they can learn or feel motivated

Prerequisites

OK firstly, I want to make it clear that I am not a developer and the following may sound scary because it might involve something that you have never done before as a non-developer. It is not scary and you can do it too!

YouTube is part of the Google family and to interact with the Google Cloud Platform, you need a Google account - eg. what you use for Gmail. 

Once you're signed into the Google Cloud Platform you need to create a Project.

Once your project is created you will need to create an API Key to use with the YouTube API. This API Key is what will be used in a cloud flow in Power Automate. The YouTube Data API v3 is the API that will be used from the Google Cloud Platform.

Disclaimer

By having a Project with API Keys in the Google Cloud Platform and calling the YouTube API, there are quota usages involved. 

Understanding the YouTube API Request

The API request I'm using in my automation is PlaylistItems using the GET method. The API Key created from the project is used for the authentication. In the GET method there are three parameters which is explained in the YouTube API documentation
  • Required
  • Filter
  • Optional
For the required parameter of part I'm referencing snippet which provides properties that I'll be using downstream in the cloud flow.

For the filter parameter I'm referencing playlistId as I'm only interested in retrieving a random video from a single playlist. I have not tried this with multiple playlists by referencing id for the filter parameter.

For the optional parameter maxResults is referenced as there can only be a maximum of 50 items (videos) returned from a playlist. This means if there are more than 50 videos in a playlist, another request is performed to retrieve the next lot of items.

This is where the pageToken parameter comes in handy as it will be used in the next API request to retrieve the next lot of items.

The logic applied

The cloud flow is going to use the HTTP request action to call the YouTube API and loop through each page and 
  • retrieve a random video and append to an array
  • use the nextPageToken value returned in the response to process the next page
From the array created of random videos from each page, a random video will be selected.

The selected random video is then shared to a Microsoft Teams channel.

Example for your learning

The following is a diagram I shared in my WTF episode.


Let's say there are a total of 180 videos in a playlist. There will be a total of 4 pages to loop through. This means 4 random videos will be selected from each page and then finally a random video will be selected from the 4 random videos (the array) which will be shared to a Microsoft Teams channel.

What the playlistItems API response looks like

The following is what the API returns and the property values will be using are highlighted in red.
  • nextPageToken
  • url of the VideoThumbnail
  • videoId

The playlist I'm retrieving a random video from

I'm a fan of at home workouts and one channel I do follow that has awesome workout videos for all levels is Mr and Mrs Muscle. Their video formats are really great and they also provide modified movements to help viewers out. They have a large variety off themes such as
  • Knee friendly workouts
  • No equipment HIIT workouts
  • Chair only home workouts
The playlist I'm using in this WTF episode is their Full Body HIIT Workouts.

Let's Automate

This is what my cloud flow in Power Automate looks like.

The trigger

For learning purposes the trigger is Manually trigger a flow. In real life the Schedule trigger would be used where you define the frequency of when the cloud flow should be triggered.

Initialize nextPageToken variable

Since YouTube allows a maximum of 50 videos to be retrieve from a playlist, an Initialize variable action is used to reference the nextPageToken in response returned by the YouTube API. 

This nextPageToken value will be used for the HTTP request in order to retrieve the next page in the playlist so that the array of random videos can be created.

Initialize random videos array

This is another Initialize variable action to that will be the array of random videos from each page of a YouTube playlist.

Do until

This is the first time I believe I'm using this action in a WTF episode. It's an action that performs the criteria defined until it has been met. In this use case the criteria is to process the actions inside the Do Until action, until the nextPageToken is blank - no longer exists. When there is no nextPageToken in the response it means that there's no page left to retrieve videos in the playlist.

HTTP request

  • The Method is GET
  • The URI is the YouTube API request
  • The content-Type in the header is the usual application/JSON
  • For the values in Queries,
    • pageToken is the optional parameter and the variable is referenced
    • part is the required parameter where snippet is referenced
    • maxResults is the optional parameter where 50 is the maximum value of items returned
    • playlistId is the ID of the YouTube playlist id which can be found in the URL of the YouTube
  • key is the API Key created in the project within the Google Cloud Platform

Set variable - nextPageToken continuous

Using a Set variable action, the nextPageToken value returned from the HTTP request is referenced by the Initialize nextPageToken variable. This is so that the Do until action can continue to perform the HTTP request action that calls the YouTube API in order to retrieve the next page of videos.


Append array - secondary videos

Using an Append array action, a random video (row) in the array of the page retrieved will be selected. A reminder that a maximum of 50 videos will be returned per page of a playlist.

The expression is
body('HTTP_request')?['items'][rand(0, length(body('HTTP_request')?['items']))]


Array value - EXPLANATION PURPOSES ONLY

This is a Compose action that I used in the WTF episode to show you the array of the random videos selected from each page returned by the API response. In the WTF episode I showed how there were only two videos selected as there were only two pages.

Random video selected

This is a Compose action to select a random video from the Random selected videos array (from the Initialize random videos array action).

The expression is
variables('Random selected videos')[rand(0, length(variables('Random selected videos')))]

Post your own adaptive card as the Flow bot to a channel

To share the random YouTube video with colleagues/peers, I am using the the Post your own adaptive card as the Flow bot to a channel action. This will post an adaptive card to a channel in Microsoft Teams. I modified the Activity update sample for adaptive cards 

There is a Product video sample for adaptive cards but at the time of writing this WTF blog post, it is not supported with Microsoft Teams.

I kept the adaptive card simple by having
  • some text
  • an image which is the thumbnail of the YouTube video
  • an action which launches a browser (web or mobile) based on the embedded URL when clciked. This will be the YouTube video URL

This was all built in the adaptive cards designer site and then I copied the card payload into the action in my Power Automate cloud flow.


For the expression that is used for the image of the adapative card, it is
outputs('Random_video_selected')?['snippet']

For the expression that is used for the action that launches the embedded URL in a browser, it is
outputs('Random_video_selected')?['snippet']['resourceId']['videoId']

Cloud flow in action

When the cloud flow runs on the scheduled time, it will call the YouTube API to retrieve the available pages from the defined YouTube playlist and will select a random video which will be shared to a channel in Microsoft Teams for learning or motivation 😄

Summary

For some daily or weekly motivation why not use Power Automate with cloud flows to share a random YouTube video to help spark some motivation in the team? It can be a workout video that you can do from home, a cooking video for "Cook off Fridays" or an educational video from the Power Platform YouTube channel. Give it a go and when it works, give me a shout on Twitter 🙂