How to get number of video views with YouTube API

2019-05-28 09:28发布

问题:

Anyone figured out a way to get number of video views with YouTube API into Google Docs?

Up until recently I was successfully using the method outlined in the YouTube View Count in Google Spreadsheet blog post by David Toy.

But it stopped working recently and I began to get the below error:

Request failed for https://gdata.youtube.com/feeds/api/videos/Prv2-9U39K8?v=2&alt=json returned code 410.
Truncated server response: <errors xmlns='http://schemas.google.com/g/2005'>
<error><domain>GData</domain><code>NoLongerAvailableException</code>
<internalReason>No longer avai... 
(use muteHttpExceptions option to examine full response) (line 2, file "Code")

Has anyone run into this? If so any ideas on how to fix it would be really helpful.

Thanks!

回答1:

The script from that blog post uses v2 of the API which has now been deprecated and switched off. The new version would be:

function getYoutubeViews(videoId){
  var url = "https://www.googleapis.com/youtube/v3/videos?part=statistics&id=" + videoId;
  url = url + "&key={YOUR-API-KEY}";
  var videoListResponse = UrlFetchApp.fetch(url);
  var json = JSON.parse(videoListResponse.getContentText());
  return json["items"][0]["statistics"]["viewCount"];
}

In order to make this work you will need an API key. Here is the guide on the YouTube developers site which explains how to get the key. Once you have obtained your key simply replace {YOUR-API-KEY} in the code above with it.

To call the function from a Google spreadsheet, select a cell and enter: =getYoutubeViews("{YOUR-VIDEO-ID}"). For instance, =getYoutubeViews("IiPJsI8pl8Q").