YouTube Reporting API - Data Model

Importante: Los informes diarios de la API y los informes de reabastecimiento están disponibles durante 60 días desde la fecha en que se generan. Los informes de datos históricos están disponibles durante 30 días desde la fecha en que se generan.

Esta política se aplica a nivel global a todos los informes y trabajos de informes. Para obtener más información, consulta el historial de revisión de la API de informes de YouTube.

La API de informes de YouTube admite informes predefinidos que contienen un conjunto completo de datos de YouTube Analytics sobre un canal o propietario del contenido. Estos informes te permiten descargar los conjuntos de datos masivos que puedes consultar con la API de YouTube Analytics o en la sección Analytics de Creator Studio.

La API también admite un conjunto de informes generados automáticamente y administrados por el sistema que están disponibles para los propietarios de contenido que tienen acceso a los informes correspondientes en el menú Informes. Esos informes contienen datos de ingresos publicitarios y de suscripciones a YouTube Premium. Consulta la documentación de informes administrados por el sistema para obtener más información.

Descripción general

Los campos de estos informes se caracterizan como dimensiones o métricas:

  • Dimensiones: criterios comunes que se utilizan para recopilar datos, como la fecha en que se produjo una acción o el país donde se encuentran los usuarios. En un informe, cada fila de datos tiene una combinación única de valores de dimensiones.
  • Las métricas son mediciones individuales relacionadas con la actividad del usuario, el rendimiento de los anuncios o los ingresos estimados. Las métricas de actividad del usuario incluyen aspectos como el recuento de vistas y las calificaciones (me gusta y no me gusta).

A modo de ejemplo, el informe básico de actividad del usuario de los canales contiene las siguientes dimensiones:

  • day: Es la fecha en la que se produjo la actividad.
  • channel: Es el canal de YouTube asociado con la actividad.
  • video: El video de YouTube asociado con la actividad.
  • liveOrOnDemand: Un valor que indica si los usuarios estaban mirando una transmisión de video en vivo.
  • subscribedStatus: un valor que indica si los usuarios estaban suscritos al canal.
  • country: Es el país donde se encuentran los usuarios.

El informe también contiene muchas métricas, como las vistas, los me gusta y averageViewDuration. Después de recuperar e importar el informe, una aplicación puede realizar muchos cálculos diferentes en función de valores de dimensiones comunes.

Por ejemplo, para calcular la cantidad total de vistas en Alemania en una fecha específica, suma los valores de la métrica vistas en todas las filas en las que el valor de la columna country es DE y el valor de la columna day es la fecha en formato YYYY-MM-DD.

Cómo recuperar informes de YouTube Analytics

Los siguientes pasos explican cómo recuperar informes de propietarios de contenido y canales a través de la API. Consulta la documentación de informes administrados por el sistema para obtener instrucciones sobre cómo recuperar esos informes.

Paso 1: Recupera las credenciales de autorización

Se deben autorizar todas las solicitudes a la API de informes de YouTube. La guía de autorización explica cómo usar el protocolo OAuth 2.0 para recuperar tokens de autorización.

Las solicitudes a la API de informes de YouTube usan los siguientes alcances de autorización:

Permisos
https://www.googleapis.com/auth/yt-analytics.readonly Permite ver informes de YouTube Analytics sobre tu contenido de YouTube. Este alcance proporciona acceso a las métricas de actividad del usuario, como el número de reproducciones y de calificaciones.
https://www.googleapis.com/auth/yt-analytics-monetary.readonly Permite ver informes monetarios de YouTube Analytics sobre tu contenido de YouTube. Este permiso proporciona acceso a las métricas de actividad del usuario, así como a las métricas estimadas de ingresos y rendimiento de los anuncios.

Paso 2: Identifica el informe que deseas recuperar

Invoca el método reportTypes.list de la API para recuperar una lista de informes que se pueden generar para el canal o el propietario del contenido. El método devuelve una lista de IDs y nombres de informes. Captura el valor de la propiedad id para los informes que deseas generar. Por ejemplo, el ID del informe básico de actividad del usuario para canales es channel_basic_a1.

