Optimize query to YouTube API - youtube

Help optimize YouTube API requests. The entire quota is spent in 5 minutes
Get id TOP 5 trends:
https://www.googleapis.com/youtube/v3/videos?part=contentDetails&key={token}&fields=items(id)&chart=mostPopular&regionCode=RU&maxResults=5
Get channel id and channel name from video id:
https://www.googleapis.com/youtube/v3/videos?part=snippet&id={VideoId}&key={token}
Get channel name from username
https://www.googleapis.com/youtube/v3/channels?key={token}&forUsername={UserName}&part=id
Get channel image:
https://www.googleapis.com/youtube/v3/channels?id={ChannelId}&part=snippet&key={token}
Video count on channel:
​https://www.googleapis.com/youtube/v3/playlistItems?playlistId={ChannelId}&key={token}&part=snippet
Last video on channel:
https://www.googleapis.com/youtube/v3/search?key={token}&channelId={ChannelId}&part=id&order=date&maxResults=1

These are a few tips I think it might help:
Set specific fields to retrieve in each request.
The "search" request is the one who consumes more quota than the rest of your requests.
Here are your modified requests:
Get id TOP 5 trends - Demo:
https://www.googleapis.com/youtube/v3/videos?part=contentDetails&chart=mostPopular&hl=<REGION_CODE>&maxResults=5&fields=items%2Fid&key={YOUR_API_KEY}
Get channel id and channel name from video id: - demo
https://www.googleapis.com/youtube/v3/videos?part=snippet&id=<VIDEO_ID>&fields=items(snippet(channelId%2CchannelTitle))&key={YOUR_API_KEY}
Get channel name from username (also bring at the same time the channel image and its count of uploaded videos) - demo
https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics&forUsername=<CHANNEL_USERNAME>&fields=items(snippet(thumbnails%2Ctitle)%2Cstatistics%2FvideoCount)&key={YOUR_API_KEY}
Last video on channel: - demo
Here you can use other approach:
Use the channel_id and replace the value as follows:
Channel: Microsoft Hololens:
Channel_id: UCT2rZIAL-zNqeK1OmLLUa6g
Uploads (playlist): UUT2rZIAL-zNqeK1OmLLUa6g
Once you get the uploads (playlist), use the following request:
https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&playlistId=<UPLOAD_PLAYLIST>&fields=items(contentDetails(videoId%2CvideoPublishedAt))&key={YOUR_API_KEY}
And use the latest videoId from the response - (which has the most recent updated time).

Related

Youtube Analytics API - How to get all the video stats for a given channel and date?

We got to build our own reporting database for our Youtube channel to measure the channel and video performance.
To support this, we implemented an ETL job to extract using Youtube Analytics API and used below python code to get the data.
def GetAnalyticsData(extractDate,accessToken, channelId):
channelId = 'channel%3D%3D{0}'.format(channelId)
headers = {'Authorization': 'Bearer {}'.format(accessToken),
'accept': 'application/json'}
url = 'https://youtubeanalytics.googleapis.com/v2/reports?dimensions={dimensions}&endDate={enddate}&ids={ids}&maxResults={maxresults}&metrics={metrics}&startDate={startdate}&alt={alt}&sort={sort}'.format(
dimensions='video',
ids=channelId,
enddate= extractDate,
startdate=extractDate,
metrics = 'views%2Ccomments%2Clikes%2Cdislikes%2Cshares%2CestimatedMinutesWatched%2CsubscribersGained%2CsubscribersLost%2CannotationClicks%2CannotationClickThroughRate%2CaverageViewDuration%2CaverageViewPercentage%2CannotationCloseRate%2CannotationImpressions%2CannotationClickableImpressions%2CannotationClosableImpressions%2CannotationCloses',
maxresults = 200,
alt ='json',
sort='-views'
)
return requests.get(url,headers=headers)
We hit this API everyday and get all the video metric and sorted by views in descending order.
This solved our need partially and it returns only 200 videos, if we specify maxResults more than 200, its return 400 error code.
The challenge is, how to get all videos for the given date and given channel?
Thanks in advance.
Regards,
Guna
I am not keen on YouTube analytics API, but it seems that you are looking for startIndex.
startIndex
integer
The 1-based index of the first entity to retrieve. (The default value is 1.) Use this parameter as a pagination mechanism along with the max-results parameter.

