YouTube Live Analytics (views, total watch time) - youtube-api

I need to get metrics (primarily total live views and total/avg live view duration) for YouTube LIVE events. I'm having trouble with both v2 and v3 APIs.
I can schedule and stream through the API fine, and I'd like to pull the analytics as soon as the broadcast ends to roll up some reports.
Question
How can I get total or average live view duration from the v3 API?
Or, how can I properly query the v2 reports API for Live events to get non-zero data back?
More Details On Current Attempts
Here are the types of queries I've tried:
YouTube v3 API:
https://www.googleapis.com/youtube/v3/videos?
id={live_video_id}&
part={"statistics,liveStreamingDetails"}&
access_token={access_token}
{
"kind": "youtube#videoListResponse",
"etag": "...",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": "...",
"id": "..",
"statistics": {
"viewCount": "38",
"likeCount": "1",
"dislikeCount": "0",
"favoriteCount": "0",
"commentCount": "0"
},
"liveStreamingDetails": {
"actualStartTime": "2018-10-11T12:01:23.000Z",
"actualEndTime": "2018-10-11T14:00:12.000Z",
"scheduledStartTime": "2018-10-11T12:00:00.000Z",
"scheduledEndTime": "2018-10-11T14:00:00.000Z"
}
}
]
}
I can get statistics.viewCount count here, but there's no way to get the avg/total time watched.
YouTube v2 Reports API:
https://youtubeanalytics.googleapis.com/v2/reports?
startDate={"2017-01-01"}&
endDate={time.Now().Add(24*time.Hour).Format("YYYY-MM-DD")}&
filters={"video==" + live_video_id}&
metrics={"views,estimatedMinutesWatched"}&
ids={"channel==MINE"}&
access_token={accessToken}
{
"kind": "youtubeAnalytics#resultTable",
"columnHeaders": [
{
"name": "views",
"columnType": "METRIC",
"dataType": "INTEGER"
},
{
"name": "estimatedMinutesWatched",
"columnType": "METRIC",
"dataType": "INTEGER"
}
],
"rows": [
[
0,
0
]
]
}
This query would seem to give the metrics I need, but it's all 0s, even when v3 returns non-zero views.

TL;DR YouTube Reports API v2 doesn't update the metrics quite often for less popular live streams.
This is how I reached this conclusion...
I fetched the views, estimatedMinutesWatched of an old video from my channel. While both these APIs worked, the view count returned by the YouTube Reports API v2 was not accurate and was lagging behind the YouTube Data API v3.
Next, I ran a Livestream (unlisted) and engaged on the stream with a few other accounts. None of these engagements (like, subscribe, views) was shown in the Reports API v2 nor in YouTube Studio Analytics. This proves that the "rows": [[0,0]] returned by YouTube Reports API v2 is completely normal. But surprisingly, the Data API v3 did return the correct metrics as you pointed out.
For live streams with large audience and engagement, the Reports API may work perfectly fine.
Since the Data API doesn't provide watch times of any sort, your best bet would be to use both these APIs in conjunction, Data API v3 to fetch the basic metrics like views, likes,.. and the Reports API v2 for more sophisticated metrics.
Tip: If you are interested in displaying the live stream metrics later on, you can use the dimension=liveOrOnDemand parameter and filter the metrics to the LIVE stream alone.

Related

How to get a User's Youtube handle after they sign in with Google?

Is there an API to retrieve a user's Youtube handle as of today?
cannot find anything in Youtube Data API doc.
One more time YouTube Data API v3 doesn't provide a basic feature. As handle isn't found for channel handles in YouTube Data API v3 revision history, while it's a recent feature.
I recommend you to try out my open-source YouTube operational API. Indeed by fetching https://yt.lemnoslife.com/channels?part=about&id=CHANNEL_ID, you will get the channel handle you are looking for in item["about"]["handle"].
For instance for UCQxJsAlqmBPAbR_0syDi9mg you would get:
{
"kind": "youtube#channelListResponse",
"etag": "NotImplemented",
"items": [
{
"kind": "youtube#channel",
"etag": "NotImplemented",
"id": "UCQxJsAlqmBPAbR_0syDi9mg",
"about": {
...
"handle": "#Fairphone"
}
}
]
}

