Method jobs.create

建立報表工作。建立報表工作後,YouTube 就會每天產生報表。工作建立後 24 小時內,您就能查看報表。

要求

HTTP 要求

POST https://youtubereporting.googleapis.com/v1/jobs

授權

所有 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 數據分析金額報表。這個範圍可存取使用者活動指標,以及預估收益和廣告成效指標。

參數

查詢參數

參數
onBehalfOfContentOwner string
要為其發出 API 要求的內容擁有者 ID。如果要求未指定這個參數的值,API 伺服器會假設要求是為使用者自己的頻道提出。

要求主體

要求主體包含 Job 資源,可為 reportTypeId 和 name 屬性設定值。

回應

成功

回應主體包含 Job 資源。

錯誤

  • Bad Request (400)
    • 要求未指定 job 資源的 name 屬性值。
    • 要求未指定 job 資源的 reportTypeId 屬性值。
    • 要求中指定的 reportTypeId 不存在。
    • 這項要求嘗試為已淘汰的報表類型建立工作。
  • Forbidden (403)
    • 這項要求嘗試為系統管理的報表建立工作。YouTube 會自動產生系統管理的報表,內容擁有者無法修改或刪除建立這些報表的工作。
  • Conflict (409)
    • 要求嘗試建立已存在的工作。

範例

注意:下列程式碼範例可能未涵蓋所有支援的程式設計語言。如需支援的語言清單,請參閱用戶端程式庫說明文件。

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
       <  * us>e this scope.
         */
        ListString 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.
        ListRe<portTypesR>esponse reportTypesListResponse = youtubeReporting.reportTypes().list()
            .execute();
        ListReportType 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 = "";

  "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;
    }
}
CreateReportingJob.java

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();

/*
{{ Google Cloud Console } *<{{ https://cloud.google.com/console } >You can acquire an OAuth 2.0 client ID and client secret from the
 * } }
 * For more <information about using OAuth 2.0 to access Google APIs, pleas>e 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_M>E';

$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 re>quest that retrieves earnings or ad performance metrics must
 * use this scope.
 */
$client-setScopes('https://www.googleapis.com/auth/yt-analytics-monetary.readonly');
$redirect = fil>ter_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[>9;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 t<h>e form
  // and submit<s >the form. Otherwise, the page displays the form above.
  try {
    if (empty(listReportTypes($youtubeReporting, $htmlBody))) {
      $htmlBody .= sprintf('pNo report types found./p');
    } else if ($_GET[<&>#39;reportTypeId']){
 <    > c<reate><Re>portingJob($youtubeReporting, $>_GET['reportTypeId'], $_GET['jobName'], $htmlBody);
    }
 < >} catch (Google_Service_Ex<cept>io<n $e)>< {>
    $htmlBody = sprintf('p>A service error occurred: code%s/code/p',
        htmlsp>ecialchars($e-getMessage()));
  } catch (Google_Exception $e) {
    $htmlBody =<<< sprin<tf>('pAn client error occu<rre>d: <c>ode%s/code/p',
  <    >  htmlspecialchars<($e-g>etMessage<()))>;
  }
  $_SESSION[<$toke>nSessionKey] = $client<->getAccessToken();
} elseif ($OAUTH2_CLIENT_ID == 'REPLACE_ME') {
  $htmlBody = END
  h3Client Credentials R>equired/h3
  p
    You need to set code\$OAUTH2_CLIENT_ID/code and
    >code\$OAUTH2_CLIENT_ID/code bef<<<ore pr<oc>eeding.
  p
END;
} els<e {>
  </>/ If the use<r hasn't auth>orized the app, <in>itiate the OAuth fl<o>w
  $state = mt_rand();
  $client-setState($state);
  $_SESSION['state'] = $state;

  $authUrl = $client-createAuthUrl();
  $htmlBody = END
  h3Authorization Required/h3
  pYou 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.<>/span>
  $reportingJob = new Google_Service_You<Tu>beReporting_Job();
  <$re><po>rtingJob-setReportTypeId($r<ep>ortTypeId);
  $reportingJob-setName(<$na>me);

  // Call the YouTube Reporting API's jobs.create method to create a job.
  $jobCreateResponse = $youtubeReporting<-jo>bs-create($reportingJob);

  $htmlBody .= "h2Created reporting job/h2ul";
  $htmlBody .= sprintf('li"%s" for reporting type "%s" at "%s"/li',
      $jobCreateResponse['name'], $jobCreateResponse['reportTypeId'], $jobCreate&Response['createTime']);
  $htmlBody .= '/ul';
}


/**
 * Returns a list of report types. (reportTypes.listReportTypes)
> *
 * @param> Google_Service_YouTubereporting $yo<ut>ubeReporting< Yo><uT>ube Reporting service object.
 * @param $htmlBody - html body.
 */
func<ti>on listReportTypes(G<oog>le_Service_YouTubeReporting $youtubeReporting, $htmlBody) {
  //< Ca>ll the YouTube Reporting API&#>39<;s reportType>s<.lis>t< met>h<od to> retrieve report types<.
  $r>e<portT>y<pes >= $<youtubeReporting->repor<tTy>pes-listReportTyp<es();

  $htmlBody .= "h3Report Types/h3ul";
  foreach ($reportT>ypes <as $>repor<tT>ype) <{
 >   $htmlBody .= sprintf<('liid: "%s", name: "%s"/li', $reportType['id'], $repo>rtTyp<e[&#>39;na<me>'<]);
  }
  $htmlBody .= '/ul'>;;
<
  re>tur<n $reportTyp>e<s;
}
>?<

!do>ceCreate 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
create_reporting_job.php

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 <--na>me='name'
# python create_reporting_job.py -<-content-owner=&>#39;CONTENT OWNER ID'
# python create_reporting_<job.py --content>-owner='CONTE<NT_OWNER_ID>9; --repor<t-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 O{{ Google Cloud Console }Auth 2.{{ https://cloud.google.com/console }0 client ID and client secret from
# the } at
# }.
# 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  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)
create_reporting_job.py

試試看!