youtube api - get timestamp of subscription

I am fetching all the Accounts that have subscribed to the authenticated user's channel.
Is there a way to obtain the timestamp of when the user has subscribed to the channel?
The default "publishedAt" sadly is of no help because that seems to be the timestamp of when the channel was created.
Also, that is not part of the "subscriberSnippet"-Section
Twitch and Mixer both provide "created_at", but the YouTube-API is a whole other story...
Thank you very much,
~ Daniel
Based from the official documentation of Youtube API:
Subscriptions: list
retrieves a list of channels that the specified channel subscribes to.
You can view here the subscriptions resource and publishedAt is part of it:
snippet.publishedAt datetime
The date and time that the subscription was created. The value is specified in ISO 8601
(YYYY-MM-DDThh:mm:ss.sZ) format.
You can try the try this section from the documentation and check your Youtube Subscibers List using Creator Studio by following the steps here.
Note: The list only shows subscribers who have chosen to make their
subscriptions public. When a user first joins YouTube, their
subscriptions list is set to private by default.
Yes, here's an example in Python
import requests
headers = {
'Authorization': 'Bearer {0}'.format(token),
'Client-Id': client_id
}
query = {
'part': 'subscriberSnippet,snippet',
'mySubscribers': 'true',
'key': youtube_key
}
if cursor is not None:
query['pageToken'] = cursor
response = requests.get(
'https://youtube.googleapis.com/youtube/v3/subscriptions',
headers=headers, params=query)
res = response.json()
weirdly, snippet contains your authenticated user channel description and title but publishedAt field corresponds to when the item from subscriberSnippet subscribed to your authenticated user

YouTube API: Get upload playlistID for YouTube Channel

I'm trying to figure out the best way to get a channel's upload playlistID given the channel's channelID. E.g. for the channel with channelID
UC9CuvdOVfMPvKCiwdGKL3cQ
The corresponding upload playlistID is
UU9CuvdOVfMPvKCiwdGKL3cQ
Notice the second character has changed from a "C" to a "U"
I can do this transformation via string manipulation, but I'm curious if there's a better, less hacky way to find the upload playlist ID through the official youtube api.
Here's some Kotlin code that shows my issue:
I can find the ChannelID for the "Game Grumps" channel through the following youtube api v3 search:
val req = youtube.search().list("snippet");
req.key = {API_KEY}
req.q = "Game Grumps"
req.type = "channel"
val response = req.execute();
The resulting Channel id (response.items[0].snippet.channelId) is UC9CuvdOVfMPvKCiwdGKL3cQ
But when I run the following to try to get the videos uploaded by the channel, I have to use the transformed ChannelID (starting with UU instead of UC)
val req = youtube.PlaylistItems().list("snippet")
req.playlistId = "UU9CuvdOVfMPvKCiwdGKL3cQ"
req.key = {API_KEY}
val response = req .execute()
If I use the untransformed "UC" channelID, I get the following error: The playlist identified with the requests playlistId parameter cannot be found.
Instead of just replacing the second character with a "U", what's the more robust way (e.g. using the youtube API) of translating a ChannelID to a PlaylistID (for the uploads from that channel)?
I would suggest using the official Youtube API, instead of trying to manipulate the strings. You can follow the instructions here:
Instructions to get video ids for all uploaded videos for a channel in V3
Get the channel id for the channel you want (you probably only need to do this once, then you can save it)
Use search.list
Set type to channel
Set q to the name of the channel you want
Grab the channel id (something like this: "channelId": "UC0X2VuXXXXXXXXXXXXXXXX")
Get the playlist id for the channel uploads using the channel id from step 1 (you probably only need to do this once, then you can save it)
Use channels.list
Set id to UC0X2VuXXXXXXXXXXXXXXXX from step 1
Grab the uploads key from contentDetails (something like this: "uploads": "UU0XXXXXXXXXXXXXXXXXXXX")
Get the videos via the playlistitems in the playlist using the playlist id from step 2
Use playlistItems.list
Set playlistId to UU0XXXXXXXXXXXXXXXXXXXX from step 2
Go through each PlaylistItem and pull out the video id

Youtube API 3 get latest videos

