Want to code faster? Our Python Code Generator lets you create Python scripts with just a few clicks. Try it now!
YouTube is no doubt the biggest video-sharing website on the Internet. It is one of the main sources of education, entertainment, advertisement, and many more fields. Since it's a data-rich website, accessing its API will enable you to get almost all of the YouTube data.
In this tutorial, we'll cover how to get YouTube video details and statistics, search by keyword, get YouTube channel information, and extract comments from both videos and channels, using YouTube API with Python.
Here is the table of contents:
To enable YouTube Data API, you should follow below steps:
credentials.json
:Note: If this is the first time you use Google APIs, you may need to simply create an OAuth Consent screen and add your email as a testing user.
Now that you have set up YouTube API, get your credentials.json
in the current directory of your notebook/Python file, and let's get started.
First, install required libraries:
Now let's import the necessary modules we gonna need:
SCOPES
is a list of scopes of using YouTube API; we're using this one to view all YouTube data without any problems.
Now let's make the function that authenticates with YouTube API:
youtube_authenticate()
looks for the credentials.json
file that we downloaded earlier, and try to authenticate using that file, this will open your default browser the first time you run it, so you accept the permissions. After that, it'll save a new file token.pickle
that contains the authorized credentials.
It should look familiar if you used a Google API before, such as Gmail API, Google Drive API, or something else. The prompt in your default browser is to accept permissions required for the app. If you see a window that indicates the app isn't verified, you may just want to head to Advanced and click on your App name.
Now that you have everything set up, let's begin with extracting YouTube video details, such as title, description, upload time, and even statistics such as view count, and like count.
The following function will help us extract the video ID (that we'll need in the API) from a video URL:
We simply used the urllib.parse module to get the video ID from a URL.
The below function gets a YouTube service object (returned from youtube_authenticate()
function), as well as any keyword argument accepted by the API, and returns the API response for a specific video:
Notice we specified part of snippet
, contentDetails
and statistics
, as these are the most important parts of the response in the API.
We also pass kwargs
to the API directly. Next, let's define a function that takes a response returned from the above get_video_details()
function, and prints the most useful information from a video:
Finally, let's use these functions to extract information from a demo video:
We first get the video ID from the URL, and then we get the response from the API call and finally print the data. Here is the output:
You see, we used the id
parameter to get the details of a specific video, you can also set multiple video IDs separated by commas, so you make a single API call to get details about multiple videos, check the documentation for more detailed information.
Searching using YouTube API is straightforward; we simply pass q
parameter for query, the same query we use in the YouTube search bar:
This time we care about the snippet, and we use search()
instead of videos()
like in the previously defined get_video_details()
function.
Let's, for example, search for "python"
and limit the results to only 2:
We set maxResults
to 2 so we retrieve the first two items, here is a part of the output:
You can also specify the order
parameter in search()
function to order search results, which can be 'date'
, 'rating'
, 'viewCount'
, 'relevance'
(default), 'title'
, and 'videoCount'
.
Another useful parameter is the type
, which can be 'channel'
, 'playlist'
or 'video'
, default is all of them.
Please check this page for more information about the search().list()
method.
This section will take a channel URL and extract channel information using YouTube API.
First, we need helper functions to parse the channel URL. The below functions will help us to do that:
Now we can parse the channel URL. Let's define our functions to call the YouTube API:
We'll be using get_channel_videos()
to get the videos of a specific channel, and get_channel_details()
will allow us to extract information about a specific youtube channel.
Now that we have everything, let's make a concrete example:
We first get the channel ID from the URL, and then we make an API call to get channel details and print them.
After that, we specify the number of pages of videos we want to extract. The default is ten videos per page, and we can also change that by passing the maxResults
parameter.
We iterate on each video and make an API call to get various information about the video, and we use our predefined print_video_infos()
to print the video information.
Here is a part of the output:
You can get other information; you can print the response
dictionary for further information or check the documentation for this endpoint.
YouTube API allows us to extract comments; this is useful if you want to get comments for your text classification project or something similar.
The below function takes care of making an API call to commentThreads()
:
The below code extracts comments from a YouTube video:
You can also change url
variable to be a YouTube channel URL so that it will pass allThreadsRelatedToChannelId
instead of videoId
as a parameter to commentThreads()
API.
We're extracting two comments per page and two pages, so four comments in total. Here is the output:
We're extracting the comment itself, the number of likes, and the last updated date; you can explore the response dictionary to get various other useful information.
You're free to edit the parameters we passed, such as increasing the maxResults
, or changing the order
. Please check the page for this API endpoint.
YouTube Data API provides a lot more than what we covered here. If you have a YouTube channel, you can upload, update and delete videos, and much more.
I invite you to explore more in the YouTube API documentation for advanced search techniques, getting playlist details, members, and much more.
If you want to extract YouTube data but don't want to use the API, then we also have a tutorial on getting YouTube data with web scraping (more like an unofficial way to do it).
Below are some of the Google API tutorials:
Happy Coding ♥
Let our Code Converter simplify your multi-language projects. It's like having a coding translator at your fingertips. Don't miss out!
View Full Code Analyze My Code
Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!