YouTube Reporting API - Get Bulk Data Reports
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
YouTube genera automáticamente un conjunto de informes de ingresos publicitarios administrados por el sistema para los propietarios de contenido que tienen acceso a los informes correspondientes en Creator Studio. Estos informes están diseñados para proporcionar acceso programático a los datos que también están disponibles en los informes descargables manualmente a los que se puede acceder en el menú Informes de Creator Studio de YouTube.
Nota: La API proporciona acceso a un conjunto diferente de informes que Creator Studio, aunque los informes contienen datos similares. Los informes de la API pueden tener campos diferentes y también usar nombres de campos distintos de los informes de Creator Studio.
Dado que YouTube genera automáticamente informes administrados por el sistema, el proceso para recuperar estos informes es diferente al de los informes de datos masivos de YouTube Analytics disponibles a través de la API.
Cómo recuperar informes
En los siguientes pasos, se explica cómo recuperar informes administrados por el sistema a través de la API.
Paso 1: Recupera las credenciales de autorización
Todas las solicitudes a la API de YouTube Reporting deben estar autorizadas. En la guía de autorización, se explica cómo usar el protocolo de OAuth 2.0 para recuperar tokens de autorización.
Las solicitudes a la API de YouTube Reporting usan los siguientes permisos 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 alcance proporciona acceso a las métricas de actividad del usuario y a las métricas de rendimiento de los anuncios y los ingresos estimados. |
Paso 2: Recupera el ID del trabajo para el informe deseado
Llama al método jobs.list
para recuperar una lista de trabajos administrados por el sistema. Establece el parámetro includeSystemManaged
en true
.
La propiedad reportTypeId
de cada recurso Job
devuelto identifica el tipo de informe administrado por el sistema asociado a ese trabajo. Tu aplicación necesita el valor de la propiedad id
del mismo recurso en el siguiente paso.
En el documento Informes, se enumeran los informes disponibles, sus IDs de tipo de informe y los campos que contienen. También puedes usar el método reportTypes.list
para recuperar una lista de los tipos de informes admitidos.
Paso 3: Recupera la URL de descarga del informe
Llama al método jobs.reports.list
para recuperar una lista de los informes creados para el trabajo. En la solicitud, establece el parámetro jobId
en el ID del trabajo del informe que deseas recuperar.
Puedes filtrar la lista de informes con cualquiera de los siguientes parámetros o con todos ellos:
-
Usa el parámetro createdAfter
para indicar que la API solo debe devolver los informes creados después de una fecha y hora especificadas. Este parámetro se puede usar para garantizar que la API solo devuelva informes que aún no hayas procesado.
-
Usa el parámetro startTimeBefore
para indicar que la respuesta de la API solo debe contener informes si los datos más antiguos del informe son anteriores a la fecha especificada. Mientras que el parámetro createdAfter
se refiere al momento en que se creó el informe, esta fecha se refiere a los datos del informe.
-
Usa el parámetro startTimeAtOrAfter
para indicar que la respuesta de la API solo debe contener informes si los datos más antiguos del informe son posteriores a la fecha especificada o se encuentran en ella. Al igual que el parámetro startTimeBefore
, este valor del parámetro corresponde a los datos del informe y no a la hora en que se creó el informe.
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.
- 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 que se puede recuperar el informe.
- La propiedad
createTime
del recurso especifica la fecha y la hora en que se generó el informe. Tu aplicación debe almacenar este valor y usarlo para determinar si cambiaron los informes descargados anteriormente.
Paso 4: Descarga el informe
Envía una solicitud HTTP GET al downloadUrl
que obtuviste en el paso 4 para recuperar el informe.
Informes de procesamiento
Prácticas recomendadas
Las aplicaciones que usan la API de YouTube Reporting deben siempre seguir estas prácticas:
-
Usa la fila de encabezado de un informe para determinar el orden de las columnas del informe. Por ejemplo, no supongas que las vistas serán la primera métrica que se mostrará en un informe solo porque es la primera métrica que aparece en la descripción del informe. En su lugar, usa la fila de encabezado del informe para determinar qué columna contiene esos datos.
-
Mantén un registro de los informes que descargaste para evitar procesar el mismo informe varias veces. 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 correctamente los informes, almacena la marca de tiempo correspondiente a la fecha y hora en 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 los informes nuevos, incluidos los informes nuevos con datos completados, cada vez que llames a la API.
Como medida de seguridad, antes de recuperar un informe, también verifica que su ID no aparezca ya 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 que se generó cada informe o el startTime
y el endTime
del informe, que juntos identifican el período para el que el informe contiene datos. En el caso de los informes que recuperan datos masivos para YouTube Analytics, es probable que cada trabajo tenga muchos informes, ya que cada uno contiene datos de un período de 24 horas. Los trabajos administrados por el sistema que abarcan períodos más largos tendrán menos informes.
Usa el ID del 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.
Características del informe
Los informes de la API son archivos .csv
(valores separados por comas) versionados que tienen las siguientes características:
-
Cada informe contiene datos de un período único que abarca desde las 12:00 a.m. (hora del Pacífico) de la fecha de inicio del informe hasta las 11:59 p.m. (hora del Pacífico) de la fecha de finalización del informe.
-
Los datos del informe no están ordenados.
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
Última actualización: 2025-08-21 (UTC)
[null,null,["Última actualización: 2025-08-21 (UTC)"],[[["\u003cp\u003eYouTube's Reporting API provides access to system-managed ad revenue reports, which differ from Creator Studio reports in terms of fields and naming, yet contain similar data.\u003c/p\u003e\n"],["\u003cp\u003eRetrieving these reports involves four steps: getting authorization credentials, retrieving the job ID, getting the report's download URL, and downloading the report.\u003c/p\u003e\n"],["\u003cp\u003eThe API requires specific authorization scopes, either \u003ccode\u003ehttps://www.googleapis.com/auth/yt-analytics.readonly\u003c/code\u003e for general user activity metrics or \u003ccode\u003ehttps://www.googleapis.com/auth/yt-analytics-monetary.readonly\u003c/code\u003e for monetary and ad performance metrics.\u003c/p\u003e\n"],["\u003cp\u003eBest practices for using the API include using the header row to identify column ordering and keeping a record of downloaded reports to avoid reprocessing the same data, while also checking for updated reports.\u003c/p\u003e\n"],["\u003cp\u003eEach report is a \u003ccode\u003e.csv\u003c/code\u003e file containing data for a specific period, from 12:00 a.m. to 11:59 p.m. Pacific Time, and the data within the reports is not sorted.\u003c/p\u003e\n"]]],["YouTube provides system-managed ad revenue reports accessible via the Reporting API. To retrieve these reports, first, obtain authorization credentials using OAuth 2.0. Next, retrieve the job ID for the desired report type by calling `jobs.list` with `includeSystemManaged` set to `true`. Then, call `jobs.reports.list`, providing the job ID, to get the report's download URL, which may be filtered by creation or start times. Finally, use an HTTP GET request to download the report. Remember to store downloaded report details to avoid reprocessing.\n"],null,["# YouTube Reporting API - Get Bulk Data Reports\n\nYouTube automatically generates a set of system-managed ad revenue reports for content owners that have access to the corresponding reports in [Creator Studio](http://studio.youtube.com/). These reports are designed to provide programmatic access to data that is also available in manually downloadable reports accessible in the [Reports menu](https://support.google.com/youtube/answer/7648605) of the YouTube Creator Studio.\n\n**Note:** The API provides access to a different set of reports than Creator Studio, though the reports contain similar data. API reports might have different fields and also use different field names than Creator Studio reports.\n\nSince YouTube automatically generates system-managed reports, the process for retrieving these reports is different than for the YouTube Analytics bulk data reports available via the API.\n\nRetrieving reports\n------------------\n\nThe following steps explain how to retrieve system-managed reports via the API.\n\n### Step 1: Retrieve authorization credentials\n\nAll YouTube Reporting API requests must be authorized. The [Authorization guide](/youtube/reporting/guides/authorization) explains how to use the OAuth 2.0 protocol to retrieve authorization tokens.\n\nYouTube Reporting API requests use the following authorization scopes:\n\n| Scopes ||\n|----------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| 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. |\n| 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. |\n\n### Step 2: Retrieve the job ID for the desired report\n\nCall the `jobs.list` method to retrieve a list of system-managed jobs. Set the [includeSystemManaged](/youtube/reporting/v1/reference/rest/v1/jobs/list#includeSystemManaged) parameter to `true`.\n\nThe [reportTypeId](/youtube/reporting/v1/reference/rest/v1/jobs#reportTypeId) property in each returned `Job` resource identifies the type of system-managed report associated with that job. Your application needs the [id](/youtube/reporting/v1/reference/rest/v1/jobs#id) property value from the same resource in the following step.\n\nThe [Reports](/youtube/reporting/v1/reports/system_managed/reports) document lists available reports, their report type IDs, and the fields they contain. You can also use the [reportTypes.list](/youtube/reporting/v1/reference/rest/v1/reportTypes/list) method to retrieve a list of supported report types.\n\n### Step 3: Retrieve the report's download URL\n\nCall the `jobs.reports.list` method to retrieve a list of reports created for the job. In the request, set the [jobId](/youtube/reporting/v1/reference/rest/v1/jobs.reports/list#jobId) parameter to the job ID of the report that you want to retrieve.\n\nYou can filter the list of reports using any or all of the following parameters:\n\n- Use the [createdAfter](/youtube/reporting/v1/reference/rest/v1/jobs.reports/list#createdAfter) parameter to indicate that the API should only return reports created after a specified time. This parameter can be used to ensure that the API only returns reports that you have not already processed.\n\n- Use the [startTimeBefore](/youtube/reporting/v1/reference/rest/v1/jobs.reports/list#startTimeBefore) parameter to indicate that the API response should only contain reports if the earliest data in the report is before the specified date. Whereas the `createdAfter` parameter pertains to the time the report was created, this date pertains to the data in the report.\n\n- Use the [startTimeAtOrAfter](/youtube/reporting/v1/reference/rest/v1/jobs.reports/list#startTimeAtOrAfter) parameter to indicate that the API response should only contain reports if the earliest data in the report is on or after the specified date. Like the `startTimeBefore` parameter, this parameter value corresponds to the data in the report and not the time the report was created.\n\nThe API response contains a list of `Report` resources for that job. Each resource refers to a report that contains data for a unique period.\n\n- The resource's [startTime](/youtube/reporting/v1/reference/rest/v1/jobs.reports#startTime) and [endTime](/youtube/reporting/v1/reference/rest/v1/jobs.reports#endTime) properties identify the time period that the report's data covers.\n- The resource's [downloadUrl](/youtube/reporting/v1/reference/rest/v1/jobs.reports#downloadUrl) property identifies the URL from which the report can be fetched.\n- The resource's [createTime](/youtube/reporting/v1/reference/rest/v1/jobs.reports#createTime) property specifies the date and time when the report was generated. Your application should store this value and use it to determine whether previously downloaded reports have changed.\n\n### Step 4: Download the report\n\nSend an HTTP GET request to the `downloadUrl` obtained in step 4 to retrieve the report.\n\nProcessing reports\n------------------\n\n### Best practices\n\nApplications that use the YouTube Reporting API should *always* follow these practices:\n\n- Use a report's header row to determine the ordering of the report's columns. For example, do not assume that [views](/youtube/reporting/v1/reports/metrics#views) will be the first metric returned in a report just because it is the first metric listed in a report description. Instead, use the report's header row to determine which column contains that data.\n\n- Keep a record of the reports you have downloaded to avoid repeatedly processing the same report. The following list suggests a couple of ways to do that.\n\n - When calling the [reports.list](/youtube/reporting/v1/reference/rest/v1/jobs.reports/list) method, use the [createdAfter](/youtube/reporting/v1/reference/rest/v1/jobs.reports/list#createdAfter) parameter to only retrieve reports created after a certain date. (Omit the `createdAfter` parameter the first time you retrieve reports.)\n\n Each time you retrieve and successfully process reports, store the timestamp corresponding to the [date and time](/youtube/reporting/v1/reference/rest/v1/jobs.reports#createTime) when the newest of those reports was created. Then, update the `createdAfter` parameter value on each successive call to the [reports.list](/youtube/reporting/v1/reference/rest/v1/jobs.reports/list) method to ensure that you are only retrieving new reports, including new reports with backfilled data, each time you call the API.\n\n As a safeguard, before retrieving a report, also check to ensure that the report's [ID](/youtube/reporting/v1/reference/rest/v1/jobs.reports#id) is not already listed in your database.\n - Store the [ID](/youtube/reporting/v1/reference/rest/v1/jobs.reports#id) for each report that you have downloaded and processed. You can also store additional information like the [date and time](/youtube/reporting/v1/reference/rest/v1/jobs.reports#createTime) when each report was generated or the report's [startTime](/youtube/reporting/v1/reference/rest/v1/jobs.reports#startTime) and [endTime](/youtube/reporting/v1/reference/rest/v1/jobs.reports#endTime), which together identify the period for which the report contains data. For reports that retrieve bulk data for YouTube Analytics, each job will likely have many reports since each report contains data for a 24-hour period. System-managed jobs that cover longer time periods will have fewer reports.\n\n Use the report ID to identify reports that you still need to download and import. However, if two new reports have the same [startTime](/youtube/reporting/v1/reference/rest/v1/jobs.reports#startTime) and [endTime](/youtube/reporting/v1/reference/rest/v1/jobs.reports#endTime) property values, only import the report with the newer [createTime](/youtube/reporting/v1/reference/rest/v1/jobs.reports#createTime) value.\n\n### Report characteristics\n\nAPI reports are versioned `.csv` (comma-separated values) files that have the following characteristics:\n\n- Each report contains data for a unique period lasting from 12:00 a.m. Pacific time on the report's start date through 11:59 p.m. Pacific time on the report's end date.\n\n- Report data is not sorted."]]