Cree informes programados y acceda a ellos

Puedes crear y programar informes con la IU o la API de Google Display & Video 360. Por ejemplo, los usuarios finales pueden configurar un informe diario que muestre las impresiones del día anterior o un informe mensual que muestre el gasto total.

Creación de informes programados

Crea un nuevo informe programado en la interfaz de informes de Display & Video 360 o con el método de la API de queries.create. Puedes encontrar todos los detalles sobre la función de informes de Display & Video 360 y cómo crear informes nuevos en el sitio de asistencia de Display & Video 360.

Los informes se pueden programar durante la creación con el campo Repeats en la IU y el campo schedule en la API. Estos campos se deben configurar en un intervalo de tiempo adecuado.

Una vez que se haya configurado el campo adecuado, este informe se ejecutará en ese programa y los informes generados estarán disponibles para descargar.

Acceder a los informes programados

Los informes programados se generan como archivos CSV simples y se almacenan de forma automática y segura en Google Cloud Storage. Sin embargo, no es posible acceder a los buckets de Google Cloud Storage que contienen estos archivos directamente. En su lugar, los archivos se pueden descargar de forma manual desde la IU de Display & Video 360 o recuperarse de manera programática con URLs preautorizadas que se obtienen de la API.

A continuación, se proporciona un ejemplo de cómo utilizar la API para descargar un archivo de informe. En este ejemplo, queries.reports.list se usa con el parámetro orderBy para recuperar el informe más reciente de una consulta. Luego, se usa el campo Report.reportMetadata.googleCloudStoragePath para ubicar el archivo del informe y descargar su contenido en un archivo CSV local.

Java

Importaciones obligatorias:

import com.google.api.client.googleapis.media.MediaHttpDownloader;
import com.google.api.client.googleapis.util.Utils;
import com.google.api.client.http.GenericUrl;
import com.google.api.services.doubleclickbidmanager.DoubleClickBidManager;
import com.google.api.services.doubleclickbidmanager.model.ListReportsResponse;
import com.google.api.services.doubleclickbidmanager.model.Report;
import java.io.FileOutputStream;
import java.io.OutputStream;

Ejemplo de código:

long queryId = query-id;

// Call the API, listing the reports under the given queryId from most to
// least recent.
ListReportsResponse reportListResponse =
    service
        .queries()
        .reports()
        .list(queryId)
        .setOrderBy("key.reportId desc")
        .execute();

// Iterate over returned reports, stopping once finding a report that
// finished generating successfully.
Report mostRecentReport = null;
if (reportListResponse.getReports() != null) {
  for (Report report : reportListResponse.getReports()) {
    if (report.getMetadata().getStatus().getState().equals("DONE")) {
      mostRecentReport = report;
      break;
    }
  }
} else {
  System.out.format("No reports exist for query Id %s.\n", queryId);
}

// Download report file of most recent finished report found.
if (mostRecentReport != null) {
  // Retrieve GCS URL from report object.
  GenericUrl reportUrl =
      new GenericUrl(mostRecentReport.getMetadata().getGoogleCloudStoragePath());

  // Build filename.
  String filename =
      mostRecentReport.getKey().getQueryId() + "_"
          + mostRecentReport.getKey().getReportId() + ".csv";

  // Download the report file.
  try (OutputStream output = new FileOutputStream(filename)) {
    MediaHttpDownloader downloader =
        new MediaHttpDownloader(Utils.getDefaultTransport(), null);
    downloader.download(reportUrl, output);
  }
  System.out.format("Download of file %s complete.\n", filename);
} else {
  System.out.format(
      "There are no completed report files to download for query Id %s.\n",
      queryId);
}

Python

Importaciones obligatorias:

from contextlib import closing
from six.moves.urllib.request import urlopen

Ejemplo de código:

query_id = query-id

# Call the API, listing the reports under the given queryId from most to
# least recent.
response = service.queries().reports().list(queryId=query_id, orderBy="key.reportId desc").execute()

# Iterate over returned reports, stopping once finding a report that
# finished generating successfully.
most_recent_report = None
if response['reports']:
  for report in response['reports']:
    if report['metadata']['status']['state'] == 'DONE':
      most_recent_report = report
      break
else:
  print('No reports exist for query Id %s.' % query_id)

# Download report file of most recent finished report found.
if most_recent_report != None:
  # Retrieve GCS URL from report object.
  report_url = most_recent_report['metadata']['googleCloudStoragePath']

  # Build filename.
  output_file = '%s_%s.csv' % (report['key']['queryId'], report['key']['reportId'])

  # Download the report file.
  with open(output_file, 'wb') as output:
    with closing(urlopen(report_url)) as url:
      output.write(url.read())
  print('Download of file %s complete.' % output_file)
else:
  print('There are no completed report files to download for query Id %s.' % query_id)

PHP

$queryId = query-id;

// Call the API, listing the reports under the given queryId from most to
// least recent.
$optParams = array('orderBy' => "key.reportId desc");
$response = $service->queries_reports->listQueriesReports($queryId, $optParams);

// Iterate over returned reports, stopping once finding a report that
// finished generating successfully.
$mostRecentReport = null;
if (!empty($response->getReports())) {
  foreach ($response->getReports() as $report) {
    if ($report->metadata->status->state == "DONE") {
      $mostRecentReport = $report;
      break;
    }
  }
} else {
  printf('<p>No reports exist for query ID %s.</p>', $queryId);
}

// Download report file of most recent finished report found.
if ($mostRecentReport != null) {
  // Build filename.
  $filename = $mostRecentReport->key->queryId . '_' . $mostRecentReport->key->reportId . '.csv';

  // Download the report file.
  file_put_contents($filename, fopen($mostRecentReport->metadata->googleCloudStoragePath, 'r'));
  printf('<p>Download of file %s complete.</p>', $filename);
} else {
  printf('<p>There are no completed report files to download for query Id %s.</p>', $queryId);
}