So I am trying to grab 10 latest videos from user uploads.
Now the only problem is that the only date visible in the playlistitems request is publishedAt which is the date when the video was uploaded
- not the date of when it was made public, which makes a huge difference.
I noticed that I can grab the correct date via the video request, but it just does not seem to be the best place to do it.
Let me show you an example of what I am dealing with.
Let's take Maroon5 channel.
forUserName: Maroon5VEVO
GET https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername=Maroon5VEVO&key={YOUR_API_KEY}
https://developers.google.com/youtube/v3/docs/channels/list#try-it
Here is where we grab the:
uploadsId: UUN1hnUccO4FD5WfM7ithXaw
So we can query:
GET https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=UUN1hnUccO4FD5WfM7ithXaw&maxResults=50&key={YOUR_API_KEY}
https://developers.google.com/youtube/v3/docs/playlistItems/list#try-it
and then we can have a look at some videos.
Let's grab the latest one. For me it is this one:
"title": "Maroon 5 - This Summer's Gonna Hurt Like A ... (Explicit)",
"videoId": "Wa64gOwuIyE"
And most importantly :
"publishedAt": "2015-06-01T17:41:58.000Z",
Now let's grab more details of this video, by running this query:
GET https://www.googleapis.com/youtube/v3/videos?part=snippet&id=Wa64gOwuIyE&key={YOUR_API_KEY}
https://developers.google.com/youtube/v3/docs/videos/list#try-it
Here we get more detailed view with a date that is ... different !
"publishedAt": "2015-06-01T20:00:01.000Z",
That means that the publishedAt date in playlists is actually the date of the upload - not when the video was made public.
In our list of 10 latest items we want the LATEST published videos , and not latest uploaded vids.
If you know a way how to approach it , please share.
Here is my snippet for now (working with a wrong publishedAt date)
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems",{
part : 'snippet',
maxResults : 10,
playlistId : UPLOADS_PID,
key: YOUR_API_KEY},
function(data) {
$.each( data.items, function(i, item ) {
(...)
});
}
);
I believe you can use /search endpoint. As you want to grab 10 latest videos from user uploads, you can use channel id instead of playlist id.
Request:
GET https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={CHANNEL_ID}&maxResults=10&order=date&type=video&key={YOUR_API_KEY}

How can I get a channel ID from YouTube?

