Youtube Playlist Data API | Set-3

We can find the playlist id for a specific playlist that we want to work with. Well, the answer to this is there are two ways to find the Id:

  1. The first way is — use the code we discussed in the previous article to list your entire playlist. This will generate the list of playlists you have, with the ID and name mentioned.
  2. The second method is to log into your Youtube account. Navigate to the playlist you want, click on it and select the Share option. This will show you the Playlist Id.

Since this all requires user authorization, so we will create the OAuth Credential first …
Before adding the video, we`ll see how to display the contents of a playlist using code.
Follow the steps below to generate a Client ID and Secret.

  1. Go to developer console Google Google and click “ Sign in” in the upper right corner of the page … Sign in with your valid Google account credentials. If you do not have a Google account, first set up an account and then use your login details on the Google Developers homepage.
  2. Now navigate to developer toolbars and create a new project.
  3. Click on the Enable API option .
  4. In the search box, search for Youtube Data API and select the Youtube Data API option that appears in the dropdown.
  5. You will be redirected to the Youtube Data API information screen along with two options: ENABLE and TRY API .
  6. Click on the ENABLE, option to get started with the API.
  7. On the sidebar, under the API and services “select” Credentials “.
  8. At the top of the page, select the OAuth consent screen tab. Select an email address, enter a product name if not already set, and click Save.
  9. On the tab Credentials, select the Create Credentials drop-down list and select OAuth Client ID . OAuth is typically used where authorization is required, such as retrieving a user`s favorite videos.
  10. Select the application type Other, enter the name YouTube Myvideos Data API, click the Create button, and click OK “.
  11. Click the Download button to the right of the client ID to download the JSON file.
  12. Save and rename the file as client_secret.json and move it to working directory.

Install additional libraries using pip :

 pip install --upgrade google-auth google-auth-oauthlib google -auth-httplib2 

Code for displaying playlist Items:

import os

import google.oauth2.credentials

import google_auth_oauthlib.flow

from googleapiclient.discovery import build

from googleapiclient.errors import HttpError

from google_auth_oauthlib.flow import InstalledAppFlow

 
# CLIENT_SECRETS_FILE variable specifies
# the name of the file that contains
# client_id and client_secret.

CLIENT_SECRETS_FILE = "client_secret.json"

  
# This area allows full read / write
# access to the authenticated user account
# and requires requests to use an SSL connection.

SCOPES = [ ` https://www.googleapis.com/auth/youtube.force-ssl ` ]

API_SERVICE_NAME = ` youtube `

API_VERSION = ` v3`

 

def get_authenticated_service ():

  flow = InstalledAppFlow.from_client_secrets_file (

CLIENT_SECRETS_FILE, SCOPES)

 

credentials = flow.run_console ()

return build (API_SERVICE_NAME, API_VERSION, credentials = credentials)

 

def print_response (response):

print (response)

 
# Create a resource based on a list
# properties specified as key-value pairs.
# Leave the properties with empty values ​​outside
# of the inserted resource.

def build_resource (properties):

resource = {}

for p in properties :

# Given the key as & quot; snippet.title & quot ;, split

# in the & quot; snippet & quot; and & quot; title & quot;, where

# "Snippet" will be an object, and "title"

# will be a property on this object.

prop_array = p.split ( `.` )

  ref = resource

for pa in range ( 0 , len (prop_array)):

is_array = False

key = prop_array [pa]

 

# For properties that have array values ​​

# convert the type name & quot; snippet.tags [ ] & quot; in

# snippet.tags and set the flag for processing

# array value

if key [ - 2 :] = = `[]` :

key = key [ 0 : len (key) - 2 :]

is_array = True

  

if pa = = ( len (prop_array) - 1 ):

# Leave properties blank

  # from the inserted resource.

if properties [p]:

if is_array:

ref [key] = properties [p] .split ( `,` )

else :

ref [key] = properties [p]

elif key not in ref:

# For example, property & quot; snippet.title & quot ;,

# but the resource doesn`t have a snippet yet

  # object. Create a snippet object here. setting

# & quot; ref = ref [key] & quot; means next time

# through a for loop in range ...

# set a property on the resource chunk object.

ref [key] = {}

ref = ref [key]