how to map youtube handles to channel IDs

Youtube recently rolled out handles feature where they gave users youtube.com/#xxx type usernames, when visited these URLs show user's channel but I can't find any documentation or reference in API repositories.
How to extract youtube user channel ID from their handle?
One more time YouTube Data API v3 doesn't provide a basic feature.
I recommend you to try out my open-source YouTube operational API. Indeed by fetching https://yt.lemnoslife.com/channels?handle=#HANDLE you will get the YouTube channel id you are looking for in item["id"].
For instance with the YouTube channel handle #WHO, you would get:
{
"kind": "youtube#channelListResponse",
"etag": "NotImplemented",
"items": [
{
"kind": "youtube#channel",
"etag": "NotImplemented",
"id": "UC07-dOwgza1IguKA86jqxNA"
}
]
}

Retrieve the subscribers id who watched video

Overall Goal: To report possible subscribers who are not active on my YouTube channel.
I'm reading through the YouTube Data API (v3) trying to understand how to retrieve the actual ids who watched a specific video. I know you can get the number of views, but I don't see any call/response that shows you the subscriber ids. Has anyone done this?
So far what I gathered from the docs and Google searching is that this was possible using the Watch History of a subscriber, but that's been deprecated.
Thanks in advance!
So I do not believe it's possible to get IDs of users who have watched certain videos but I have a workaround for my use case; reporting inactive subscribers. This is not the best but it'll get me somewhere.
YouTube's API is very limiting now, but by calling the Subscriptions API
https://www.googleapis.com/youtube/v3/subscriptions?part=snippet%2CcontentDetails&mySubscribers=true&key=[YOUR_API_KEY]
I am able to get all subscribers with their channel IDs. Then after saving their IDs, I can check each one's statistics by making this call:
https://www.googleapis.com/youtube/v3/channels?part=statistics&id=[SUB_ID]&key=[YOUR_API_KEY]
which I receive a response like this:
{
"kind": "youtube#channelListResponse",
"etag": "\"j6xRRd8dTPVVptg711_CSPADRfg/AZpZT_vQrY3UTi57ia_QqrKdc8c\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#channel",
"etag": "\"something\"",
"id": "[SUB_ID]",
"statistics": {
"viewCount": "0",
"commentCount": "0",
"subscriberCount": "1",
"hiddenSubscriberCount": false,
"videoCount": "0"
}
}
]
}
Using this response (see "statistics"), I am making a generalization that if the subscriber has no comments AND no videos, then it's a safe bet that they are not active.

What is difference of "Posted video" and "Uploads" in YouTube Channel? And how to get them through YouTube Data v3 API?

