Getting YouTube Analytics Data Into Power BI Using Python Script

YouTube is making people go popular & itself is going popular these days. YouTube is second largest search engine in the world.

In this blog, we will be using YouTube API to get YouTube Analytics data into Power BI using a Python script.

Following are the things you can extract from YouTube API,

  1. Channel’s Statistics
  2. Number of videos
  3. Total Number of Subscribers
  4. Snippet
  5. Content Details etc.

In this blog we are using, Visual Studio Code, Python 3.7 & Microsoft Power BI.

Now, let’s start from the scratch,

Before going to first step, lets setup our machine and environment,

We have to install Google API Client & pandas package  by writing below command in Window’s Command Prompt,

pip install google-api-python-client

pip install pandas

 Now we are ready to start,

Step 1: Importing Packages

Import packages using code below:

from googleapiclient.discovery import build

import pandas as pd

We are using Build Method from Google API Client package & will create dataframe using Pandas package.


Step 2: Creating Objects

We are creating objects, to call data from YouTube Analytics API. For creating object, you will need API Key and your Channel ID.

You can get API Key from here.

For getting the Channel ID just go the any YouTube channel and check the URL. You will find the Channel ID:

Example: https://www.youtube.com/channel/UCr2dD3s19aldh4qjuTRHCiG

For above YouTube URL, the Channel ID is UCr2dD3s19aldh4qjuTRHCiG

Step 3: Code to Call Data from API

#Importing required packages

from googleapiclient.discovery import build

import pandas as pd

from datetime import datetime


#Creating Objects

#Creating Objects

youTubeApiKey=’Your API Key’

youtube= build(“youtube”,”v3″,developerKey=youTubeApiKey) #We’re using YouTube Data API v3

channelId = ‘Your Channel ID’

#Calling Data from API

statdata=youtube.channels().list(part=”statistics”,id=channelId).execute()

stats=statdata[“items”][0][“statistics”]

stats

 

Output:

#Getting Snippet Data

Just like the Statistics, Snippet also contain various important information.

snippetdata=youtube.channels().list(part=”snippet”,id=channelId).execute()

snippetdata

Output:

#Getting Details of all videos

contentdata=youtube.channels().list(id=channelId,part=’contentDetails’).

execute()

playlist_id = contentdata[‘items’][0][‘contentDetails’][‘relatedPlaylists’]

[‘uploads’]

videos = [ ]

next_page_token = None

while 1:

res = youtube.playlistItems().list(playlistId=playlist_id,

part=’snippet’,

maxResults=50,

pageToken=next_page_token).execute()

videos += res[“items”]

next_page_token = res.get(‘nextPageToken’)

if next_page_token is None:

break

print(videos)

Output:


#Getting the statistics of each video

stats = []

for i in range(0, len(video_ids), 40):

res = (youtube).videos().list(id=”,”.join(video_ids[i:i+40]),part=”statistics”).execute()

stats += res[“items”]

print(stats)

 

Output:

#Collecting All Information in a List & creating a dataframe

title=[ ]

liked=[ ]

disliked=[ ]

views=[ ]

url=[ ]

comment=[ ]

for i in range(len(videos)):

title.append((videos[i])[‘snippet’][‘title’])

url.append(“https://www.youtube.com/watch?v=”+(videos[i])[‘snippet’][‘resourceId’][‘videoId’])

liked.append(int((stats[i])[‘statistics’][‘likeCount’]))

disliked.append(int((stats[i])[‘statistics’][‘dislikeCount’]))

views.append(int((stats[i])[‘statistics’][‘viewCount’]))

comment.append(int((stats[i])[‘statistics’][‘commentCount’]))

data={“title”:title,”url”:url,”liked”:liked,”disliked”:disliked,”views”:views,”comment”:comment}

df=pd.DataFrame(data)

df

 

Output:


Step 4: Running Python Script in Microsoft Power BI

Now we’ve the script, which will give us the required data. Now just copy the script.

Now, go to Power BI Desktop & click on “Get Data” and select “Python Script”. Paste the copied script in the prompted box and click Ok.

It takes some time to execute the script. After it get executed you will get,

Now, expand the Value column. You will get the final result.

This is all about getting data from YouTube Analytics data in Power BI. I hope it gives the information needed.

Addend Analytics is a Microsoft Power BI-partner based in Mumbai, India. Apart from being authorized for Power BI implementations, Addend has successfully executed Power BI projects for 100+ clients across sectors like Financial Services, Banking, Insurance, Retail, Sales, Manufacturing, Real estate, Logistics, and Healthcare in countries like the US, Europe, Switzerland, and Australia. Get a free consultation now by emailing us at kamal.sharma@addendanalytics.com or Contact us.

Gaurav Lakhotia
Data Analyst
Addend Analytics