else :

# For example, property & quot; snippet .description & quot ;,

# and the resource already has a snippet object.

ref = ref [key]

  return resource

 
# Remove keyword arguments not set

def remove_empty_kwargs ( * * kwargs):

good_kwargs = {}

if kwargs is not None :

for key, v alue in kwargs.items ():

if value:

  good_kwargs [key] = value

return good_kwargs

 

def playlist_items_list (client, * * kwargs):

  

  kwargs = remove_empty_kwargs ( * * kwa rgs)

response = client.playlistItems (). list ( * * kwargs) .execute ()

 

return print_response (response)

 

 

if __ name__ = = ` __main__` :

# If running locally, disable OAuthlib

  # HTTP check. When running in production

# * Don`t * leave this option enabled.

os.environ [ `OAUTHLIB_INSECURE_TRANSPORT` ] = `1`

client = get_authenticated_service ()

 

playlist_items_list (client,

part = `snippet, contentDetails` ,

  maxResults = 3 ,

playlistId = ` PLqAJNJC4tCYtyVYlRABk5NTDDi2sfqbqV` )

Output:
When you run the code , you will be prompted for an authorization code. To get the code, you must follow the link indicated on the command line screen above the line: Enter the authorization code.

Now follow the link and copy and paste the authorization code that you get by granting permission.

For convenience, we have set the maxResults parameter to 3. Otherwise, the totalResults counter is 32. This means that the requested playlist consists of 32 videos.

Video embed code: This example shows how to embed a video into a playlist. Id, snippet.resourceId.kind, and snippet.resourceId.videoId are required attributes.
Before adding the video to the desired playlist, we will first upload the video to the YouTube channel and then assign the video to the desired playlist using the video id. Follow the steps in

import os

import google.oauth2.credentials

import google_auth_oauthlib.flow

from googleapiclient.discovery import build

from googleapiclient.errors import HttpError

from google_auth_oauthlib.flow import InstalledAppFlow

 
# The CLIENT_SECRETS_FILE variable specifies
# the name of the file that contains
# client_id and client_secret.

CLIENT_SECRETS_FILE = " client_secret.json "

  
# This area allows full read / write access
# to the authenticated user account and requires
# asks to use an SSL connection.

SCOPES = [ ` https://www.googleapis.com/auth/youtube.force-ssl ` ]

API_SERVICE_NAME = `youtube`

API_VERSION = `v3`

  

def get_authenticated_service ():

flow = InstalledAppFlow. from_client_secrets_file (

CLIENT_SECRETS_FILE, SCOPES)

 

credentials = flow.run_console ()

  return build (API_SERVICE_NAME, API_VERSION, credentials = credentials)

 

def print_response (response):

print (response)

 
# Create resource based property list
# given as key-value pairs. Leave properties with
# empty values ​​from the inserted resource.

def build_resource (properties):

resource = {}

for p in properties:

# Given a key like & quot; snippet.title & quot;, divide by

# "fragment" and "title" where the "fragment" will be

# the object and title will be a property of this object.

prop_array = p.split ( `.` )

ref = resource

for pa in range ( 0 , len (prop_array)) :

is_array = False

key = prop_array [pa]

 

# For properties that have array values ​​

# convert name like & quot; snippet.tags [] & quot; in

# snippet.tags and set the flag for processing

# array value

if key [ - 2 :] = = `[]` :

key = key [ 0 : len (key) - 2 :]

is_array = True

  

if pa = = ( len (prop_array) - 1 ):

# Leave properties blank

  # from the inserted resource.

if properties [p]:

if is_array:

ref [key] = properties [p] .split ( `,` )

else :

ref [key] = properties [p]

elif key not in ref:

# For example, property & quot; snippet.title & quot ;,

# but the resource doesn`t have a snippet yet

  # object. Create a snippet object here.

# Setting "ref = ref [key]" means that in the next

# Time through the loop "for annuals in the range ..." we

# will set the property to

# fragment of the "object".

ref [key] = {}

ref = ref [key]

else :

# For example, the & q uot; snippet.description & quot ;,

# and the resource already has a snippet object .

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       ref = ref [key]

return resource

 
# Remove keyword arguments that are not set

def remove_empty_kwargs ( * *