También puedes encontrar los nombres de los informes en la documentación que define los informes de canales y los informes de propietarios de contenido admitidos.

Paso 3: Crea un trabajo de informe

YouTube no comenzará a generar tu informe hasta que crees un trabajo de informe para ese informe. (Por lo tanto, los informes solo se generan para los canales y los propietarios del contenido que realmente desean recuperarlos).

Para crear un trabajo de informes, llama al método jobs.create de la API. Configura los siguientes valores en el cuerpo de la solicitud:

  • Establece el valor de la propiedad reportTypeId en el ID de informe que recuperaste en el paso 2.
  • Establece el valor de la propiedad name con el nombre que deseas asociar con el informe.

La respuesta de la API al método jobs.create contiene un recurso Job, que especifica el ID que identifica el trabajo de forma única. Puedes comenzar a recuperar el informe dentro de las 48 horas posteriores a la creación del trabajo, y el primer informe disponible será para el día en que programaste el trabajo.

Por ejemplo, si programas un trabajo el 1 de septiembre, el informe del 1 de septiembre estará listo el 3 de septiembre. El informe del 2 de septiembre se publicará el 4 de septiembre, y así sucesivamente.

Paso 4: Recupera el ID de trabajo

Nota: Si tu aplicación almacenó el ID de tarea que se mostró en el paso 3, puedes omitir este paso.

Llama al método jobs.list para recuperar una lista de trabajos programados. La propiedad reportTypeId en cada recurso Job que se muestra identifica el tipo de informe que genera ese trabajo. Tu aplicación necesita el valor de la propiedad id del mismo recurso en el siguiente paso.

Paso 5: Recupere la URL de descarga del informe

Llama al método jobs.reports.list para recuperar una lista de informes creados para el trabajo. En la solicitud, establece el parámetro jobId en el ID de tarea del informe que deseas recuperar.

Sugerencia: Usa el parámetro createdAfter para indicar que la API solo debe mostrar los informes creados después de un período especificado. Este parámetro puede usarse para garantizar que la API solo muestre informes que aún no hayas procesado.

La respuesta de la API contiene una lista de recursos Report para ese trabajo. Cada recurso hace referencia a un informe que contiene datos de un período único de 24 horas. Ten en cuenta que YouTube genera informes descargables para los días en los que no había datos disponibles. Esos informes contienen una fila de encabezado, pero no contienen datos adicionales.

  • Las propiedades startTime y endTime del recurso identifican el período que abarcan los datos del informe.
  • La propiedad downloadUrl del recurso identifica la URL desde la cual se puede recuperar el informe.
  • La propiedad createTime del recurso especifica la fecha y hora en que se generó el informe. La aplicación debe almacenar este valor y utilizarlo para determinar si cambiaron los informes descargados anteriormente.

Paso 6: Descarga el informe

Envía una solicitud GET HTTP al downloadUrl obtenido en el paso 5 para recuperar el informe.

Si quieres reducir el ancho de banda necesario para descargar informes, habilita la compresión gzip en las solicitudes de descarga. Aunque tu aplicación va a necesitar tiempo adicional de CPU para descomprimir las respuestas de la API, el beneficio de consumir menos recursos de red suele ser mayor que el costo.

Para recibir una respuesta codificada en gzip, configura el encabezado de la solicitud HTTP Accept-Encoding como gzip, como se muestra en el siguiente ejemplo:

Accept-Encoding: gzip

Procesamiento de informes

Prácticas recomendadas

