How to count the total number of views from a youtube channel? - youtube

I want to get the total amount of views (all videos) from a channel on youtube using the Youtube API in PHP. I didn't found any method to do that. Does anyone have en idea ? Thanks in advance for your help.

You can use the new YouTube Analytics API
https://developers.google.com/youtube/analytics/v1/available_reports
you can modify the code of the sample application to call the api in the client side:
https://developers.google.com/youtube/analytics/v1/sample-application
and do something like this to get the number of views per day:
var request = gapi.client.youtubeAnalytics.reports.query({
// Convert dates to YYYY-MM-DD strings for start-date and end-date parameters.
'start-date': formatDateString(lastWeek),
'end-date': formatDateString(today),
// Identify channel for which you're retrieving data.
ids: 'channel==' + channelId,
dimensions: 'day',
metrics: 'views'
});

This is the code (don't forget to rename yourUserName with your YouTube username):
$xdoc = new DomDocument;
$xdoc->Load('http://gdata.youtube.com/feeds/api/users/yourUserName');
$ytstat = $xdoc->getElementsByTagName('statistics')->item(0);
$total_views = $ytstat->getAttribute(totalUploadViews);
echo $total_views;

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 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}

Retrieving individual videos view count - Youtube API V3.0 - JavaScript

I've been trying to get the view count on videos that I query through the following method:
function search() {
var request = gapi.client.youtube.search.list({
part: 'snippet',
channelId: 'IRRELEVANT',
order: 'date',
maxResults: '25'
});
request.execute(function(response){
YoutubeResponse(response);
});
While the documentation tells me that there's a statistics portion to every video, after the snippet I have __proto__ which I guess means there was an error somewhere? or did the API change? Essentially I need the view count of those 25 most recent videos...
I tried changing part: 'snippet' to part: 'statistics' but got back a code: -32602...
Thanks for the help,
Cheers!
EDIT: Apparently the search.list doesn't have the "statistics" but rather I need to search every video individually... The thing is, when using googles "Try It" feature (https://developers.google.com/youtube/v3/docs/videos/list#try-it) when you ask for the statistics in the "Fields" part at the bottom, it doesn't do anything... So I am VERY confused as to how the heck can I get the view counts & length of all 25 videos (if individually or all at once - preferably-)
The link you gave https://developers.google.com/youtube/v3/docs/videos/list#try-it is working for me.
To get duration and viewCount: Fill in for part: contentDetails,statistics and for id: a comma-separated-list of video-id's like: TruIq5IxuiU,-VoFbH8jTzE,RPNDXrAvAMg,gmQmYc9-zcg
This will create a request as:
GET https://www.googleapis.com/youtube/v3/videos?part=contentDetails,statistics&id=TruIq5IxuiU,-VoFbH8jTzE,RPNDXrAvAMg,gmQmYc9-zcg&key={YOUR_API_KEY}
Agree with the answer provided by #Als.
But I found a code snippet which might be more convenient for some of you:
function youtube_view_count_shortcode($params)
{
$videoID = $params['id']; // view id here
$json = file_get_contents("https://www.googleapis.com/youtube/v3/videos?
part=statistics&id=" . $videoID . "&key=xxxxxxxxxxxxxxxxxxxxxxxx");
$jsonData = json_decode($json);
$views = $jsonData->items[0]->statistics->viewCount;
return number_format($views);
}
Replace the key value with the google api key for youtube data API and the video id with the youtube video id and Voila you get the total number of views for the youtube video.
Source: https://www.codementor.io/rajharajesuwari/how-to-get-youtube-views-count-aftojpxhj

Retrieve number of items in playlist with YouTube API v3

I'm transferring my iOS code from YouTube Data API v2 to v3.
I would like to retrieve the number of items in a playlist with YouTube API v3.
With the data API v2, I could call a search query, resulting in a list of playlist items with the property "size", which represented the size of the playlist, see:
https://gdata.youtube.com/feeds/api/playlists/snippets?q=GoogleDevelopers&max-results=10&v=2&alt=jsonc
With API v3, I haven't found a way to achieve this. I tried queries, like below, not resulting in the desired output.
https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=RD0KSOMA3QBU0&key={YOUR_API_KEY}
The only way to get the number of items is running a query for each playlist, retrieving the full playlist items. This is an overkill, however, and results in a too high API usage.
https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=RD0KSOMA3QBU0&key={YOUR_API_KEY}
Any help appreciated!
Thanks
thanks for that. It helped me to find a solution, which is now to call
https://www.googleapis.com/youtube/v3/playlists?part=contentDetails&id={Comma Separated ID's}&key={YOUR_API_KEY}
an use the option to make a comma separate lists of the playlists to evaluate. In the return string, I grab the "itemCount" parameter for each playlist.
Thanks
Unfortunately, there is no way to get number of items in a playlist without requesting contentDetails in the parts (which isn't supported when listing playlists).
I have use the following V3 api to get the playlist videos, and its works for me.
https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&maxResults=50&playlistId=PLFPg_IUxqnZM3uua-YwStHJ1qmlQKBnh0&key={YOUR_API_KEY_HERE}
**
playlistId
**
There is no details available for "playlistId" parameter in Youtube Documentation.
but is works for getting playlist videos.
This javascript will retrieve the number 91.
That is the total number of clips (total = data.pageInfo.totalResults)
from the youtube playlist
<script>
function numberOfClips(pid){
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems",{
part : 'snippet',
maxResults : 2,
playlistId : pid,
key: 'YOUR API v.3 KEY',
fields: 'pageInfo(totalResults)'
},
function(data) {
total = data.pageInfo.totalResults;
$('#total').html('Total number of clips: ' + total);
st = JSON.stringify(data,'',2);
$('#area1').val(st);
});
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body onload="numberOfClips('PLE9F62B21C75C054C')">
<p id="total"></p>
<textarea id='area1' style='width:400px;height:100px;'></textarea>
PLE9F62B21C75C054C
I would not recommend to rely on neither itemsCount in Playlist-Query nor pageInfo.totalResults in Playlistitems-Query, because both values may differ from the size of the retrieved list of playlist-items
see also: https://stackoverflow.com/questions/37899490/totalresults-in-playlistitems-do-not-match-items-size

Getting top twitter trends by country

I know how to get trends using API, but i want it by country and top 10.
How can I ? Is that possible?
Tried this one but not working
http://api.twitter.com/1/trends/current.json?count=50
Note that Twitter API v1 is no longer functional. Read announcement
So you should use Twitter API 1.1.
REST method is this: GET trends/place
https://dev.twitter.com/docs/api/1.1/get/trends/place
You should authenticate with access tokens to reach this data.
Yes, you can.
First, figure out which countries you want to get data for.
Calling
https://dev.twitter.com/docs/api/1/get/trends/available
Will give you a list of all the countries Twitter has trends for.
Suppose you want the trends for the UK. The above tells us that the WOEID is 23424975.
To get the top ten trends for the UK, call
https://api.twitter.com/1/trends/23424975.json
you need to figure out the woeids first use this tool here http://sigizmund.info/woeidinfo/ and then it becomes as easy as a simple function
function get_trends($woeid){
return json_decode(file_get_contents("http://api.twitter.com/1/trends/".$woeid.".json?exclude=hashtags", true), false);
}
Here you go, I wrote a simple sample script for you. Check It Out Here Twitter Trends Getter
Hope it helps!
I'm a 'bit' late to the party on this one but you can use:
npm i twit --save
then,
const Twit = require('twit');
const config = require('./config');
const T = new Twit(config);
const params = {
id: '23424829',
id: '23424975',
id: '23424977'
// count: 3
};
T.get('trends/place', params, gotData, limit);
function gotData(err, data, response) {
var tweets = data;
console.log(JSON.stringify(tweets, undefined, 2));
}
You have to Complete Authentication using Api Key to Fetch Results in JSON.
Another Thing Keep in Mind Twitter Api is Limited.
If you are Making Website for Top Twitter Trends then Visit this Url https://twitter-trends.vlivetricks.com/, Right Click >> Copy Source Code and Replace only Trends Name using Your Json Variable.

Resources