Realiza encuestas y consulta los informes completados

Una operación de ejecución de informes se ejecuta de forma asíncrona como una operación de larga duración, representada por el Operation objeto. El resultado de una operación de ejecución de informes son los resultados del informe basados en el Report objeto.

En esta guía, se describe cómo puedes usar la API de Curation Partners para obtener una operación de ejecución de informes que sondee el estado de la operación, y recuperar los resultados del informe de la operación de ejecución de informes completada.

Antes de comenzar

Antes de continuar, debes completar lo siguiente:

Cómo sondear el estado de una ejecución de informes

Para verificar el estado de ejecución de una operación de ejecución de informes, usa el curators.reports.operations.get método.

En el siguiente ejemplo, se realiza una solicitud GET para sondear una operación:

REST

Solicitud

curl \
  'https://curationpartners.googleapis.com/v1/curators/ACCOUNT_ID/reports/123456789/operations/10486370264' \
  --header 'Authorization: Bearer ACCESS_TOKEN' \
  --header 'Accept: application/json' \
  --compressed

Reemplaza lo siguiente:

  • ACCOUNT_ID: Tu ID de cuenta.
  • ACCESS_TOKEN: Tu token de acceso.

Respuesta

Cuando se completa correctamente, la respuesta es una Operation con el campo done establecido en true, y la carga útil response se propaga con el nombre de recurso reportResult:

{
  "name": "curators/ACCOUNT_ID/reports/123456789/operations/10486370264",
  "done": true,
  "metadata": {
    "@type": "type.googleapis.com/google.ads.curationpartners.v1.RunReportMetadata",
    "percentComplete": 100
  },
  "response": {
    "@type": "type.googleapis.com/google.ads.curationpartners.v1.RunReportResponse",
    "reportResult": "curators/ACCOUNT_ID/reports/123456789/results/10486370264"
  }
}

Java

/*
 * Copyright (c) 2026 Google LLC
 *
 * 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.curationpartners.v1.curators.reports.operations;

import com.google.api.services.curationpartners.v1.CurationPartners;
import com.google.api.services.curationpartners.v1.model.Operation;
import com.google.api.services.samples.curationpartners.v1.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

public class GetReportOperation {

  /**
   * Executes the get operation for a report operation.
   *
   * @param curationPartnersClient the initialized Curation Partners API client.
   * @param accountId the account ID of the curator.
   * @param reportId the resource ID of the report.
   * @param operationId the resource ID of the report operation.
   * @throws IOException if the API returns an error.
   */
  public static void execute(
      CurationPartners curationPartnersClient,
      Long accountId,
      String reportId,
      String operationId)
      throws IOException {
    String name =
        String.format(
            "curators/%s/reports/%s/operations/%s", accountId, reportId, operationId);

    System.out.printf("Getting report operation with name \"%s\".%n", name);

    // Get the status of the report operation.
    Operation operation =
        curationPartnersClient
            .curators()
            .reports()
            .operations()
            .get(name)
            .execute();

    System.out.println("Successfully retrieved report operation:");
    Utils.jsonPrettyPrint(operation);
  }

  /**
   * Creates and configures the ArgumentParser for this sample.
   *
   * @return the configured ArgumentParser.
   */
  private static ArgumentParser createArgumentParser() {
    ArgumentParser parser =
        ArgumentParsers.newFor("GetReportOperation")
            .build()
            .defaultHelp(true)
            .description("Gets the status of a long-running report operation. If the " +
                "operation is done, you can view the report contents with the " +
                "`curators.reports.results.fetchRows` method.");

    // Required arguments.
    parser
        .addArgument("-a", "--account_id")
        .help("The account ID of the curator.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-r", "--report_id")
        .help("The resource ID of the report.")
        .required(true);
    parser
        .addArgument("-o", "--operation_id")
        .help("The resource ID of the report operation to retrieve.")
        .required(true);

    return parser;
  }

  public static void main(String[] args) {
    ArgumentParser parser = createArgumentParser();

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    CurationPartners client = null;
    try {
      client = Utils.getCurationPartnersClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create Curation Partners API service:%n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:%n%s", ex);
      System.exit(1);
    }

    try {
      execute(
          client,
          parsedArgs.getLong("account_id"),
          parsedArgs.getString("report_id"),
          parsedArgs.getString("operation_id"));
    } catch (IOException ex) {
      System.out.printf("Curation Partners API returned error response:%n%s", ex);
      System.exit(1);
    }
  }
}