Las aplicaciones que usan la API de informes de YouTube siempre deben seguir estas prácticas:

  • Utiliza la fila de encabezado de un informe para determinar el orden de las columnas del informe. Por ejemplo, no des por sentado que las vistas serán la primera métrica que se mostrará en un informe solo porque sea la primera que aparezca en la descripción de un informe. En su lugar, utiliza la fila de encabezado del informe para determinar qué columna contiene esos datos.

  • Lleve un registro de los informes que ha descargado para evitar que el mismo informe se procese de forma reiterada. En la siguiente lista, se sugieren algunas formas de hacerlo.

    • Cuando llames al método reports.list, usa el parámetro createdAfter para recuperar solo los informes creados después de una fecha determinada. (Omite el parámetro createdAfter la primera vez que recuperes informes).

      Cada vez que recuperes y proceses informes correctamente, almacena la marca de tiempo correspondiente a la fecha y hora en la que se creó el más reciente de esos informes. Luego, actualiza el valor del parámetro createdAfter en cada llamada sucesiva al método reports.list para asegurarte de recuperar solo informes nuevos, incluidos los informes nuevos con datos reabastecidos, cada vez que llames a la API.

      Como protección, antes de recuperar un informe, asegúrate también de que el ID del informe no aparezca en tu base de datos.

    • Almacena el ID de cada informe que hayas descargado y procesado. También puedes almacenar información adicional, como la fecha y hora en la que se generó cada informe o la startTime y la endTime del informe, que juntos identifican el período para el cual el informe contiene datos. Ten en cuenta que es probable que cada trabajo tenga muchos informes, ya que cada uno contiene datos para un período de 24 horas.

      Usa el ID de informe para identificar los informes que aún debes descargar e importar. Sin embargo, si dos informes nuevos tienen los mismos valores de propiedad startTime y endTime, solo importa el informe con el valor createTime más reciente.

  • Los informes contienen ID asociados con los recursos de YouTube, y puedes usar la API de datos de YouTube para recuperar metadatos adicionales de esos recursos. Como se indica en las Políticas para Desarrolladores de los Servicios de la API de YouTube (artículos III.E.4.b a III.E.4.d), los clientes de la API deben borrar o actualizar los metadatos de recursos almacenados de la API después de 30 días.

Características del informe

Los informes de la API son archivos con versiones de .csv (valores separados por coma) que tienen las siguientes características:

  • Cada informe contiene datos para un período único de 24 horas que dura desde las 12:00 a.m. hasta las 11:59 p.m., hora del Pacífico. Por lo tanto, en cualquier informe determinado, el valor de la dimensión día es siempre el mismo.

  • Los informes se actualizan diariamente.

  • YouTube genera informes descargables para los días en los que no había datos disponibles. Esos informes contendrán una fila de encabezado, pero no contendrán datos adicionales.

  • Los informes de las APIs están disponibles durante 60 días desde el momento en que se generan, a excepción de los datos históricos generados para nuevos trabajos de informes. No se podrá acceder a los informes una vez que tengan más de 60 días de antigüedad.
  • Los informes que contienen datos históricos estarán disponibles durante 30 días desde la fecha en que se crearon. No se podrá acceder a los informes que contengan datos históricos una vez que tengan más de 30 días de antigüedad.
  • Los datos del informe no se filtran. Por lo tanto, un informe de canal contiene todos los datos de los videos o las playlists de un canal, excepto que se menciona en el siguiente párrafo respecto de los recursos eliminados. Del mismo modo, un informe de propietario de contenido contiene todos los datos de los canales del propietario del contenido (videos, playlists, rendimiento de anuncios, etc.), con la siguiente excepción.

    Aunque los datos de los informes no se filtran, los informes no contienen ninguna referencia a los recursos de YouTube que se hayan borrado al menos 30 días antes de la fecha de generación del informe.

  • Los datos del informe no están ordenados.

  • Los informes omiten las filas que no tienen métricas. En otras palabras, se excluyen del informe las filas que no tienen ninguna métrica. Por ejemplo, si un video no tiene vistas en Albania un día en particular, el informe de ese día no contendrá filas para Albania.

  • Los informes no contienen filas que proporcionen datos de resumen de las métricas, como la cantidad total de vistas para todos los videos de un canal. Puedes calcular esos valores totales como la suma de los valores que se muestran en el informe, pero es posible que esa suma no incluya las métricas de los videos borrados, como se indicó más arriba. También puedes usar la API de YouTube Analytics para recuperar los recuentos totales. La API de YouTube Analytics muestra valores totales que incluyen métricas para recursos borrados, a pesar de que no se hace referencia explícitamente a esos recursos en las respuestas de la API.

Datos de reabastecimiento

Los datos de reabastecimiento son un conjunto de datos que reemplaza un conjunto enviado anteriormente. Cuando hay un informe de datos de reabastecimiento disponible, tu aplicación debe recuperar el informe nuevo y actualizar tus datos almacenados para que coincidan con el conjunto de datos revisado. Por ejemplo, tu aplicación podría borrar los datos anteriores del período que abarca el informe y, luego, importar el nuevo conjunto de datos.

Si YouTube tiene datos de reabastecimiento, generará un informe nuevo con un ID de informe nuevo. En ese caso, los valores de las propiedades startTime y endTime del informe coincidirán con las horas de inicio y finalización de un informe que estaba disponible y que quizás ya descargaste.

Los informes de reabastecimiento no contienen ninguna referencia a los recursos de YouTube que se hayan borrado al menos 30 días antes de la fecha en que se generó el informe.

Datos históricos

Cuando programas un nuevo trabajo de informe, YouTube genera informes históricos a partir de ese día y genera informes que abarcan el período de 30 días anteriores a la fecha en la que creaste el trabajo. Por lo tanto, en esta documentación, los datos históricos hacen referencia a un informe que contiene datos de un período antes de que se programara el trabajo de generación de informes.

Los informes históricos se publican tan pronto como están disponibles. Por lo general, todos los datos históricos se publican para un trabajo en un par de días. Como se explica en la sección Características de informes, los informes que contienen datos históricos están disponibles durante 30 días desde la fecha en que se generan. Los informes que contienen datos no históricos están disponibles durante 60 días.

Anonimización de datos

Para garantizar el anonimato de los usuarios de YouTube, solo se muestran los valores de algunas dimensiones si una métrica en la misma fila alcanza un umbral determinado.

Por ejemplo, en el informe de fuentes de tráfico de video de los canales, cada fila contiene varias dimensiones, como trafficSourceType y trafficSourceDetail. Además, cada fila contiene varias métricas, incluidas las vistas. En las filas que describen el tráfico que se originó a partir de una búsqueda de YouTube, la dimensión trafficSourceDetail identifica el término de búsqueda que generó el tráfico.

En este ejemplo, se aplican las siguientes reglas:

  • El informe de fuentes de tráfico identifica el término de búsqueda (trafficSourceDetail) solo si generó, al menos, una cantidad determinada de vistas de un video específico en un día determinado. En este caso, vistas es la métrica, video es la dimensión de agregación y trafficSourceDetail es la dimensión anonimizada.

  • El informe incluye una fila adicional que agrega las métricas de todos los valores de trafficSourceDetail que no cumplen con el umbral de vistas. Esa fila informa la cantidad total de vistas asociadas con esos términos de búsqueda, pero no identifica los términos en sí.

En las siguientes tablas se muestran estas reglas. La primera tabla contiene un conjunto hipotético de datos sin procesar que YouTube usaría para generar un informe de fuentes de tráfico y la segunda tabla contiene el informe en sí. En este ejemplo, el umbral del recuento de vistas es de 10, lo que significa que el informe solo identifica un término de búsqueda si generó, al menos, 10 vistas de un video específico en un día específico. (los umbrales reales están sujetos a cambios).

Datos de tráfico de búsqueda de YouTube sin procesar para un video

Supongamos que los siguientes datos describen el tráfico de búsqueda de YouTube a un video en particular en un día determinado.

término de búsqueda vistas minutos de visualización estimados
estilo gangnam 100 200
psy 15 25
gangnam psy 9 15
oppa gangnam 5 8
danza de equitación 2 5

Ejemplo de informe de fuentes de tráfico

En la siguiente tabla, se muestra un extracto del informe de fuentes de tráfico que generaría YouTube para los datos sin procesar de la sección anterior. (El informe real incluiría más dimensiones y métricas). En este ejemplo, el informe identifica los términos de búsqueda solo si generaron, al menos, 10 vistas. Los umbrales reales están sujetos a cambios.

