Youtube Data API | Set-1

03 Dec, 2018
Google provides a large set of API’s for the developer to choose from. Each and every service provided by Google has an associated API. Being on of them, Youtube Data API is very simple to use provides features like –
Search for videos
Handle videos like retrieve information about a video, insert a video, delete a video etc.
Handle Subscriptions like lists all the subscriptions, insert or delete a subscription.
Retrieve information about comments like replies to a specific comment identified by a parentId etc.
In this article, we will discuss Google Youtube API. Please follow the steps below to enable the API and start using it.
Create New Project, Enable API and Create Credentials: In this step we will create a project and will enable the API.Go to 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 a account first and then use the details to Sign In on the Google Developers Homepage.Now navigate to the Developer Dashboard and create a new Project.Click on Enable API option.In the search field, search for Youtube Data API and select the Youtube Data API option that comes in the drop down list.You will be redirected to a screen that says information about the Youtube Data API, along with two options : ENABLE and TRY APIClick on ENABLE option to get started with the API.In the sidebar under APIs & Services, select Credentials.In the Credentials tab, select the Create credentials drop-down list, and choose API key.There are two types of Credentials: API Key and OAuth. OAuth provides you with Client Id and a Secret Key in the form of a .json file. OAuth is generally used where authorization is required like in the case of retrieving liked videos of a user. So for the rest cases where authorization is not required like searching for the videos using a keyword or for searching for the related videos etc we will be using API Key.Installation: Google API client for python can be installed using simple pip command:pip install --upgrade google-api-python-client
Create New Project, Enable API and Create Credentials: In this step we will create a project and will enable the API.Go to 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 a account first and then use the details to Sign In on the Google Developers Homepage.Now navigate to the Developer Dashboard and create a new Project.Click on Enable API option.In the search field, search for Youtube Data API and select the Youtube Data API option that comes in the drop down list.You will be redirected to a screen that says information about the Youtube Data API, along with two options : ENABLE and TRY APIClick on ENABLE option to get started with the API.In the sidebar under APIs & Services, select Credentials.In the Credentials tab, select the Create credentials drop-down list, and choose API key.There are two types of Credentials: API Key and OAuth. OAuth provides you with Client Id and a Secret Key in the form of a .json file. OAuth is generally used where authorization is required like in the case of retrieving liked videos of a user. So for the rest cases where authorization is not required like searching for the videos using a keyword or for searching for the related videos etc we will be using API Key.
Go to 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 a account first and then use the details to Sign In on the Google Developers Homepage.
Now navigate to the Developer Dashboard and create a new Project.
Click on Enable API option.
In the search field, search for Youtube Data API and select the Youtube Data API option that comes in the drop down list.
You will be redirected to a screen that says information about the Youtube Data API, along with two options : ENABLE and TRY API
Click on ENABLE option to get started with the API.
In the sidebar under APIs & Services, select Credentials.
In the Credentials tab, select the Create credentials drop-down list, and choose API key.There are two types of Credentials: API Key and OAuth. OAuth provides you with Client Id and a Secret Key in the form of a .json file. OAuth is generally used where authorization is required like in the case of retrieving liked videos of a user. So for the rest cases where authorization is not required like searching for the videos using a keyword or for searching for the related videos etc we will be using API Key.
Installation: Google API client for python can be installed using simple pip command:pip install --upgrade google-api-python-client
pip install --upgrade google-api-python-client
Let’s start with the Search function.
There are five variants of search method – Search by Keyword, Search by Location, Search Live Events, Search Related Videos and Search My videos. Let’s cover first two types of search method.
Search by Keyword function: This will return the list of videos, channels and playlists according to the search query. By default, if the type parameter is skipped, method will display videos, channels and playlists. Default value of max results parameter is 5. This example retrieves results associated with the keyword “Geeksforgeeks”.
from apiclient.discovery import build   # Arguments that need to passed to the build functionDEVELOPER_KEY = "your_API_Key" YOUTUBE_API_SERVICE_NAME = "youtube"YOUTUBE_API_VERSION = "v3"   # creating Youtube Resource Objectyoutube_object = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,                                        developerKey = DEVELOPER_KEY)      def youtube_search_keyword(query, max_results):           # calling the search.list method to    # retrieve youtube search results    search_keyword = youtube_object.search().list(q = query, part = "id, snippet",                                               maxResults = max_results).execute()           # extracting the results from search response    results = search_keyword.get("items", [])       # empty list to store video,     # channel, playlist metadata    videos = []    playlists = []    channels = []           # extracting required info from each result object    for result in results:        # video result object        if result['id']['kind'] == "youtube# video":            videos.append("% s (% s) (% s) (% s)" % (result["snippet"]["title"],                            result["id"]["videoId"], result['snippet']['description'],                            result['snippet']['thumbnails']['default']['url']))          # playlist result object        elif result['id']['kind'] == "youtube# playlist":            playlists.append("% s (% s) (% s) (% s)" % (result["snippet"]["title"],                                 result["id"]["playlistId"],                                 result['snippet']['description'],                                 result['snippet']['thumbnails']['default']['url']))          # channel result object        elif result['id']['kind'] == "youtube# channel":            channels.append("% s (% s) (% s) (% s)" % (result["snippet"]["title"],                                   result["id"]["channelId"],                                    result['snippet']['description'],                                    result['snippet']['thumbnails']['default']['url']))               print("Videos:\n", "\n".join(videos), "\n")    print("Channels:\n", "\n".join(channels), "\n")    print("Playlists:\n", "\n".join(playlists), "\n")   if __name__ == "__main__":    youtube_search_keyword('Geeksforgeeks', max_results = 10)     
Output: Search by Location function: This example retrieves results associated with the keyword “Geeksforgeeks”. The request retrieves top 5 results within 100km (specified by the locationRadius parameter value) of the point specified by the location parameter value.
from apiclient.discovery import build   # Arguments that need to passed to the build functionDEVELOPER_KEY = "your_API_Key" YOUTUBE_API_SERVICE_NAME = "youtube"YOUTUBE_API_VERSION = "v3"   # creating Youtube Resource Objectyoutube_object = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,                                        developerKey = DEVELOPER_KEY)      def youtube_search_location(query, max_results = 5):           # calling the search.list method to retrieve youtube search results    search_location = youtube_object.search().list(q = query, type ='video',                                           location ='20.593683, 78.962883',                              locationRadius ='100km', part = "id, snippet",                                          maxResults = max_results).execute()           # extracting the results from search response    results = search_location.get("items", [])       # empty list to store video metadata    videos = []           # extracting required info from each result object    for result in results:          # video result object        videos.append(result["id"]["videoId"])    video_ids = ", ".join(videos)    video_response = youtube_object.videos().list(id = video_ids, part ='snippet,                                                     recordingDetails').execute()               search_videos = []    for video_result in video_response.get("items", []):        search_videos.append("% s, (% s, % s)" %(video_result["snippet"]["title"],                         video_result["recordingDetails"]["location"]["latitude"],                       video_result["recordingDetails"]["location"]["longitude"]))      print ("Videos:\n", "\n".join(search_videos), "\n")    if __name__ == "__main__":    youtube_search_location('Geeksforgeeks', max_results = 5)
Output:
Note: location parameter is a string that specifies Latitude/Longitude coordinates of a geographic location.
location parameter identifies the point at the center of the area.
locationRadius parameter specifies the maximum distance that the location associated with a video can be from that point for the video to still be included in the search results.
type argument can only be video in this search method type. In this example, we have used Latitude/ Longitude coordinates for Delhi, India.
Note: We have used only limited parameters in the above example. There are many other parameters that can be set and if not set then what default value they take can be found from Youtube Search List Documentation. Please refer to the documentation to have a full understanding of the available parameters.
References:https://developers.google.com/youtube/v3/docs/search/list
GBlog
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
How to Learn Data Science in 10 weeks?
What is Hashing | A Complete Tutorial
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe