Method jobs.reports.list

Lists reports that have been generated for the specified reporting job.

Request

HTTP request

GET https://youtubereporting.googleapis.com/v1/jobs/{jobId}/reports

Authorization

All YouTube Reporting API requests must be authorized. The Authorization guide explains how to use the OAuth 2.0 protocol to retrieve authorization tokens.

YouTube Reporting API requests use the following authorization scopes:

Scopes
https://www.googleapis.com/auth/yt-analytics.readonly View YouTube Analytics reports for your YouTube content. This scope provides access to user activity metrics, like view counts and rating counts.
https://www.googleapis.com/auth/yt-analytics-monetary.readonly View YouTube Analytics monetary reports for your YouTube content. This scope provides access to user activity metrics and to estimated revenue and ad performance metrics.

Parameters

Path parameters

Parameters
jobId string
The ID that YouTube uses to uniquely identify the job for which reports are being listed.

Query parameters

Parameters
createdAfter timestamp
If specified, this parameter indicates that the API response should only contain reports created after the specified date and time, including new reports with backfilled data. Note that the value pertains to the time that the report is created and not the dates associated with the returned data.

The value is a timestamp in RFC3339 UTC "Zulu" format, accurate to microseconds. Example: "2015-10-02T15:01:23.045678Z".
onBehalfOfContentOwner string
The ID of the content owner for whom the API request is being made. If the request does not specify a value for this parameter, the API server assumes that the request is being made for the user's own channel.
pageSize number
The requested page size. If no value is specified, the API server chooses an appropriate default.

Note that the server may return fewer report types than requested.
pageToken string
A token identifying a page of results that the server should return. Typically, this is the value of the nextPageToken property returned in response to the previous call to the jobs.reports.list method.
startTimeAtOrAfter timestamp
This parameter indicates that the API response should only contain reports if the earliest data in the report is on or after the specified date. Whereas the createdAfter parameter value pertains to the time the report was created, this date pertains to the data in the report.

The value is a timestamp in RFC3339 UTC "Zulu" format, accurate to microseconds. Example: "2015-10-02T15:01:23.045678Z".
startTimeBefore timestamp
This parameter indicates that the API response should only contain reports if the earliest data in the report is before the specified date. Whereas the createdAfter parameter value pertains to the time the report was created, this date pertains to the data in the report.

The value is a timestamp in RFC3339 UTC "Zulu" format, accurate to microseconds. Example: "2015-10-02T15:01:23.045678Z".

Request body

The request body must be empty.

Response

If successful, the response body contains data with the following structure:

{
  "reports": [
    Report resource
  ],
  "nextPageToken": string
}

This method returns a 404 (NOT FOUND) HTTP response code if the specified job does not exist.

If the API response contains a value for this property, then additional reports are available for the specified job. To retrieve those reports, submit an additional jobs.reports.list request, setting the pageToken parameter value to this value.
Properties
reports[] list
The list of reports that have been generated for the specified jobId. Each item in the list is a report resource.
nextPageToken string
A token to retrieve next page of results. Pass this value in the ListReportsRequest.page_token field in the subsequent call to ListReports method to retrieve the next page of results.

Examples

Note: The code samples below may not represent all supported programming languages. See the client libraries documentation for a list of supported languages.

Java

The sample below uses the Java client library.

This code sample calls the jobs.list method to retrieve a list of reporting jobs. It then calls the reports.list method with the jobId parameter set to a specific job id to retrieve reports created by that job. Finally, the sample prints out the download URL for each report.

/*
 * 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.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

The sample below uses the PHP client library.

This code sample calls the jobs.list method to retrieve a list of reporting jobs. It then calls the reports.list method with the jobId parameter set to a specific job id to retrieve reports created by that job. Finally, the sample prints out the download URL for each report.

<?php

/**
 * 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
 */

// Call set_include_path() as needed to point to your client library.
require_once 'Google/Client.php';
require_once 'Google/Service/YouTubeReporting.php';
session_start();


/*
 * You can acquire an OAuth 2.0 client ID and client secret from the
 * Google Developers Console <https://console.developers.google.com/>
 * 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 full read/write access to the
 * authenticated user's account.
 */
$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);

if (isset($_GET['code'])) {
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die('The session state did not match.');
  }

  $client->authenticate($_GET['code']);
  $_SESSION['token'] = $client->getAccessToken();
  header('Location: ' . $redirect);
}

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}

// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
  try {
    if (empty(listReportingJobs($youtubeReporting, $htmlBody))) {
      $htmlBody .= sprintf('<p>No jobs found.</p>');
    } else if ($_GET['reportUrl']){
      downloadReport($youtubeReporting, $_GET['reportUrl'], $htmlBody);
    } else if ($_GET['jobId']){
      retrieveReports($youtubeReporting, $_GET['jobId'], $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['token'] = $client->getAccessToken();
} 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;
}


/**
 * Returns a list of reporting jobs. (jobs.listJobs)
 *
 * @param Google_Service_YouTubereporting $youtubeReporting YouTube Reporting service object.
 * @param $htmlBody - html body.
 */
function listReportingJobs(Google_Service_YouTubeReporting $youtubeReporting, &$htmlBody) {
  // Call the YouTube Reporting API's jobs.list method to retrieve reporting jobs.
  $reportingJobs = $youtubeReporting->jobs->listJobs();

  $htmlBody .= "<h3>Reporting Jobs</h3><ul>";
  foreach ($reportingJobs as $job) {
    $htmlBody .= sprintf('<li>id: "%s", name: "%s" report type: "%s"</li>', $job['id'],
        $job['name'], $job['reportTypeId']);
  }
  $htmlBody .= '</ul>';

  return $reportingJobs;
}


/**
 * 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 $htmlBody - html body.
 */
function retrieveReports(Google_Service_YouTubeReporting $youtubeReporting, $jobId, &$htmlBody) {
  // Call the YouTube Reporting API's reports.list method to retrieve reports created by a job.
  $reports = $youtubeReporting->jobs_reports->listJobsReports($jobId);

  if (empty($reports)) {
    $htmlBody .= sprintf('<p>No reports found.</p>');
  } else {
    $htmlBody .= sprintf('<h2>Reports for the job "%s"</h2><ul>', $jobId);
    foreach ($reports as $report) {
      $htmlBody .= sprintf('<li>From "%s" to "%s" downloadable at "%s"</li>',
          $report['startTime'], $report['endTime'], $report['downloadUrl']);
      $htmlBody .= '</ul>';
    }
  }
}


/**
 * 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 $htmlBody - html body.
 */
function downloadReport(Google_Service_YouTubeReporting $youtubeReporting, $reportUrl, &$htmlBody) {
  $client = $youtubeReporting->getClient();
  // Setting the defer flag to true tells the client to return a request which can be called
  // with ->execute(); instead of making the API call immediately.
  $client->setDefer(true);

  // Call the YouTube Reporting API's media.download method to download a report.
  $request = $youtubeReporting->media->download("");
  $request->setUrl($reportUrl);
  $response = $client->execute($request);

  file_put_contents("reportFile", $response->getResponseBody());
  $client->setDefer(false);
}
?>

<!doctype html>
<html>
<head>
<title>Retrieve reports</title>
</head>
<body>
  <form method="GET">
    <div>
      Job Id: <input type="text" id="jobId" name="jobId" placeholder="Enter Job Id">
    </div>
    <br>
    <div>
      Report URL: <input type="text" id="reportUrl" name="reportUrl" placeholder="Enter Report Url">
    </div>
    <br>    <input type="submit" value="Retrieve!">
  </form>
  <?=$htmlBody?>
</body>
</html>

Python

The sample below uses the Python client library.

This code sample calls the jobs.list method to retrieve a list of reporting jobs. It then calls the reports.list method with the jobId parameter set to a specific job id to retrieve reports created by that job. Finally, the sample prints out the download URL for each report.

#!/usr/bin/python

# Usage example:
# python retrieve_reports.py

import httplib2
import os
import sys

from apiclient.discovery import build
from apiclient.errors import HttpError
from apiclient.http import MediaIoBaseDownload
from io import FileIO
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow


# 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 Developers Console at
# https://console.developers.google.com/.
# 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_secrets.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.
YOUTUBE_ANALYTICS_MONETARY_READ_SCOPE = (
  "https://www.googleapis.com/auth/yt-analytics-monetary.readonly")
YOUTUBE_REPORTING_API_SERVICE_NAME = "youtubereporting"
YOUTUBE_REPORTING_API_VERSION = "v1"

# This variable defines a message to display if the CLIENT_SECRETS_FILE is
# missing.
MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0

To make this sample run you will need to populate the client_secrets.json file
found at:
   %s
with information from the APIs Console
https://console.developers.google.com

For more information about the client_secrets.json file format, please visit:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
                                   CLIENT_SECRETS_FILE))

# Authorize the request and store authorization credentials.
def get_authenticated_service(args):
  flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_ANALYTICS_MONETARY_READ_SCOPE,
    message=MISSING_CLIENT_SECRETS_MESSAGE)

  storage = Storage("%s-oauth2.json" % sys.argv[0])
  credentials = storage.get()

  if credentials is None or credentials.invalid:
    credentials = run_flow(flow, storage, args)

  return build(YOUTUBE_REPORTING_API_SERVICE_NAME, YOUTUBE_REPORTING_API_VERSION,
    http=credentials.authorize(httplib2.Http()))


# Call the YouTube Reporting API's jobs.list method to retrieve reporting jobs.
def list_reporting_jobs(youtube_reporting):
  results = youtube_reporting.jobs().list(
  ).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, job_id):
  results = youtube_reporting.jobs().reports().list(
    jobId=job_id
  ).execute()

  if "reports" in results and results["reports"]:
    reports = results["reports"]
    for report in reports:
      print ("Report from '%s' to '%s' downloadable at '%s'"
        % (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):
  request = youtube_reporting.media().download(
    resourceName=""
  )
  request.uri = report_url
  fh = FileIO('report', 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 enter a job id for report retrieval. Then return the 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 enter a report URL for download. Then return the 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__":
  args = argparser.parse_args()

  youtube_reporting = get_authenticated_service(args)
  try:
    if list_reporting_jobs(youtube_reporting):
      retrieve_reports(youtube_reporting, get_job_id_from_user())
      download_report(youtube_reporting, get_report_url_from_user())
  except HttpError, e:
    print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
  else:
    print "Retrieved reports."

Try it!