A continuación, se describe cómo puedes usar el campo done para sondear el estado de la operación:

  • Si el campo done de la respuesta es el valor false, la operación de ejecución de informes aún se está procesando.
  • Si el campo done de la respuesta es el valor true, la operación de ejecución de informes se completó. El objeto Operation en el cuerpo de la respuesta también contiene cualquiera de los siguientes campos:
    • response: Indica que la operación de ejecución de informes se realizó correctamente. Este campo es un objeto propagado con un campo @type establecido en el tipo type.googleapis.com/google.ads.curationpartners.v1.RunReportResponse. El tipo RunReportResponse se propaga con un campo reportResult que contiene el nombre del informe correspondiente result.
    • error: Indica que la operación de ejecución de informes no se realizó correctamente. El campo error se propaga con un Status objeto que describe por qué falló la ejecución del informe.

Cómo recuperar filas de un informe completado

Puedes recuperar el contenido de una operación de ejecución de informes completada con el curators.reports.results.fetchRows método. Debes completar el parámetro de ruta de acceso name para el resultado del informe, que es el nombre de recurso del campo reportResult de una operación de ejecución de informes completa.

En el siguiente ejemplo, se realiza una solicitud GET para recuperar filas de resultados:

REST

Solicitud

curl \
  'https://curationpartners.googleapis.com/v1/curators/ACCOUNT_ID/reports/123456789/results/10486370264:fetchRows?pageSize=1' \
  --header 'Authorization: Bearer ACCESS_TOKEN' \
  --header 'Accept: application/json' \
  --compressed

Respuesta

{
  "rows": [
    {
      "dimensionValues": [
        {
          "stringValue": "2026-08-01"
        },
        {
          "stringValue": "segment-1001"
        }
      ],
      "metricValueGroups": [
        {
          "primaryValues": [
            {
              "intValue": "150000"
            },
            {
              "intValue": "3200"
            },
            {
              "doubleValue": 450.75
            },
            {
              "doubleValue": 45.08
            }
          ]
        }
      ]
    }
  ],
  "runTime": "2026-08-05T12:00:00Z",
  "dateRanges": [
    {
      "startDate": {
        "year": 2026,
        "month": 7,
        "day": 6
      },
      "endDate": {
        "year": 2026,
        "month": 8,
        "day": 4
      }
    }
  ],
  "totalRowCount": 2,
  "nextPageToken": "QC7nzW91c2VTcGFubmVyQ29udGlubWF0aW6uVG9wZY45NP=="
}

Java

/*
 * Copyright (c) 2026 Google LLC
 *
 * 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.curationpartners.v1.curators.reports.results;

import com.google.api.services.curationpartners.v1.CurationPartners;
import com.google.api.services.curationpartners.v1.model.FetchReportResultRowsResponse;
import com.google.api.services.samples.curationpartners.v1.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

public class FetchReportResultRows {

  /**
   * Executes the fetchRows operation for report result rows.
   *
   * @param curationPartnersClient the initialized Curation Partners API client.
   * @param accountId the account ID of the curator.
   * @param reportId the resource ID of the report.
   * @param resultId the resource ID of the report result.
   * @param pageSize the maximum number of rows to return per page.
   * @param pageToken the page token from a previous response, if any.
   * @throws IOException if the API returns an error.
   */
  public static void execute(
      CurationPartners curationPartnersClient,
      Long accountId,
      String reportId,
      String resultId,
      Integer pageSize,
      String pageToken)
      throws IOException {
    String name = String.format("curators/%s/reports/%s/results/%s", accountId, reportId, resultId);

    System.out.printf("Fetching report result rows for \"%s\".%n", name);

    CurationPartners.Curators.Reports.Results.FetchRows request =
        curationPartnersClient.curators().reports().results().fetchRows(name);

    if (pageSize != null) {
      request.setPageSize(pageSize);
    }
    if (pageToken != null) {
      request.setPageToken(pageToken);
    }

    FetchReportResultRowsResponse response = request.execute();

    System.out.println("Successfully fetched report result rows:");
    Utils.jsonPrettyPrint(response);
  }

  /**
   * Creates and configures the ArgumentParser for this sample.
   *
   * @return the configured ArgumentParser.
   */
  private static ArgumentParser createArgumentParser() {
    ArgumentParser parser =
        ArgumentParsers.newFor("FetchReportResultRows")
            .build()
            .defaultHelp(true)
            .description("Fetches rows for a completed report result.");

    // Required arguments.
    parser
        .addArgument("-a", "--account_id")
        .help("The account ID of the curator.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-r", "--report_id")
        .help("The resource ID of the report.")
        .required(true);
    parser
        .addArgument("--result_id")
        .help("The resource ID of the report result. This is identical to the resource ID of " +
            "the corresponding report run operation.")
        .required(true);

    // Optional arguments.
    parser
        .addArgument("--page_size")
        .help("The maximum number of rows to return per page.")
        .type(Integer.class);
    parser
        .addArgument("--page_token")
        .help("A page token, received from a previous `FetchReportResultRows` call.");

    return parser;
  }

  public static void main(String[] args) {
    ArgumentParser parser = createArgumentParser();

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    CurationPartners client = null;
    try {
      client = Utils.getCurationPartnersClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create Curation Partners API service:%n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:%n%s", ex);
      System.exit(1);
    }

    try {
      execute(
          client,
          parsedArgs.getLong("account_id"),
          parsedArgs.getString("report_id"),
          parsedArgs.getString("result_id"),
          parsedArgs.getInt("page_size"),
          parsedArgs.getString("page_token"));
    } catch (IOException ex) {
      System.out.printf("Curation Partners API returned error response:%n%s", ex);
      System.exit(1);
    }
  }
}

Puedes especificar los siguientes parámetros de consulta:

  • pageSize: La cantidad máxima de filas que se mostrarán. El valor predeterminado es 1,000 filas y el máximo es 10,000 filas.
  • pageToken: El token de página que se muestra en una respuesta fetchRows anterior para recuperar el siguiente lote de filas.

La respuesta contiene los siguientes campos:

  • rows: Un array de objetos Row. Cada fila contiene lo siguiente:
    • dimensionValues: Valores para cada dimensión solicitada, ordenados de forma idéntica a las dimensiones de la definición del informe.
    • metricValueGroups: Grupos de valores de métricas que corresponden a los intervalos de fechas. Cada grupo contiene una lista primaryValues ordenada de forma idéntica a las métricas de la definición del informe.
  • dateRanges: Los intervalos de fechas fijas calculados para el informe. El campo dateRanges solo se incluye en el cuerpo de la respuesta de la primera página.
  • totalRowCount: La cantidad total de filas en el resultado del informe. El campo totalRowCount solo se incluye en el cuerpo de la respuesta de la primera página.
  • nextPageToken: Token para pasar en solicitudes posteriores para recuperar la siguiente página de filas. Si no existen filas adicionales, la API de Curation Partners omite este campo del cuerpo de la respuesta.

En el ejemplo de REST curators.reports.results.fetchRows, cada elemento de rows se asigna directamente a la ReportDefinition configurada en el informe:

  • dimensionValues: Contiene valores correspondientes a cada dimensión en el campo reportDefinition.dimensions en el orden exacto que especificaste. En el ejemplo, el primer valor 2026-08-01 corresponde a la dimensión DATE, y el segundo valor, segment-1001, corresponde a la dimensión CURATION_DATA_SEGMENT_ID.
  • metricValueGroups: Contiene valores de métricas agrupados en los intervalos de fechas del informe. En cada grupo, el campo primaryValues contiene los valores correspondientes a cada métrica en el campo reportDefinition.metrics en el orden exacto que especificaste. En este ejemplo, los cuatro valores corresponden a los siguientes valores de enumeración Metric:

    • IMPRESSIONS: 150000
    • CLICKS: 3200
    • SPEND: 450.75
    • CURATION_PARTNER_FEE: 45.08
  • dateRanges: Contiene el intervalo de fechas fijas que Google calculó para el intervalo relativo, THIS_MONTH_TO_DATE, configurado en la definición del informe.

Próximos pasos