I am in the middle of developing a YouTube client using YouTube Data v3 API, and is playing with two different channels observed:
Go Pro Channel: https://www.youtube.com/user/GoProCamera/videos
YouTube curated Sports Channel: https://www.youtube.com/channel/UCEgdi0XIXXZ-qJOFPf4JSKw/videos
In Go Pro channel, I can also choose a video filter: "Uploads", "Liked" and "Posted Videos". I am much puzzled by the "Uploads" and "Posted Videos" filter, which from my observation, on this channel, they are giving the same result. But in YouTube curated sports channel, there is only "Posted Video" option there.
For the past hours, I can not find any definitive explanation from YouTube v2/v3's API documentation, and what is more bothering me is, I can not find any API to retrieve the video entry data in those channels.
For Go Pro Channel, I could at least rely on the method mentioned here to get uploaded video: How do I get a list of uploaded videos for a certain channel with the new YouTube Data API (V3)?
But for curated channels, even this method does not work, the playlist given in channel query result is always empty:
Request
GET https://www.googleapis.com/youtube/v3/channels?part=id%2CcontentDetails%2Csnippet&id=UCEgdi0XIXXZ-qJOFPf4JSKw&key={YOUR_API_KEY}
Authorization: Bearer ya29.dwCMU6xpf5N9AxwAAABgIM94lgv7jGHw0h0oEjs6uZUdPFO28CDYhbvgXdKTjw
X-JavaScript-User-Agent: Google APIs Explorer
Response
200 OK
- Show headers -
{
"kind": "youtube#channelListResponse",
"etag": "\"WFPuK6TsnblcGPcnMex79s42ynQ/qpdedwjxXQ-COrk0dODO-8DTAx0\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#channel",
"etag": "\"WFPuK6TsnblcGPcnMex79s42ynQ/TP96YXZ0G4VPdQ7fd2IYgW79rW0\"",
"id": "UCEgdi0XIXXZ-qJOFPf4JSKw",
"snippet": {
"title": "Sports",
"description": "Sport is all forms of usually competitive physical activity which, through casual or organised participation, aim to use, maintain or improve physical ability and skills while providing entertainment to participants, and in some cases, spectators. Hundreds of sports exist, from those requiring only two participants, through to those with hundreds of simultaneous participants, either in teams or competing as individuals. Sport is generally recognised as activities which are based in physical athleticism or physical dexterity, with the largest major competitions such as the Olympic Games admitting only sports meeting this definition, and other organisations such as the Council of Europe using definitions precluding activities without a physical element from classification as sports. However, a number of competitive, but non-physical, activities claim recognition as mind sports.\nThis channel was generated automatically by YouTube's video discovery system.",
"publishedAt": "2013-12-15T20:39:04.000Z",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/i/Egdi0XIXXZ-qJOFPf4JSKw/1.jpg"
},
"medium": {
"url": "https://i.ytimg.com/i/Egdi0XIXXZ-qJOFPf4JSKw/mq1.jpg"
},
"high": {
"url": "https://i.ytimg.com/i/Egdi0XIXXZ-qJOFPf4JSKw/hq1.jpg"
}
}
},
"contentDetails": {
"relatedPlaylists": {
"likes": "LLEgdi0XIXXZ-qJOFPf4JSKw",
"uploads": "UUEgdi0XIXXZ-qJOFPf4JSKw"
}
}
}
]
}
--
Request
GET https://www.googleapis.com/youtube/v3/playlistItems?part=id%2CcontentDetails%2Csnippet&playlistId=UUEgdi0XIXXZ-qJOFPf4JSKw&key={YOUR_API_KEY}
X-JavaScript-User-Agent: Google APIs Explorer
Response
200 OK
- Show headers -
{
"kind": "youtube#playlistItemListResponse",
"etag": "\"WFPuK6TsnblcGPcnMex79s42ynQ/0ky7gu-r2KEON6-qkmzKhU77B-Q\"",
"pageInfo": {
"totalResults": 0,
"resultsPerPage": 5
},
"items": [
]
}
It seems to me this is a dead end now, so is there any way to get videos from this kind of curated channels?
If you've already got the channel ID of the curated channel, you can just use the search endpoint to get the videos; for example, this API call will receive the 50 most recent videos added to YouTube's sports channel:
https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCEgdi0XIXXZ-qJOFPf4JSKw&maxResults=50&order=date&key={YOUR_API_KEY}

How to get "transcript" in youtube-api v3

