מחזירה רשימה של סוגי דוחות שהערוץ או בעלי התוכן יכולים לאחזר. כל פריט ברשימה מכיל נכס id
שמזהה את מזהה הדוח, וצריך להשתמש בערך הזה כדי לתזמן משימת דיווח.
בקשה
בקשת HTTP
GET https://youtubereporting.googleapis.com/v1/reportTypes
פרמטרים
פרמטרים של שאילתה
פרמטרים | |
---|---|
onBehalfOfContentOwner |
string המזהה של בעלי התוכן שעבורם נשלחת בקשת ה-API. אם הבקשה לא מציינת ערך לפרמטר הזה, שרת ה-API מניח שהבקשה נשלחת עבור הערוץ של המשתמש עצמו. |
pageSize |
number גודל הדף המבוקש. אם לא צוין ערך, שרת ה-API יבחר ברירת מחדל מתאימה. לתשומת ליבך, השרת עשוי להחזיר פחות סוגי דוחות ממה שנדרש. |
pageToken |
string אסימון שמזהה דף תוצאות שהשרת צריך להחזיר. בדרך כלל, זהו הערך של המאפיין nextPageToken שהוחזר בתגובה לקריאה הקודמת ל-method reportTypes.list . |
includeSystemManaged |
boolean יש להגדיר את ערך הפרמטר ל- true כדי לציין שתגובת ה-API תציג דוחות בניהול המערכת.מערכת YouTube יוצרת באופן אוטומטי דוחות בניהול המערכת עבור בעלי התוכן ב-YouTube שיש להם גישה לאותם דוחות בתפריט הדוחות. דוחות בניהול המערכת זמינים רק לחלק מבעלי התוכן. בעלי התוכן לא צריכים לקרוא לשיטה jobs.create כדי להורות ל-YouTube להתחיל ליצור את הדוחות האלה, והשיטה הזו מחזירה שגיאה אם הנכס reportTypeId מזהה דוח שמנוהל על ידי מערכת.ערך ברירת המחדל של הפרמטר הוא false . |
גוף הבקשה
אין לספק גוף בקשה כשמבצעים קריאה ל-method הזה.
תשובה
אם הפעולה בוצעה ללא שגיאות, השיטה הזו מחזירה גוף תגובה עם המבנה הבא:
{ "reportTypes": [ ReportType resource ], "nextPageToken": string }
מאפיינים
הטבלה הבאה מגדירה את המאפיינים שמופיעים בתגובה הזו:
מאפיינים | |
---|---|
reportTypes[] |
list רשימה של סוגי דוחות שבעלי התוכן או בעלי התוכן יכולים לאחזר את הנתונים של בקשת ה-API. כל פריט ברשימה הוא משאב reportType . |
nextPageToken |
string אם תגובת ה-API מכילה ערך בשביל הנכס הזה, יהיו סוגי דוחות נוספים שזמינים לערוץ או לבעלי התוכן המשויכים. כדי לאחזר את סוגי הדוחות האלה, צריך לשלוח בקשת reportTypes.list נוספת, ולהגדיר את ערך הפרמטר pageToken כערך הזה. |
דוגמאות
הערה: יכול להיות שדוגמאות הקוד הבאות לא מייצגות את כל שפות התכנות הנתמכות. רשימת השפות הנתמכות זמינה במסמך בנושא ספריות לקוח.
Java
הדוגמה הבאה משתמשת בספריית הלקוח של Java.
הדוגמה הזו ממחישה איך ליצור משימת דיווח. היא מפעילה את השיטה 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; } }
PHP
הדוגמה הבאה משתמשת בספריית הלקוח של PHP.
הדוגמה הזו ממחישה איך ליצור משימת דיווח. היא מפעילה את השיטה 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>
Python
הדוגמה הבאה משתמשת בספריית הלקוח של Python.
הדוגמה הזו ממחישה איך ליצור משימת דיווח. היא מפעילה את השיטה 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)