Youtube Data API for handling videos | Set-5

Prerequisite: Youtube Data API for handling videos | Set-1, Set-2, Set-3

In this article, we will be discussing Rate a Video and Get Rating of a Video.

Examples in this article will be requiring user authorization. So, we will be first creating OAuth Credential and install additional libraries.
Follow the steps below to generate a Client Id and a Secret Key.



  1. Go to Google Google Developers Console and Click on Sign In in the upper rightmost corner of the page. Sign In using the credentials of the valid Google Account. If you don’t have a google account, setup an account first and then use the details to Sign In on the Google Developers Homepage.
  2. Now navigate to the Developer Dashboard and create a new Project.
  3. Click on Enable API option.
  4. In the search field, search for Youtube Data API and select the Youtube Data API option that comes in the drop down list.
  5. You will be redirected to a screen that says information about the Youtube Data API, along with two options : ENABLE and TRY API.
  6. Click on ENABLE option to get started with the API.
  7. In the sidebar under APIs & 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 the Save button.
  9. In the Credentials tab, select the Create credentials drop-down list, and choose OAuth Client Id. OAuth is generally used where authorization is required like in the case of retrieving liked videos of a user.
  10. Select the application type Other, enter the name “YouTube Data API Myvideos”, and click the Create button and click OK.
  11. Click on 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 the working directory.

Install additional libraries using the pip command:

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

Code to rate a video: This example shows how to rate a video. In this example, we are rating a video with a like. You have three options to try here: like, dislike and none (means to remove the rating of either type like/ dislike from the video).

filter_none

edit
close

play_arrow

link
brightness_4
code

import argparse
import os
import re
import urllib.request
import urllib.error
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 = 'client_secret.json'
  
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 like_video(youtube):
    youtube.videos().rate(id ='ZmtLzRJh8n8',
                   rating ='like').execute()
  
# Driver Code
if __name__ == '__main__':
  
    youtube = get_authenticated_service()
      
    try:
        like_video(youtube)
    except urllib.error.HttpError as e:
        print ('An HTTP error %d occurred:\n % s'
                     %(e.resp.status, e.content))
    else:
        print ('The rating has been added')

chevron_right


Output:

When you will execute the code you will be asked for the authorization code. For getting the code you need to follow the link mentioned in the command prompt screen above the line: Enter the Authorization code.

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

From the images of my Youtube Account, you can see that there is addition to the list of like videos.

Code to getRating: This example show how to retrieve rating given by the authorized user to the list of videos in the parameter list.


filter_none

edit
close

play_arrow

link
brightness_4
code

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 a file that
# contains the OAuth 2.0 information
# for this application, including its 
# client_id and client_secret.
CLIENT_SECRETS_FILE = "client_secret.json"
  
# This OAuth 2.0 access scope allows for
# full read/write access to the authenticated
# user's account and requires requests to 
# use an SSL connection.
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)
  
# Remove keyword arguments that are not set
def remove_empty_kwargs(**kwargs):
    good_kwargs = {}
      
    if kwargs is not None:
        for key, value in kwargs.items():
        if value:
            good_kwargs[key] = value
    return good_kwargs
  
def videos_get_rating(client, **kwargs):
    # See full sample for function
    kwargs = remove_empty_kwargs(**kwargs)
      
    response = client.videos().getRating(
                        **kwargs).execute()
  
    return print_response(response)
  
if __name__ == '__main__':
    # When running locally, disable OAuthlib's
    # HTTPs verification. When running in 
    # production * do not * leave this option enabled.
    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
    client = get_authenticated_service()
      
    videos_get_rating(client,
        id ='UPmVTPyE5DM, c0KYU2j0TM4, eIho2S0ZahI',
        onBehalfOfContentOwner ='')
   

chevron_right


Output:

When you will execute the code you will be asked for the authorization code. For getting the code you need to follow the link mentioned in the command prompt screen above the line: Enter the Authorization code.

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

As you can see from the output one of the video is rated as like and other two videos have no rating.

References:

  1. https://developers.google.com/youtube/v3/docs/videos/rate
  2. https://developers.google.com/youtube/v3/docs/videos/getRating


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.