YouTube Reporting API 支援預先定義的報表,內含頻道或內容擁有者的完整 YouTube 數據分析資料。你可以透過這些報表下載大量資料集,並使用 YouTube Analytics API 查詢,或在 Creator Studio 的「數據分析」專區中查詢。
此外,API 也支援一組自動產生的系統管理報表,只要內容擁有者有權存取「報表」選單中的相應報表,就能使用這些報表。這些報表包含廣告收益資料和 YouTube Premium 訂閱收益資料。詳情請參閱系統管理報表說明文件。
總覽
這些報表中的報表欄位可分為維度和指標:
- 維度是常見的資料匯總條件,例如動作發生的日期或使用者所在的國家/地區。在報表中,每列資料都有不重複的維度值組合。
- 指標是與使用者活動、廣告成效或預估收益相關的個別評估結果。使用者活動指標包括影片觀看次數和評分 (喜歡和不喜歡)。
舉例來說,頻道的基礎使用者活動報表包含下列維度:
- day:活動發生的日期。
- 頻道:與活動相關聯的 YouTube 頻道。
- 影片:與活動相關聯的 YouTube 影片。
- liveOrOnDemand:表示觀眾是否觀看即時影像串流的值。
- subscribedStatus:表示觀眾是否已訂閱頻道的值。
- 國家/地區:觀眾所在的國家/地區。
報表也包含許多指標,例如觀看次數、喜歡次數和averageViewDuration。擷取及匯入報表後,應用程式可根據常見的維度值進行多種不同的計算。
舉例來說,如要計算特定日期在德國的觀看次數總和,請加總 views 指標值,但前提是 country 資料欄值為 DE,且 day 資料欄值為 YYYY-MM-DD 格式的日期。
擷取 YouTube 數據分析報表
下列步驟說明如何透過 API 擷取頻道和內容擁有者報表。如需如何擷取這些報表的操作說明,請參閱「系統管理的報表」。
步驟 1:擷取授權憑證
所有 YouTube Reporting API 要求皆須獲得授權。如要透過 OAuth 2.0 通訊協定擷取授權權杖,請參閱授權指南。
YouTube Reporting API 要求會使用下列授權範圍:
| 範圍 | |
|---|---|
| https://www.googleapis.com/auth/yt-analytics.readonly | 查看您 YouTube 內容的 YouTube 數據分析報表。這個範圍可存取使用者活動指標,例如觀看次數和評分次數。 |
| https://www.googleapis.com/auth/yt-analytics-monetary.readonly | 查看您 YouTube 內容的 YouTube 數據分析金額報表。這個範圍可存取使用者活動指標,以及預估收益和廣告成效指標。 |
步驟 2:找出要擷取的報表
呼叫 API 的 reportTypes.list 方法,擷取可為頻道或內容擁有者產生的報表清單。這個方法會傳回報表 ID 和名稱的清單。擷取要產生報表的 id 資源值。舉例來說,頻道的基礎使用者活動報表 ID 為 channel_basic_a3。
您也可以在定義支援的頻道報表和內容擁有者報表文件中,找到報表名稱。
步驟 3:建立報表工作
您必須先為報表建立報表工作,YouTube 才會開始產生報表。(因此,系統只會為實際想擷取報表的頻道和內容擁有者產生報表)。
如要建立報表工作,請呼叫 API 的 jobs.create 方法。在要求主體中設定下列值:
- 將
reportTypeId屬性的值設為您在步驟 2 中擷取的報表 ID。 - 將
name屬性的值設為要與報表建立關聯的名稱。
jobs.create 方法的 API 回應包含 Job 資源,其中指定了可唯一識別工作的 ID。工作建立後 48 小時內,您就能開始擷取報表,而第一份報表會是您排定工作當天的資料。
舉例來說,如果您在 9 月 1 日排定工作,9 月 1 日的報表將於 9 月 3 日產生。9 月 2 日的報告將於 9 月 4 日發布。
步驟 4:擷取工作 ID
注意:如果應用程式已儲存步驟 3 中傳回的工作 ID,則可略過這個步驟。
呼叫 jobs.list 方法,即可擷取排定工作清單。每個傳回的 Job 資源中的 reportTypeId 屬性,會指出該工作產生的報表類型。應用程式在下一個步驟中,需要使用相同資源的 id 屬性值。
步驟 5:擷取報表的下載網址
呼叫 jobs.reports.list 方法,擷取為工作建立的報表清單。在要求中,將 jobId 參數設為要擷取報表的作業 ID。
提示:使用 createdAfter 參數,表示 API 應只傳回指定時間後建立的報表。這個參數可確保 API 只會傳回您尚未處理的報表。
API 回應會包含該工作的 Report 資源清單。每個資源都代表一份報表,內含特定 24 小時期間的資料。請注意,即使當天沒有資料,YouTube 仍會產生可供下載的報表。這些報表包含標題列,但不含其他資料。
- 資源的
startTime和endTime屬性會指出報表資料涵蓋的時間範圍。 - 資源的
downloadUrl屬性會指出可擷取報表的網址。 - 資源的
createTime屬性會指定報表的產生日期和時間。應用程式應儲存這個值,並用來判斷先前下載的報表是否已變更。
步驟 6:下載報表
向步驟 5 中取得的 downloadUrl 傳送 HTTP GET 要求,以擷取報表。
如要減少下載報表所需的頻寬,請在下載要求中啟用 gzip 壓縮。雖然應用程式需要額外的 CPU 時間來解壓縮 API 回應,但通常節省網路資源的好處會大於這項成本。
如要接收以 gzip 編碼的回應,請將 Accept-Encoding HTTP 要求標頭設為 gzip,如下列範例所示:
Accept-Encoding: gzip
處理報表
最佳做法
使用 YouTube Reporting API 的應用程式「一律」應遵循下列做法:
-
如要決定報表欄的順序,請使用報表的標題列。舉例來說,報表說明中列出的第一個指標是「觀看次數」,但這不代表「觀看次數」就是報表中傳回的第一個指標。請改用報表的標題列,判斷哪個資料欄包含該資料。
為確保日後報表處理作業不受影響,應用程式應預期任何報表都會新增指標,並準備好處理及納入這些新資料欄。新指標會以新資料欄的形式顯示在報表標題中。
-
為避免重複處理同一份報表,請記錄您已下載的報表。以下列舉幾種做法。
-
呼叫
reports.list方法時,請使用 createdAfter 參數,只擷取特定日期後建立的報表。(首次擷取報表時,請省略createdAfter參數)。每次擷取並順利處理報表時,請儲存與最新報表建立日期和時間對應的時間戳記。然後,在每次呼叫
reports.list方法時,更新createdAfter參數值,確保每次呼叫 API 時只會擷取新報表,包括含有回填資料的新報表。為確保安全,在擷取報表前,請先檢查資料庫中是否已列出該報表的 ID。
-
儲存您下載及處理的每份報表 ID。您也可以儲存其他資訊,例如每份報表的產生日期和時間,或是報表的
startTime和endTime,這兩者會共同指出報表包含資料的期間。請注意,由於每份報表都包含 24 小時的資料,因此每個工作可能會有多份報表。使用報表 ID 找出仍需下載及匯入的報表。不過,如果兩份新報表具有相同的
startTime和endTime屬性值,請只匯入createTime值較新的報表。
-
-
報表包含與 YouTube 資源相關聯的 ID。如要擷取這些資源的其他中繼資料,請使用 YouTube Data API。如《YouTube API 服務開發人員政策》(第 III.E.4.b 節至 III.E.4.d 節) 所述,API 用戶端必須在 30 天後刪除或重新整理從該 API 儲存的資源中繼資料。
報表特性
API 報表是版本化的 .csv (逗號分隔值) 檔案,具有下列特性:
-
每份報表都包含一段 24 小時的資料,時間範圍為太平洋標準時間 (UTC-8) 凌晨 12:00 至晚上 11:59。因此,在任何報表中,「日期」維度值一律相同。
-
報表每天都會更新。
-
即使當天沒有資料,YouTube 仍會產生可供下載的報表。這些報表會包含標題列,但不會包含其他資料。
- API 報表自產生當日起 60 天內有效,但為新報表工作產生的歷來資料除外。報表超過 60 天後,您就無法存取。
- 包含歷來資料的報表在產生後可保留 30 天。如果報表包含歷來資料,且建立時間超過 30 天,您就無法存取。
-
報表資料未經過濾。因此,頻道報表會包含頻道影片或播放清單的所有資料,但刪除資源的相關資料除外 (請參閱下段)。同樣地,內容擁有者報表包含內容擁有者頻道的所有資料 (影片、播放清單、廣告成效等),但有以下例外情況。
雖然報表資料不會經過篩選,但如果 YouTube 資源在報表產生日期前至少 30 天遭到刪除,報表就不會包含任何相關參照。
-
報表資料未排序。
-
報表會省略沒有指標的資料列。換句話說,報表會排除沒有任何指標的資料列。舉例來說,如果某部影片在特定日期於阿爾巴尼亞沒有任何觀看次數,當天的報表就不會包含阿爾巴尼亞的資料列。
-
報表不會提供指標的摘要資料列,例如頻道所有影片的總觀看次數。您可以將報表中的值加總,計算出這些總值,但加總結果可能不包含已刪除影片的指標。你也可以使用 YouTube Analytics API 擷取總計數。即使 API 回應中未明確參照已刪除的資源,YouTube Analytics API 仍會傳回包含這些資源指標的總值。
-
空白維度值:在大量報表中,
video_id或channel_id等維度資料欄在下列情況中可能包含空字串:- 已刪除的資源:如果影片或頻道已刪除,報表會省略已刪除資源的 ID,但仍會納入資料列,以保留上層實體的匯總指標總計。
- 頻道層級指標:在包含
video_id維度的報表中,頻道層級的指標 (例如直接從頻道首頁獲得的訂閱) 會顯示在video_id為空字串的資料列中。
補充資料
回填資料是指取代先前傳送資料集的資料集。當系統提供回填資料報表時,應用程式應擷取新報表,並更新儲存的資料,以符合修訂後的資料集。舉例來說,應用程式可以刪除報表涵蓋時間範圍的先前資料,然後匯入新的資料集。
如果 YouTube 有回填資料,就會產生新的報告,並提供新的報告 ID。在這種情況下,報表的 startTime 和 endTime 屬性值會與先前提供的報表 (您可能已下載) 的開始和結束時間相符。
如果 YouTube 資源在報表產生日期前至少 30 天遭到刪除,回填報表就不會包含任何相關參照。
歷來資料
排定新的報表工作後,YouTube 會從當天起產生歷來報表,並產生涵蓋工作建立時間前 30 天的報表。因此,在本文件中,歷來資料是指包含報表工作排定前一段時間範圍資料的報表。
歷來報告一經發布,就會立即顯示。通常,系統會在幾天內發布職缺的所有歷來資料。如「報表特性」一節所述,包含歷來資料的報表在產生後可保留 30 天。不含歷來資料的報表可保留 60 天。
資料去識別化
為確保 YouTube 觀眾的匿名性,只有當同一列中的指標達到特定門檻時,系統才會傳回部分維度的值。
舉例來說,在頻道的影片流量來源報表中,每個資料列都包含多個維度,包括 trafficSourceType 和 trafficSourceDetail。每個資料列也包含各種指標,包括觀看次數。在說明來自 YouTube 搜尋的流量的資料列中,trafficSourceDetail 維度會指出帶來流量的搜尋字詞。
在這個範例中,適用下列規則:
-
只有在特定日期,查詢字詞為特定影片帶來至少一定數量的觀看次數時,流量來源報表才會識別查詢字詞 (trafficSourceDetail)。在這個例子中,「觀看次數」是指標,「影片」是匯總維度,而「流量來源詳細資料」trafficSourceDetail是匿名維度。
-
報表會新增一列,匯總所有未達到觀看次數門檻的 trafficSourceDetail 值指標。該資料列會回報與這些查詢字詞相關聯的觀看次數總數,但不會識別字詞本身。
下表說明這些規則。第一個表格包含 YouTube 用來產生流量來源報表的假設原始資料集,第二個表格則包含報表本身。在這個範例中,觀看次數門檻為 10,也就是說,只有在特定日期,搜尋字詞為特定影片帶來至少 10 次觀看時,報表才會識別該搜尋字詞。(實際門檻可能會變動)。
影片的原始 YouTube 搜尋流量資料
假設下列資料說明特定影片在特定日期的 YouTube 搜尋流量。
| 搜尋字詞 | 觀看次數 | 估計觀看時間 (分鐘) |
|---|---|---|
| gangnam style | 100 | 200 |
| psy | 15 | 25 |
| psy gangnam | 9 | 15 |
| oppa gangnam | 5 | 8 |
| 騎馬舞 | 2 | 5 |
流量來源報表示例
下表摘錄 YouTube 為前一節中的原始資料產生的流量來源報表。(實際報表會包含更多維度和指標)。在本例中,只有當搜尋字詞帶來至少 10 次觀看時,報表才會識別出這些字詞。實際門檻可能會有所變動。
在報表的第三列中,trafficSourceDetail 維度值為 NULL。views 和 estimatedMinutesWatched 指標包含產生不到 10 次觀看的 3 個搜尋字詞的合併觀看次數和觀看時間 (分鐘)。
| trafficSourceDetail | 觀看次數 | estimatedMinutesWatched |
|---|---|---|
| gangnam style | 100 | 200 |
| psy | 15 | 25 |
| NULL | 16 | 28 |
會經過匿名處理的維度
下表列出維度值,如果相關聯的指標值未達到特定門檻,系統就會將這些維度值匿名化。在上述兩種情況中,指標值都是根據另一個維度匯總而來。舉例來說,如果指標是「觀看次數」,而匯總維度是「影片」,除非影片的觀看次數達到特定門檻,否則維度值會經過匿名處理。
| 指標 | 匯總維度 | 匿名維度 | 匿名值 |
|---|---|---|---|
| subscribersGained | channel | country | ZZ |
| subscribersGained | channel | province | US-ZZ |
| subscribersLost | channel | country | ZZ |
| subscribersLost | channel | province | US-ZZ |
| comments | 影片 | country | ZZ |
| comments | 影片 | province | US-ZZ |
| 喜歡次數 | 影片 | country | ZZ |
| 喜歡次數 | 影片 | province | US-ZZ |
| 不喜歡 | 影片 | country | ZZ |
| 不喜歡 | 影片 | province | US-ZZ |
| 觀看次數 | 影片 | ageGroup | NULL |
| 觀看次數 | 影片 | gender | NULL |
| 觀看次數 | video 和 trafficSourceDetail | trafficSourceDetail | NULL |
| 頻道訂閱人數 | channel | subscribedStatus | NULL |
程式碼範例
下列程式碼範例示範如何使用 API 建立報表作業,然後擷取該作業的報表。每種語言都提供兩個程式碼範例:
-
第一個程式碼範例說明如何擷取可用報表類型清單,然後建立新的報表作業。
-
第二個程式碼範例說明如何擷取特定工作的報表。工作建立完成後 48 小時內,您就可以開始擷取報表。
附註:下列程式碼範例可能不適用於所有支援的程式設計語言。如需支援的語言清單,請參閱用戶端程式庫。
Java
下列範例使用 Java 用戶端程式庫:
範例 1:建立報表工作
下列程式碼範例會呼叫 reportTypes.list 方法,擷取可用報表類型的清單。接著,系統會呼叫 jobs.create 方法來建立新的報表工作。
/* * Copyright (c) 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.services.samples.youtube.cmdline.reporting; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.services.samples.youtube.cmdline.Auth; import com.google.api.services.youtubereporting.YouTubeReporting; import com.google.api.services.youtubereporting.model.Job; import com.google.api.services.youtubereporting.model.ListReportTypesResponse; import com.google.api.services.youtubereporting.model.ReportType; import com.google.common.collect.Lists; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; /** * This sample creates a reporting job by: * * 1. Listing the available report types using the "reportTypes.list" method. * 2. Creating a reporting job using the "jobs.create" method. * * @author Ibrahim Ulukaya */ public class CreateReportingJob { /** * Define a global instance of a YouTube Reporting object, which will be used to make * YouTube Reporting API requests. */ private static YouTubeReporting youtubeReporting; /** * Create a reporting job. * * @param args command line args (not used). */ public static void main(String[] args) { /* * This OAuth 2.0 access scope allows for read access to the YouTube Analytics monetary reports for * authenticated user's account. Any request that retrieves earnings or ad performance metrics must * use this scope. */ List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/yt-analytics-monetary.readonly"); try { // Authorize the request. Credential credential = Auth.authorize(scopes, "createreportingjob"); // This object is used to make YouTube Reporting API requests. youtubeReporting = new YouTubeReporting.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential) .setApplicationName("youtube-cmdline-createreportingjob-sample").build(); // Prompt the user to specify the name of the job to be created. String name = getNameFromUser(); if (listReportTypes()) { createReportingJob(getReportTypeIdFromUser(), name); } } catch (GoogleJsonResponseException e) { System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("IOException: " + e.getMessage()); e.printStackTrace(); } catch (Throwable t) { System.err.println("Throwable: " + t.getMessage()); t.printStackTrace(); } } /** * Lists report types. (reportTypes.listReportTypes) * @return true if at least one report type exists * @throws IOException */ private static boolean listReportTypes() throws IOException { // Call the YouTube Reporting API's reportTypes.list method to retrieve report types. ListReportTypesResponse reportTypesListResponse = youtubeReporting.reportTypes().list() .execute(); List<ReportType> reportTypeList = reportTypesListResponse.getReportTypes(); if (reportTypeList == null || reportTypeList.isEmpty()) { System.out.println("No report types found."); return false; } else { // Print information from the API response. System.out.println("\n================== Report Types ==================\n"); for (ReportType reportType : reportTypeList) { System.out.println(" - Id: " + reportType.getId()); System.out.println(" - Name: " + reportType.getName()); System.out.println("\n-------------------------------------------------------------\n"); } } return true; } /** * Creates a reporting job. (jobs.create) * * @param reportTypeId Id of the job's report type. * @param name name of the job. * @throws IOException */ private static void createReportingJob(String reportTypeId, String name) throws IOException { // Create a reporting job with a name and a report type id. Job job = new Job(); job.setReportTypeId(reportTypeId); job.setName(name); // Call the YouTube Reporting API's jobs.create method to create a job. Job createdJob = youtubeReporting.jobs().create(job).execute(); // Print information from the API response. System.out.println("\n================== Created reporting job ==================\n"); System.out.println(" - ID: " + createdJob.getId()); System.out.println(" - Name: " + createdJob.getName()); System.out.println(" - Report Type Id: " + createdJob.getReportTypeId()); System.out.println(" - Create Time: " + createdJob.getCreateTime()); System.out.println("\n-------------------------------------------------------------\n"); } /* * Prompt the user to enter a name for the job. Then return the name. */ private static String getNameFromUser() throws IOException { String name = ""; System.out.print("Please enter the name for the job [javaTestJob]: "); BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); name = bReader.readLine(); if (name.length() < 1) { // If nothing is entered, defaults to "javaTestJob". name = "javaTestJob"; } System.out.println("You chose " + name + " as the name for the job."); return name; } /* * Prompt the user to enter a report type id for the job. Then return the id. */ private static String getReportTypeIdFromUser() throws IOException { String id = ""; System.out.print("Please enter the reportTypeId for the job: "); BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); id = bReader.readLine(); System.out.println("You chose " + id + " as the report type Id for the job."); return id; } }
範例 2:擷取報表
程式碼範例會呼叫 jobs.list 方法,擷取報表工作清單。接著,路徑會呼叫 reports.list 方法,並將 jobId 參數設為特定工作 ID,以擷取該工作建立的報表。最後,範例會列印每份報表的下載網址。
/* * Copyright (c) 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.services.samples.youtube.cmdline.reporting; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.GenericUrl; import com.google.api.services.samples.youtube.cmdline.Auth; import com.google.api.services.youtubereporting.YouTubeReporting; import com.google.api.services.youtubereporting.YouTubeReporting.Media.Download; import com.google.api.services.youtubereporting.model.Job; import com.google.api.services.youtubereporting.model.ListJobsResponse; import com.google.api.services.youtubereporting.model.ListReportsResponse; import com.google.api.services.youtubereporting.model.Report; import com.google.common.collect.Lists; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import javax.print.attribute.standard.Media; /** * This sample retrieves reports created by a specific job by: * * 1. Listing the jobs using the "jobs.list" method. * 2. Retrieving reports using the "reports.list" method. * * @author Ibrahim Ulukaya */ public class RetrieveReports { /** * Define a global instance of a YouTube Reporting object, which will be used to make * YouTube Reporting API requests. */ private static YouTubeReporting youtubeReporting; /** * Retrieve reports. * * @param args command line args (not used). */ public static void main(String[] args) { /* * This OAuth 2.0 access scope allows for read access to the YouTube Analytics monetary reports for * authenticated user's account. Any request that retrieves earnings or ad performance metrics must * use this scope. */ List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/yt-analytics-monetary.readonly"); try { // Authorize the request. Credential credential = Auth.authorize(scopes, "retrievereports"); // This object is used to make YouTube Reporting API requests. youtubeReporting = new YouTubeReporting.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential) .setApplicationName("youtube-cmdline-retrievereports-sample").build(); if (listReportingJobs()) { if(retrieveReports(getJobIdFromUser())) { downloadReport(getReportUrlFromUser()); } } } catch (GoogleJsonResponseException e) { System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("IOException: " + e.getMessage()); e.printStackTrace(); } catch (Throwable t) { System.err.println("Throwable: " + t.getMessage()); t.printStackTrace(); } } /** * Lists reporting jobs. (jobs.listJobs) * @return true if at least one reporting job exists * @throws IOException */ private static boolean listReportingJobs() throws IOException { // Call the YouTube Reporting API's jobs.list method to retrieve reporting jobs. ListJobsResponse jobsListResponse = youtubeReporting.jobs().list().execute(); List<Job> jobsList = jobsListResponse.getJobs(); if (jobsList == null || jobsList.isEmpty()) { System.out.println("No jobs found."); return false; } else { // Print information from the API response. System.out.println("\n================== Reporting Jobs ==================\n"); for (Job job : jobsList) { System.out.println(" - Id: " + job.getId()); System.out.println(" - Name: " + job.getName()); System.out.println(" - Report Type Id: " + job.getReportTypeId()); System.out.println("\n-------------------------------------------------------------\n"); } } return true; } /** * Lists reports created by a specific job. (reports.listJobsReports) * * @param jobId The ID of the job. * @throws IOException */ private static boolean retrieveReports(String jobId) throws IOException { // Call the YouTube Reporting API's reports.list method // to retrieve reports created by a job. ListReportsResponse reportsListResponse = youtubeReporting.jobs().reports().list(jobId).execute(); List<Report> reportslist = reportsListResponse.getReports(); if (reportslist == null || reportslist.isEmpty()) { System.out.println("No reports found."); return false; } else { // Print information from the API response. System.out.println("\n============= Reports for the job " + jobId + " =============\n"); for (Report report : reportslist) { System.out.println(" - Id: " + report.getId()); System.out.println(" - From: " + report.getStartTime()); System.out.println(" - To: " + report.getEndTime()); System.out.println(" - Download Url: " + report.getDownloadUrl()); System.out.println("\n-------------------------------------------------------------\n"); } } return true; } /** * Download the report specified by the URL. (media.download) * * @param reportUrl The URL of the report to be downloaded. * @throws IOException */ private static boolean downloadReport(String reportUrl) throws IOException { // Call the YouTube Reporting API's media.download method to download a report. Download request = youtubeReporting.media().download(""); FileOutputStream fop = new FileOutputStream(new File("report")); request.getMediaHttpDownloader().download(new GenericUrl(reportUrl), fop); return true; } /* * Prompt the user to enter a job id for report retrieval. Then return the id. */ private static String getJobIdFromUser() throws IOException { String id = ""; System.out.print("Please enter the job id for the report retrieval: "); BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); id = bReader.readLine(); System.out.println("You chose " + id + " as the job Id for the report retrieval."); return id; } /* * Prompt the user to enter a URL for report download. Then return the URL. */ private static String getReportUrlFromUser() throws IOException { String url = ""; System.out.print("Please enter the report URL to download: "); BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); url = bReader.readLine(); System.out.println("You chose " + url + " as the URL to download."); return url; }}
PHP
下列範例使用 PHP 用戶端程式庫。
範例 1:建立報表工作
下列程式碼範例會呼叫 reportTypes.list 方法,擷取可用報表類型的清單。接著,系統會呼叫 jobs.create 方法來建立新的報表工作。
<?php /** * This sample creates a reporting job by: * * 1. Listing the available report types using the "reportTypes.list" method. * 2. Creating a reporting job using the "jobs.create" method. * * @author Ibrahim Ulukaya */ /** * Library Requirements * * 1. Install composer (https://getcomposer.org) * 2. On the command line, change to this directory (api-samples/php) * 3. Require the google/apiclient library * $ composer require google/apiclient:~2.0 */ if (!file_exists(__DIR__ . '/vendor/autoload.php')) { throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"'); } require_once __DIR__ . '/vendor/autoload.php'; session_start(); /* * You can acquire an OAuth 2.0 client ID and client secret from the * {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}> * For more information about using OAuth 2.0 to access Google APIs, please see: * <https://developers.google.com/youtube/v3/guides/authentication> * Please ensure that you have enabled the YouTube Data API for your project. */ $OAUTH2_CLIENT_ID = 'REPLACE_ME'; $OAUTH2_CLIENT_SECRET = 'REPLACE_ME'; $client = new Google_Client(); $client->setClientId($OAUTH2_CLIENT_ID); $client->setClientSecret($OAUTH2_CLIENT_SECRET); /* * This OAuth 2.0 access scope allows for read access to the YouTube Analytics monetary reports for * authenticated user's account. Any request that retrieves earnings or ad performance metrics must * use this scope. */ $client->setScopes('https://www.googleapis.com/auth/yt-analytics-monetary.readonly'); $redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL); $client->setRedirectUri($redirect); // YouTube Reporting object used to make YouTube Reporting API requests. $youtubeReporting = new Google_Service_YouTubeReporting($client); // Check if an auth token exists for the required scopes $tokenSessionKey = 'token-' . $client->prepareScopes(); if (isset($_GET['code'])) { if (strval($_SESSION['state']) !== strval($_GET['state'])) { die('The session state did not match.'); } $client->authenticate($_GET['code']); $_SESSION[$tokenSessionKey] = $client->getAccessToken(); header('Location: ' . $redirect); } if (isset($_SESSION[$tokenSessionKey])) { $client->setAccessToken($_SESSION[$tokenSessionKey]); } // Check to ensure that the access token was successfully acquired. if ($client->getAccessToken()) { // This code executes if the user enters a name in the form // and submits the form. Otherwise, the page displays the form above. try { if (empty(listReportTypes($youtubeReporting, $htmlBody))) { $htmlBody .= sprintf('<p>No report types found.</p>'); } else if ($_GET['reportTypeId']){ createReportingJob($youtubeReporting, $_GET['reportTypeId'], $_GET['jobName'], $htmlBody); } } catch (Google_Service_Exception $e) { $htmlBody = sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } catch (Google_Exception $e) { $htmlBody = sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } $_SESSION[$tokenSessionKey] = $client->getAccessToken(); } elseif ($OAUTH2_CLIENT_ID == 'REPLACE_ME') { $htmlBody = <<<END <h3>Client Credentials Required</h3> <p> You need to set <code>\$OAUTH2_CLIENT_ID</code> and <code>\$OAUTH2_CLIENT_ID</code> before proceeding. <p> END; } else { // If the user hasn't authorized the app, initiate the OAuth flow $state = mt_rand(); $client->setState($state); $_SESSION['state'] = $state; $authUrl = $client->createAuthUrl(); $htmlBody = <<<END <h3>Authorization Required</h3> <p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p> END; } /** * Creates a reporting job. (jobs.create) * * @param Google_Service_YouTubereporting $youtubeReporting YouTube Reporting service object. * @param string $reportTypeId Id of the job's report type. * @param string $name name of the job. * @param $htmlBody - html body. */ function createReportingJob(Google_Service_YouTubeReporting $youtubeReporting, $reportTypeId, $name, &$htmlBody) { # Create a reporting job with a name and a report type id. $reportingJob = new Google_Service_YouTubeReporting_Job(); $reportingJob->setReportTypeId($reportTypeId); $reportingJob->setName($name); // Call the YouTube Reporting API's jobs.create method to create a job. $jobCreateResponse = $youtubeReporting->jobs->create($reportingJob); $htmlBody .= "<h2>Created reporting job</h2><ul>"; $htmlBody .= sprintf('<li>"%s" for reporting type "%s" at "%s"</li>', $jobCreateResponse['name'], $jobCreateResponse['reportTypeId'], $jobCreateResponse['createTime']); $htmlBody .= '</ul>'; } /** * Returns a list of report types. (reportTypes.listReportTypes) * * @param Google_Service_YouTubereporting $youtubeReporting YouTube Reporting service object. * @param $htmlBody - html body. */ function listReportTypes(Google_Service_YouTubeReporting $youtubeReporting, &$htmlBody) { // Call the YouTube Reporting API's reportTypes.list method to retrieve report types. $reportTypes = $youtubeReporting->reportTypes->listReportTypes(); $htmlBody .= "<h3>Report Types</h3><ul>"; foreach ($reportTypes as $reportType) { $htmlBody .= sprintf('<li>id: "%s", name: "%s"</li>', $reportType['id'], $reportType['name']); } $htmlBody .= '</ul>'; return $reportTypes; } ?> <!doctype html> <html> <head> <title>Create a reporting job</title> </head> <body> <form method="GET"> <div> Job Name: <input type="text" id="jobName" name="jobName" placeholder="Enter Job Name"> </div> <br> <div> Report Type Id: <input type="text" id="reportTypeId" name="reportTypeId" placeholder="Enter Report Type Id"> </div> <br> <input type="submit" value="Create!"> </form> <?=$htmlBody?> </body> </html>
範例 2:擷取報表
程式碼範例會呼叫 jobs.list 方法,擷取報表工作清單。接著,路徑會呼叫 reports.list 方法,並將 jobId 參數設為特定工作 ID,以擷取該工作建立的報表。最後,範例會列印每份報表的下載網址。
<?php /** * This sample supports the following use cases: * * 1. Retrieve reporting jobs by content owner: * Ex: php retrieve_reports.php --contentOwner=="CONTENT_OWNER_ID" * Ex: php retrieve_reports.php --contentOwner=="CONTENT_OWNER_ID" --includeSystemManaged==True * 2. Retrieving list of downloadable reports for a particular job: * Ex: php retrieve_reports.php --contentOwner=="CONTENT_OWNER_ID" --jobId="JOB_ID" * 3. Download a report: * Ex: php retrieve_reports.php --contentOwner=="CONTENT_OWNER_ID" --downloadUrl="DOWNLOAD_URL" --outputFile="report.txt" */ /** * Library Requirements * * 1. Install composer (https://getcomposer.org) * 2. On the command line, change to this directory (api-samples/php) * 3. Require the google/apiclient library * $ composer require google/apiclient:~2.0 */ if (!file_exists(__DIR__ . '/vendor/autoload.php')) { throw new \Exception('please run "composer require google/apiclient:~2.2.0" in "' . __DIR__ .'"'); } require_once __DIR__ . '/vendor/autoload.php'; session_start(); define('CREDENTIALS_PATH', '~/.credentials/youtube-php.json'); $longOptions = array( 'contentOwner::', 'downloadUrl::', 'includeSystemManaged::', 'jobId::', 'outputFile::', ); $options = getopt('', $longOptions); $CONTENT_OWNER_ID = ($options['contentOwner'] ? $options['contentOwner'] : ''); $DOWNLOAD_URL = (array_key_exists('downloadUrl', $options) ? $options['downloadUrl'] : ''); $INCLUDE_SYSTEM_MANAGED = (array_key_exists('includeSystemManaged', $options) ? $options['includeSystemManaged'] : ''); $JOB_ID = (array_key_exists('jobId', $options) ? $options['jobId'] : ''); $OUTPUT_FILE = (array_key_exists('outputFile', $options) ? $options['outputFile'] : ''); /* * You can obtain an OAuth 2.0 client ID and client secret from the * {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}> * For more information about using OAuth 2.0 to access Google APIs, please see: * <https://developers.google.com/youtube/v3/guides/authentication> * Please ensure that you have enabled the YouTube Data API for your project. */ function getClient() { $client = new Google_Client(); $client->setAuthConfigFile('client_secrets_php.json'); $client->addScope( 'https://www.googleapis.com/auth/yt-analytics-monetary.readonly'); $client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob'); $client->setAccessType('offline'); // Load previously authorized credentials from a file. $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH); if (file_exists($credentialsPath)) { $accessToken = json_decode(file_get_contents($credentialsPath), true); } else { // Request authorization from the user. $authUrl = $client->createAuthUrl(); printf('Open the following link in your browser:\n%s\n', $authUrl); print 'Enter verification code: '; $authCode = trim(fgets(STDIN)); // Exchange authorization code for an access token. $accessToken = $client->authenticate($authCode); $refreshToken = $client->getRefreshToken(); // Store the credentials to disk. if(!file_exists(dirname($credentialsPath))) { mkdir(dirname($credentialsPath), 0700, true); } file_put_contents($credentialsPath, json_encode($accessToken)); printf('Credentials saved to %s\n', $credentialsPath); //fclose($fp); } $client->setAccessToken($accessToken); // Refresh the token if it's expired. if ($client->isAccessTokenExpired()) { $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); file_put_contents($credentialsPath, json_encode($client->getAccessToken())); } return $client; } /** * Expands the home directory alias '~' to the full path. * @param string $path the path to expand. * @return string the expanded path. */ function expandHomeDirectory($path) { $homeDirectory = getenv('HOME'); if (empty($homeDirectory)) { $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH'); } return str_replace('~', realpath($homeDirectory), $path); } /** * Returns a list of reporting jobs. (jobs.listJobs) * * @param Google_Service_YouTubereporting $youtubeReporting YouTube Reporting service object. * @param string $onBehalfOfContentOwner A content owner ID. */ function listReportingJobs(Google_Service_YouTubeReporting $youtubeReporting, $onBehalfOfContentOwner = '', $includeSystemManaged = False) { $reportingJobs = $youtubeReporting->jobs->listJobs( array('onBehalfOfContentOwner' => $onBehalfOfContentOwner, 'includeSystemManaged' => $includeSystemManaged)); print ('REPORTING JOBS' . PHP_EOL . '**************' . PHP_EOL); foreach ($reportingJobs as $job) { print($job['reportTypeId'] . ':' . $job['id'] . PHP_EOL); } print(PHP_EOL); } /** * Lists reports created by a specific job. (reports.listJobsReports) * * @param Google_Service_YouTubereporting $youtubeReporting YouTube Reporting service object. * @param string $jobId The ID of the job. * @param string $onBehalfOfContentOwner A content owner ID. */ function listReportsForJob(Google_Service_YouTubeReporting $youtubeReporting, $jobId, $onBehalfOfContentOwner = '') { $reports = $youtubeReporting->jobs_reports->listJobsReports($jobId, array('onBehalfOfContentOwner' => $onBehalfOfContentOwner)); print ('DOWNLOADABLE REPORTS' . PHP_EOL . '********************' . PHP_EOL); foreach ($reports['reports'] as $report) { print('Created: ' . date('d M Y', strtotime($report['createTime'])) . ' (' . date('d M Y', strtotime($report['startTime'])) . ' to ' . date('d M Y', strtotime($report['endTime'])) . ')' . PHP_EOL . ' ' . $report['downloadUrl'] . PHP_EOL . PHP_EOL); } } /** * Download the report specified by the URL. (media.download) * * @param Google_Service_YouTubereporting $youtubeReporting YouTube Reporting service object. * @param string $reportUrl The URL of the report to be downloaded. * @param string $outputFile The file to write the report to locally. * @param $htmlBody - html body. */ function downloadReport(Google_Service_YouTubeReporting $youtubeReporting, $reportUrl, $outputFile) { $client = $youtubeReporting->getClient(); // Setting the defer flag to true tells the client to return a request that // can be called with ->execute(); instead of making the API call immediately. $client->setDefer(true); // Call YouTube Reporting API's media.download method to download a report. $request = $youtubeReporting->media->download('', array('alt' => 'media')); $request = $request->withUri(new \GuzzleHttp\Psr7\Uri($reportUrl)); $responseBody = ''; try { $response = $client->execute($request); $responseBody = $response->getBody(); } catch (Google_Service_Exception $e) { $responseBody = $e->getTrace()[0]['args'][0]->getResponseBody(); } file_put_contents($outputFile, $responseBody); $client->setDefer(false); } // Define an object that will be used to make all API requests. $client = getClient(); // YouTube Reporting object used to make YouTube Reporting API requests. $youtubeReporting = new Google_Service_YouTubeReporting($client); if ($CONTENT_OWNER_ID) { if (!$DOWNLOAD_URL && !$JOB_ID) { listReportingJobs($youtubeReporting, $CONTENT_OWNER_ID, $INCLUDE_SYSTEM_MANAGED); } else if ($JOB_ID) { listReportsForJob($youtubeReporting, $JOB_ID, $CONTENT_OWNER_ID); } else if ($DOWNLOAD_URL && $OUTPUT_FILE) { downloadReport($youtubeReporting, $DOWNLOAD_URL, $OUTPUT_FILE); } } ?>
Python
下列範例使用 Python 用戶端程式庫。
範例 1:建立報表工作
下列程式碼範例會呼叫 reportTypes.list 方法,擷取可用報表類型的清單。接著,系統會呼叫 jobs.create 方法來建立新的報表工作。
#!/usr/bin/python # Create a reporting job for the authenticated user's channel or # for a content owner that the user's account is linked to. # Usage example: # python create_reporting_job.py --name='<name>' # python create_reporting_job.py --content-owner='<CONTENT OWNER ID>' # python create_reporting_job.py --content-owner='<CONTENT_OWNER_ID>' --report-type='<REPORT_TYPE_ID>' --name='<REPORT_NAME>' import argparse import os import google.oauth2.credentials import google_auth_oauthlib.flow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from google_auth_oauthlib.flow import InstalledAppFlow # The CLIENT_SECRETS_FILE variable specifies the name of a file that contains # the OAuth 2.0 information for this application, including its client_id and # client_secret. You can acquire an OAuth 2.0 client ID and client secret from # the {{ Google Cloud Console }} at # {{ https://cloud.google.com/console }}. # Please ensure that you have enabled the YouTube Data API for your project. # For more information about using OAuth2 to access the YouTube Data API, see: # https://developers.google.com/youtube/v3/guides/authentication # For more information about the client_secrets.json file format, see: # https://developers.google.com/api-client-library/python/guide/aaa_client_secrets CLIENT_SECRETS_FILE = 'client_secret.json' # This OAuth 2.0 access scope allows for read access to the YouTube Analytics monetary reports for # authenticated user's account. Any request that retrieves earnings or ad performance metrics must # use this scope. SCOPES = ['https://www.googleapis.com/auth/yt-analytics-monetary.readonly'] API_SERVICE_NAME = 'youtubereporting' API_VERSION = 'v1' # Authorize the request and store authorization credentials. def get_authenticated_service(): flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES) credentials = flow.run_console() return build(API_SERVICE_NAME, API_VERSION, credentials = credentials) # Remove keyword arguments that are not set. def remove_empty_kwargs(**kwargs): good_kwargs = {} if kwargs is not None: for key, value in kwargs.iteritems(): if value: good_kwargs[key] = value return good_kwargs # Call the YouTube Reporting API's reportTypes.list method to retrieve report types. def list_report_types(youtube_reporting, **kwargs): # Provide keyword arguments that have values as request parameters. kwargs = remove_empty_kwargs(**kwargs) results = youtube_reporting.reportTypes().list(**kwargs).execute() reportTypes = results['reportTypes'] if 'reportTypes' in results and results['reportTypes']: reportTypes = results['reportTypes'] for reportType in reportTypes: print 'Report type id: %s\n name: %s\n' % (reportType['id'], reportType['name']) else: print 'No report types found' return False return True # Call the YouTube Reporting API's jobs.create method to create a job. def create_reporting_job(youtube_reporting, report_type_id, **kwargs): # Provide keyword arguments that have values as request parameters. kwargs = remove_empty_kwargs(**kwargs) reporting_job = youtube_reporting.jobs().create( body=dict( reportTypeId=args.report_type, name=args.name ), **kwargs ).execute() print ('Reporting job "%s" created for reporting type "%s" at "%s"' % (reporting_job['name'], reporting_job['reportTypeId'], reporting_job['createTime'])) # Prompt the user to enter a report type id for the job. Then return the id. def get_report_type_id_from_user(): report_type_id = raw_input('Please enter the reportTypeId for the job: ') print ('You chose "%s" as the report type Id for the job.' % report_type_id) return report_type_id # Prompt the user to set a job name def prompt_user_to_set_job_name(): job_name = raw_input('Please set a name for the job: ') print ('Great! "%s" is a memorable name for this job.' % job_name) return job_name if __name__ == '__main__': parser = argparse.ArgumentParser() # The 'name' option specifies the name that will be used for the reporting job. parser.add_argument('--content-owner', default='', help='ID of content owner for which you are retrieving jobs and reports.') parser.add_argument('--include-system-managed', default=False, help='Whether the API response should include system-managed reports') parser.add_argument('--name', default='', help='Name for the reporting job. The script prompts you to set a name ' + 'for the job if you do not provide one using this argument.') parser.add_argument('--report-type', default=None, help='The type of report for which you are creating a job.') args = parser.parse_args() youtube_reporting = get_authenticated_service() try: # Prompt user to select report type if they didn't set one on command line. if not args.report_type: if list_report_types(youtube_reporting, onBehalfOfContentOwner=args.content_owner, includeSystemManaged=args.include_system_managed): args.report_type = get_report_type_id_from_user() # Prompt user to set job name if not set on command line. if not args.name: args.name = prompt_user_to_set_job_name() # Create the job. if args.report_type: create_reporting_job(youtube_reporting, args, onBehalfOfContentOwner=args.content_owner) except HttpError, e: print 'An HTTP error %d occurred:\n%s' % (e.resp.status, e.content)
範例 2:擷取報表
程式碼範例會呼叫 jobs.list 方法,擷取報表工作清單。接著,路徑會呼叫 reports.list 方法,並將 jobId 參數設為特定工作 ID,以擷取該工作建立的報表。最後,範例會列印每份報表的下載網址。
#!/usr/bin/python ### # # This script retrieves YouTube Reporting API reports. Use cases: # 1. If you specify a report URL, the script downloads that report. # 2. Otherwise, if you specify a job ID, the script retrieves a list of # available reports for that job and prompts you to select a report. # Then it retrieves that report as in case 1. # 3. Otherwise, the list retrieves a list of jobs for the user or, # if specified, the content owner that the user is acting on behalf of. # Then it prompts the user to select a job, and then executes case 2 and # then case 1. # Usage examples: # python retrieve_reports.py --content_owner_id=<CONTENT_OWNER_ID> --local_file=<LOCAL_FILE> # python retrieve_reports.py --content_owner_id=<CONTENT_OWNER_ID> --job_id=<JOB_ID> --local_file=<LOCAL_FILE> # python retrieve_reports.py --content_owner_id=<CONTENT_OWNER_ID> --report_url=<REPORT_URL> --local_file=<LOCAL_FILE> # ### import argparse import os import google.oauth2.credentials import google_auth_oauthlib.flow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaIoBaseDownload from google_auth_oauthlib.flow import InstalledAppFlow from io import FileIO # The CLIENT_SECRETS_FILE variable specifies the name of a file that contains # the OAuth 2.0 information for this application, including its client_id and # client_secret. You can acquire an OAuth 2.0 client ID and client secret from # the {{ Google Cloud Console }} at # {{ https://cloud.google.com/console }}. # Please ensure that you have enabled the YouTube Data API for your project. # For more information about using OAuth2 to access the YouTube Data API, see: # https://developers.google.com/youtube/v3/guides/authentication # For more information about the client_secrets.json file format, see: # https://developers.google.com/api-client-library/python/guide/aaa_client_secrets CLIENT_SECRETS_FILE = 'client_secret.json' # This OAuth 2.0 access scope allows for read access to YouTube Analytics # monetary reports for the authenticated user's account. Any request that # retrieves earnings or ad performance metrics must use this scope. SCOPES = ['https://www.googleapis.com/auth/yt-analytics-monetary.readonly'] API_SERVICE_NAME = 'youtubereporting' API_VERSION = 'v1' # Authorize the request and store authorization credentials. def get_authenticated_service(): flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES) credentials = flow.run_console() return build(API_SERVICE_NAME, API_VERSION, credentials = credentials) # Remove keyword arguments that are not set. def remove_empty_kwargs(**kwargs): good_kwargs = {} if kwargs is not None: for key, value in kwargs.iteritems(): if value: good_kwargs[key] = value return good_kwargs # Call the YouTube Reporting API's jobs.list method to retrieve reporting jobs. def list_reporting_jobs(youtube_reporting, **kwargs): # Only include the onBehalfOfContentOwner keyword argument if the user # set a value for the --content_owner argument. kwargs = remove_empty_kwargs(**kwargs) # Retrieve the reporting jobs for the user (or content owner). results = youtube_reporting.jobs().list(**kwargs).execute() if 'jobs' in results and results['jobs']: jobs = results['jobs'] for job in jobs: print ('Reporting job id: %s\n name: %s\n for reporting type: %s\n' % (job['id'], job['name'], job['reportTypeId'])) else: print 'No jobs found' return False return True # Call the YouTube Reporting API's reports.list method to retrieve reports created by a job. def retrieve_reports(youtube_reporting, **kwargs): # Only include the onBehalfOfContentOwner keyword argument if the user # set a value for the --content_owner argument. kwargs = remove_empty_kwargs(**kwargs) # Retrieve available reports for the selected job. results = youtube_reporting.jobs().reports().list( **kwargs ).execute() if 'reports' in results and results['reports']: reports = results['reports'] for report in reports: print ('Report dates: %s to %s\n download URL: %s\n' % (report['startTime'], report['endTime'], report['downloadUrl'])) # Call the YouTube Reporting API's media.download method to download the report. def download_report(youtube_reporting, report_url, local_file): request = youtube_reporting.media().download( resourceName=' ' ) request.uri = report_url fh = FileIO(local_file, mode='wb') # Stream/download the report in a single request. downloader = MediaIoBaseDownload(fh, request, chunksize=-1) done = False while done is False: status, done = downloader.next_chunk() if status: print 'Download %d%%.' % int(status.progress() * 100) print 'Download Complete!' # Prompt the user to select a job and return the specified ID. def get_job_id_from_user(): job_id = raw_input('Please enter the job id for the report retrieval: ') print ('You chose "%s" as the job Id for the report retrieval.' % job_id) return job_id # Prompt the user to select a report URL and return the specified URL. def get_report_url_from_user(): report_url = raw_input('Please enter the report URL to download: ') print ('You chose "%s" to download.' % report_url) return report_url if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--content_owner', default='', help='ID of content owner for which you are retrieving jobs and reports') parser.add_argument('--job_id', default=None, help='ID of the job for which you are retrieving reports. If not ' + 'provided AND report_url is also not provided, then the script ' + 'calls jobs.list() to retrieve a list of jobs.') parser.add_argument('--report_url', default=None, help='URL of the report to retrieve. If not specified, the script ' + 'calls reports.list() to retrieve a list of reports for the ' + 'selected job.') parser.add_argument('--local_file', default='yt_report.txt', help='The name of the local file where the downloaded report will be written.') args = parser.parse_args() youtube_reporting = get_authenticated_service() try: # If the user has not specified a job ID or report URL, retrieve a list # of available jobs and prompt the user to select one. if not args.job_id and not args.report_url: if list_reporting_jobs(youtube_reporting, onBehalfOfContentOwner=args.content_owner): args.job_id = get_job_id_from_user() # If the user has not specified a report URL, retrieve a list of reports # available for the specified job and prompt the user to select one. if args.job_id and not args.report_url: retrieve_reports(youtube_reporting, jobId=args.job_id, onBehalfOfContentOwner=args.content_owner) args.report_url = get_report_url_from_user() # Download the selected report. if args.report_url: download_report(youtube_reporting, args.report_url, args.local_file) except HttpError, e: print 'An HTTP error %d occurred:\n%s' % (e.resp.status, e.content)