JavaScript 程式碼範例

下列程式碼範例使用 Google API JavaScript 專用用戶端程式庫。您可以從 GitHub 上的 YouTube API 程式碼範例存放區javascript 資料夾下載這個範例。

這段程式碼會要求使用者授權存取 https://www.googleapis.com/auth/yt-analytics.readonly 範圍。

return gapi.auth2.getAuthInstance()     .signIn({scope: "https://www.googleapis.com/auth/yt-analytics.readonly"})     ...

您的應用程式可能也需要要求存取其他範圍。舉例來說,如果應用程式會呼叫 YouTube Analytics API 和 YouTube Data API,可能也需要使用者授權存取 YouTube 帳戶。授權總覽會列出通常用於呼叫 YouTube Analytics API 的範圍。

擷取每日頻道統計資料

這個範例會呼叫 YouTube Analytics API,擷取授權使用者頻道在 2017 年的每日觀看次數和其他指標。這個範例使用 Google API JavaScript 用戶端程式庫

設定授權憑證

首次在本機執行這個範例前,請先設定專案的授權憑證:

  1. Google API 控制台中建立或選取專案。
  2. 為專案啟用 YouTube Analytics API
  3. 在「憑證」頁面頂端,選取「OAuth 同意畫面」分頁標籤。選取電子郵件地址,輸入產品名稱 (如尚未設定),然後按一下「儲存」按鈕。
  4. 在「憑證」頁面中,按一下「建立憑證」按鈕,然後選取「Oauth 用戶端 ID」
  5. 選取應用程式類型「網頁應用程式」。
  6. 在「授權的 JavaScript 來源」欄位中,輸入您提供程式碼範例的網址。舉例來說,您可以使用 http://localhost:8000http://yourserver.example.com。您可以將「已授權的重新導向 URI」欄位留空。
  7. 按一下「建立」按鈕,完成建立憑證。
  8. 關閉對話方塊前,請複製用戶端 ID,您需要將這個 ID 放入程式碼範例。

建立範例的本機副本

然後將範例儲存至本機檔案。在範例中找出下列這一行,並將 YOUR_CLIENT_ID 替換為您在設定授權憑證時取得的用戶端 ID。

gapi.auth2.init({client_id: 'YOUR_CLIENT_ID'});

執行程式碼

現在,您已準備好實際測試範例:

  1. 透過網路瀏覽器開啟本機檔案,並在瀏覽器中開啟偵錯控制台。您應該會看到顯示兩個按鈕的頁面。
  2. 按一下「授權並載入」按鈕,啟動使用者授權流程。授權應用程式擷取頻道資料後,瀏覽器的控制台應會顯示下列幾行內容:
     Sign-in successful GAPI client loaded for API
  3. 如果看到錯誤訊息而非上述程式碼,請確認您是從為專案設定的授權重新導向 URI 載入指令碼,並如上所述將用戶端 ID 放入程式碼。
  4. 按一下「execute」按鈕呼叫 API。您應該會在瀏覽器的控制台中看到 response 物件。在該物件中,result 屬性會對應至包含 API 資料的物件。

程式碼範例

<script src="https://apis.google.com/js/api.js"></script> <script>   function authenticate() {     return gapi.auth2.getAuthInstance()         .signIn({scope: "https://www.googleapis.com/auth/yt-analytics.readonly"})         .then(function() { console.log("Sign-in successful"); },               function(err) { console.error("Error signing in", err); });   }   function loadClient() {     return gapi.client.load("https://youtubeanalytics.googleapis.com/$discovery/rest?version=v2")         .then(function() { console.log("GAPI client loaded for API"); },               function(err) { console.error("Error loading GAPI client for API", err); });   }   // Make sure the client is loaded and sign-in is complete before calling this method.   function execute() {     return gapi.client.youtubeAnalytics.reports.query({       "ids": "channel==MINE",       "startDate": "2017-01-01",       "endDate": "2017-12-31",       "metrics": "views,estimatedMinutesWatched,averageViewDuration,averageViewPercentage,subscribersGained",       "dimensions": "day",       "sort": "day"     })         .then(function(response) {                 // Handle the results here (response.result has the parsed body).                 console.log("Response", response);               },               function(err) { console.error("Execute error", err); });   }   gapi.load("client:auth2", function() {     gapi.auth2.init({client_id: 'YOUR_CLIENT_ID'});   }); </script> <button onclick="authenticate().then(loadClient)">authorize and load</button> <button onclick="execute()">execute</button>