I have started using v3 of the YouTube apis on an android device, using the java client library. Some videos that I am interested in have transcripts that I can access on the web interface (like educational videos). Is there a way to access the transcripts, if present, using the v3 apis?
Thanks
I had the same problem with this... and spent like a week looking for a solution until I hit this:
https://stackoverflow.com/questions/10036796/how-to-extract-subtitles-from-youtube-videos
Just do a GET request on: http://video.google.com/timedtext?lang={LANG}&v={VIDEOID}
You don't need any api/oauth/etc. to access this.
With API v3 you can first grab the available transcripts with the snippet:
https://www.googleapis.com/youtube/v3/captions?videoId=U1e2VNtEqm4&part=snippet&key=(my_api_key):
{
"kind": "youtube#captionListResponse",
"etag": "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/aGHflncRxq1Uz6m1akhrOLUWUqU\"",
"items": [
{
"kind": "youtube#caption",
"etag": "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/IC7rNKkn3SQNdovFwR6fEabUYnY\"",
"id": "TqXDnlamg84o4bX0q2oaHz4nfWZdyiZMOrcuWsSLyPc=",
"snippet": {
"videoId": "U1e2VNtEqm4",
"lastUpdated": "2016-01-25T21:50:27.142Z",
"trackKind": "standard",
"language": "en-GB",
"name": "",
"audioTrackType": "unknown",
"isCC": false,
"isLarge": false,
"isEasyReader": false,
"isDraft": false,
"isAutoSynced": false,
"status": "serving"
}
},
{
"kind": "youtube#caption",
"etag": "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/5UP1qPkmq6mzTUaEVnFC8WqjFgU\"",
"id": "TqXDnlamg84o4bX0q2oaHw_Y53ilUWv6vMFbk0RL3XY=",
"snippet": {
"videoId": "U1e2VNtEqm4",
"lastUpdated": "2016-01-25T21:55:07.481Z",
"trackKind": "standard",
"language": "en-US",
"name": "",
"audioTrackType": "unknown",
"isCC": false,
"isLarge": false,
"isEasyReader": false,
"isDraft": false,
"isAutoSynced": false,
"status": "serving"
}
}
]
}
And then pick the transcript you want:
https://www.googleapis.com/youtube/v3/captions/id?id=TqXDnlamg84o4bX0q2oaHz4nfWZdyiZMOrcuWsSLyPc=
or
https://www.googleapis.com/youtube/v3/captions/TqXDnlamg84o4bX0q2oaHz4nfWZdyiZMOrcuWsSLyPc=
at which point you need provide an authorization key. Apparently a simple key isn't enough. Possibly because:
Quota impact: A call to this method has a quota cost of approximately 200 units.
Note the slight difference in the URLs (/caption/ versus /caption?).
All the lovely documentation is here:
https://developers.google.com/youtube/v3/docs/captions
I may be wrong, but I don't think there is yet a documented way to get the caption track via v3 of the API. If you're authenticating with oAuth2, however, your authentication will also be good for v2 of the API, so you could do a quick call to this feed:
http://gdata.youtube.com/feeds/api/videos/[VIDEOID]/captiondata/[CAPTION TRACKID]
to get the data you want. To retrieve a list of possible caption track IDs with v2 of the API, you access this feed:
https://gdata.youtube.com/feeds/api/videos/[VIDEOID]/captions
That feed request also accepts some optional parameters, including language, max-results, etc. For more details, along with a sample that shows the returned format of the caption track list, see the documentation at https://developers.google.com/youtube/2.0/developers_guide_protocol_captions#Retrieve_Caption_Set
Heres some code I wrote which grabs all the caption tracks from any youtube video without having to use the API. Just plug the video URL in the $video_url variable.
// get video id from url
$video_url = 'https://www.youtube.com/watch?v=kYX87kkyubk';
preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $video_url, $matches);
// get video info from id
$video_id = $matches[0];
$video_info = file_get_contents('http://www.youtube.com/get_video_info?&video_id='.$video_id);
parse_str($video_info, $video_info_array);
if (isset($video_info_array['caption_tracks'])) {
$tracks = explode(',', $video_info_array['caption_tracks']);
// print info for each track (including url to track content)
foreach ($tracks as $track) {
parse_str($track, $output);
print_r($output);
}
}
Probably the best way is using Youtube API 3. I'm trying it but you need an API key + OAuth 2.0 user. A fast solution is using captionsgrabber and parsing the returned HTML data.
Use example:
https://www.captionsgrabber.com/8302/get-captions.00.php?id=UJTY7ilwSq4
// Where the id is the youtube video id

Resources