En la tercera fila del informe, el valor de la dimensión trafficSourceDetail es NULL. Las métricas views y estimatedMinutesWatched contienen las vistas y los minutos que se miraron para los tres términos de búsqueda que generaron menos de 10 vistas.

trafficSourceDetail vistas estimatedMinutesWatched
estilo gangnam 100 200
psy 15 25
NULL 16 28

Dimensiones sujetas a anonimización

En la siguiente tabla, se identifican los valores de dimensión que son anónimos si los valores de la métrica asociada no cumplen con un umbral determinado. En cada caso, el valor de la métrica se agrega sobre otra dimensión. Por ejemplo, si la métrica es vistas y la dimensión de agregación es video, el valor de la dimensión se anonimiza, a menos que el video se haya visto una cierta cantidad de veces.

Métrica Dimensiones de agregación Dimensión anonimizada Valor anonimizado
subscribersGained channel country ZZ
subscribersGained channel province US-ZZ
subscribersLost channel country ZZ
subscribersLost channel province US-ZZ
comments video country ZZ
comments video province US-ZZ
me gusta video country ZZ
me gusta video province US-ZZ
no me gusta video country ZZ
no me gusta video province US-ZZ
vistas video ageGroup NULL
vistas video género NULL
vistas video y trafficSourceDetail trafficSourceDetail NULL
Cantidad de suscriptores al canal channel subscribedStatus NULL

Muestras de código

En las siguientes muestras de código, se indica cómo usar la API para crear un trabajo de informe y, luego, recuperar un informe para ese trabajo. Se proporcionan dos muestras de código para cada lenguaje:

  1. En la primera muestra de código, se indica cómo recuperar una lista de los tipos de informes disponibles y, luego, crear un trabajo de informe nuevo.

  2. En la segunda muestra de código, se indica cómo recuperar un informe para un trabajo en particular. Puedes comenzar a recuperar informes dentro de las 48 horas posteriores a la creación del trabajo.

Nota: Es posible que las siguientes muestras de código no representen todos los lenguajes de programación admitidos. Consulta la documentación de bibliotecas cliente para obtener una lista de los lenguajes admitidos.

Java

En los siguientes ejemplos se usa la biblioteca cliente de Java:

Ejemplo 1: Crea un trabajo de informes

En la siguiente muestra de código, se llama al método reportTypes.list para recuperar una lista de los tipos de informes disponibles. Luego, llama al método jobs.create para crear un nuevo trabajo de informe.

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

Ejemplo 2: recupera un informe

La muestra de código llama al método jobs.list para recuperar una lista de trabajos de informes. Luego, llama al método reports.list con el parámetro jobId configurado en un ID de tarea específico para recuperar los informes que creó ese trabajo. Finalmente, la muestra imprime la URL de descarga de cada informe.

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

En los siguientes ejemplos se usa la biblioteca cliente PHP.

Ejemplo 1: Crea un trabajo de informes

En la siguiente muestra de código, se llama al método reportTypes.list para recuperar una lista de los tipos de informes disponibles. Luego, llama al método jobs.create para crear un nuevo trabajo de informe.

<?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>

Ejemplo 2: recupera un informe

La muestra de código llama al método jobs.list para recuperar una lista de trabajos de informes. Luego, llama al método reports.list con el parámetro jobId configurado en un ID de tarea específico para recuperar los informes que creó ese trabajo. Finalmente, la muestra imprime la URL de descarga de cada informe.

<?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

Los siguientes ejemplos utilizan la biblioteca cliente de Python.

Ejemplo 1: Crea un trabajo de informes

En la siguiente muestra de código, se llama al método reportTypes.list para recuperar una lista de los tipos de informes disponibles. Luego, llama al método jobs.create para crear un nuevo trabajo de informe.

#!/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)

Ejemplo 2: recupera un informe

La muestra de código llama al método jobs.list para recuperar una lista de trabajos de informes. Luego, llama al método reports.list con el parámetro jobId configurado en un ID de tarea específico para recuperar los informes que creó ese trabajo. Finalmente, la muestra imprime la URL de descarga de cada informe.

#!/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)