I'm trying to retrive the data from my channel using the YouTube Data API V3.
For that I need my channel ID.
I've tried to find my channel ID from my YouTube account, and I failed in every single way.
If anyone have a single tip for me, I would be incredible glad.
This is the URL that I'm using to retrieve the data:
https://www.googleapis.com/youtube/v3/channels?id=fjTOrCPnAblTngWAzpnlMA&key={YOUR_API_KEY}&part=snippet,contentDetails,statistics
The ID is for the channel ID, and the key, I'm replacing the {YOUR_API_KEY} with my API KEY generated at my Google API console.
My channel ID is not:
- klauskkpm
- klausmachado
- klausmachado#gmail.com
- fjTOrCPnAblTngWAzpnlMA
My channel is: http://www.youtube.com/user/klauskkpm
To obtain the channel id you can view the source code of the channel page and find either data-channel-external-id="UCjXfkj5iapKHJrhYfAF9ZGg" or "externalId":"UCjXfkj5iapKHJrhYfAF9ZGg".
UCjXfkj5iapKHJrhYfAF9ZGg will be the channel ID you are looking for.
An easy answer is, your YouTube Channel ID is UC + {YOUR_ACCOUNT_ID}.
To be sure of your YouTube Channel ID or your YouTube account ID, access the advanced settings at your settings page
And if you want to know the YouTube Channel ID for any channel, you could use the solution #mjlescano gave.
https://www.googleapis.com/youtube/v3/channels?key={YOUR_API_KEY}&forUsername={USER_NAME}&part=id
If this could be of any help, some user marked it was solved in another topic right here.
You can get the channel ID with the username (in your case "klauskkpm") using the filter "forUsername", like this:
https://www.googleapis.com/youtube/v3/channels?key={YOUR_API_KEY}&forUsername=klauskkpm&part=id
More info here: https://developers.google.com/youtube/v3/docs/channels/list
At any channel page with "user" url for example http://www.youtube.com/user/klauskkpm, without API call, from YouTube UI, click a video of the channel (in its "VIDEOS" tab) and click the channel name on the video. Then you can get to the page with its "channel" url for example https://www.youtube.com/channel/UCfjTOrCPnAblTngWAzpnlMA.
I just found the simplest way to find the channel ID of any YouTube channel !!
Step 1: Play a video of that channel.
Step 2: Click the channel name under that video.
Step 3: Look at the browser address bar.
June 2021 edition.
Right click and view page source.
Search for "externalId", the value follows.
Source: comment by Daniel 2017.
Alternative: run this JavaScript in console:
ytInitialData.metadata.channelMetadataRenderer.externalId
An alternative to get youtube channel ID by channel url without API:
function get_youtube_channel_ID($url){
$html = file_get_contents($url);
preg_match("'<meta itemprop=\"channelId\" content=\"(.*?)\"'si", $html, $match);
if($match && $match[1])
return $match[1];
}
As of 2022-06-23:
Open Chrome Dev Tools (F12), and in the "Elements" tab, within the source code pane, depending on URL type:
A. For channel URLs of type: www.youtube.com/c/<channel_name>:
Search for either:
"externalId" - next to it there will be the channel_ID
"channelUrl" - next to it there will be: https://www.youtube.com/channel/<channel_ID>
or run in the console:
ytInitialData.metadata.channelMetadataRenderer.externalId
(credit: https://stackoverflow.com/a/68063136/624597)
B. For video URLs of type: www.youtube.com/watch?v=<video_ID>:
Search for either:
"externalId" - next to it there will be the channel_ID
"externalChannelId" - next to it there will be the channel_ID
"ownerProfileUrl" - next to it there will be: https://www.youtube.com/channel/<channel_ID>
or run in the console:
ytInitialPlayerResponse.microformat.playerMicroformatRenderer.externalChannelId
Channel id with the current youtube version is obtained very easily if you login to YouYube website and select 'My channel'
Your channel ID will be displayed on the address bar of your browser
https://www.youtube.com/account_advanced now provides both channel and user ids. See also https://developers.google.com/youtube/v3/guides/working_with_channel_ids .
2017 Update: Henry's answer may be a little off the mark here. If you look for data-channel-external-id in the source code you may find more than one ID, and only the first occurrence is actually correct. Get the channel_id used in <link rel="alternate" type="application/rss+xml" title="RSS" href="https://www.youtube.com/feeds/videos.xml?channel_id=<VALUE_HERE"> instead.
To obtain the channel id you can do the following request which gives you the channel id and playlist id.
https://www.googleapis.com/youtube/v3/channels?part=contentDetails%2C+statistics%2Csnippet&mine=true&key={YOUR_API_KEY}
mine parameter means the current authorized user
as u said channel id is prefixed with UC+{your account id} which you get while login, you can use this one also without requesting the above url you can directly call the channel api with your google id and just prefix with UC
https://www.googleapis.com/youtube/v3/channels?part=contentDetails%2C+statistics%2Csnippet&id=UC{your account id}&key={YOUR_API_KEY}
Apparently there is a channelId attribute in video page's source code;
To get Channel id
Ex: Apple channel ID
Select any of the video in that channel
Select iPhone - Share photos (video)
Now click on channel name Apple bottom of the video.
Now you will get channel id in browser url
Here this is Apple channel id : UCE_M8A5yxnLfW0KghEeajjw
Try to search for regular expression UC[-_0-9A-Za-z]{21}[AQgw] in source code. This ID is presented even if channel has non-ASCII characters in URL:
Here is screenshot of internal viewer/editor of Midnight Commander, it has regexp search:
Alternatives to get the channel URL with its ID.
With a CSS selector by searching the channel homepage source code:
body > link[rel="canonical"]
or with JS via the console:
document.querySelector('body > link[rel="canonical"]').href
Another method to find the ID of a channel that is not yours is to go to the channel page and press the red "Subscribe" button.
Then use the Chrome's Inspector tools Network tab and look for the POST request issued by the subscribe action. In the payload of this request you will find the channel id:
You can unsubscribe immediately after subscribing.
Now in 2023, typing this in console should work:
document.querySelectorAll('[itemprop="channelId"]')[0].content

Resources