Esegui il polling e visualizza i report completati

Un'operazione di esecuzione del report viene eseguita in modo asincrono come operazione a lunga esecuzione, rappresentata dall' Operation oggetto. L'output di un'operazione di esecuzione del report sono i risultati del report basati sull' Report oggetto.

Questa guida descrive come utilizzare l'API Curation Partners per ottenere un'operazione di esecuzione del report per eseguire il polling dello stato dell'operazione, e recuperare i risultati del report dell'operazione di esecuzione del report completata.

Prima di iniziare

Prima di continuare, devi completare le seguenti operazioni:

Eseguire il polling dello stato di un'esecuzione del report

Per controllare lo stato di esecuzione di un'operazione di esecuzione del report, utilizza il curators.reports.operations.get metodo.

L'esempio seguente effettua una richiesta GET per eseguire il polling di un'operazione:

REST

Richiesta

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

Sostituisci quanto segue:

  • ACCOUNT_ID: il tuo ID account.
  • ACCESS_TOKEN: il tuo token di accesso.

Risposta

Se l'operazione viene completata correttamente, la risposta è un Operation con il campo done impostato su true e il payload response viene compilato con il nome della risorsa 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);
    }
  }
}

Di seguito viene descritto come utilizzare il campo done per eseguire il polling dello stato dell'operazione:

  • Se il campo done nella risposta è il valore false, l'operazione di esecuzione del report è ancora in fase di elaborazione.
  • Se il campo done nella risposta è il valore true, l'operazione di esecuzione del report è stata completata. L'oggetto Operation nel corpo della risposta contiene anche uno dei seguenti campi:
    • response: indica che l'operazione di esecuzione del report è andata a buon fine. Questo campo è un oggetto compilato con un campo @type impostato sul tipo type.googleapis.com/google.ads.curationpartners.v1.RunReportResponse. Il tipo RunReportResponse viene compilato con un campo reportResult contenente il nome del report corrispondente result.
    • error: indica che l'operazione di esecuzione del report non è andata a buon fine. Il campo error viene compilato con un Status oggetto che descrive il motivo per cui l'esecuzione del report non è riuscita.

Recuperare le righe da un report completato

Puoi recuperare i contenuti di un'operazione di esecuzione del report completata con il curators.reports.results.fetchRows metodo. Devi compilare il parametro di percorso name per il risultato del report, ovvero il nome della risorsa del campo reportResult di un'operazione di esecuzione del report completata.

L'esempio seguente effettua una richiesta GET per recuperare le righe dei risultati:

REST

Richiesta

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

Risposta

{
  "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);
    }
  }
}

Puoi specificare i seguenti parametri di query:

  • pageSize: il numero massimo di righe da restituire. Il valore predefinito è 1000 righe e il valore massimo è 10.000 righe.
  • pageToken: il token di pagina restituito in una risposta fetchRows precedente per recuperare il batch di righe successivo.

La risposta contiene i seguenti campi:

  • rows: un array di oggetti Row. Ogni riga contiene:
    • dimensionValues: valori per ogni dimensione richiesta, ordinati in modo identico alle dimensioni nella definizione del report.
    • metricValueGroups: gruppi di valori delle metriche corrispondenti agli intervalli di date. Ogni gruppo contiene un elenco primaryValues ordinato in modo identico alle metriche nella definizione del report.
  • dateRanges: gli intervalli di date fissi calcolati per il report. Il campo dateRanges è incluso solo nel corpo della risposta della prima pagina.
  • totalRowCount: il numero totale di righe nel risultato del report. Il campo totalRowCount è incluso solo nel corpo della risposta della prima pagina.
  • nextPageToken: token da passare nelle richieste successive per recuperare la pagina di righe successiva. Se non esistono altre righe, l'API Curation Partners omette questo campo dal corpo della risposta.

Nell'esempio REST curators.reports.results.fetchRows, ogni elemento in rows esegue il mapping diretto a ReportDefinition configurato nel report:

  • dimensionValues: contiene i valori corrispondenti a ogni dimensione nel campo reportDefinition.dimensions nell'ordine esatto specificato. Nell'esempio, il primo valore 2026-08-01 corrisponde alla dimensione DATE e il secondo valore, segment-1001, corrisponde alla dimensione CURATION_DATA_SEGMENT_ID.
  • metricValueGroups: contiene i valori delle metriche raggruppati negli intervalli di date del report. In ogni gruppo, il campo primaryValues contiene i valori corrispondenti a ogni metrica nel campo reportDefinition.metrics nell'ordine esatto specificato. In questo esempio, i quattro valori corrispondono ai seguenti valori enum Metric:

    • IMPRESSIONS: 150000
    • CLICKS: 3200
    • SPEND: 450.75
    • CURATION_PARTNER_FEE: 45.08
  • dateRanges: contiene l'intervallo di date fisso calcolato da Google per l'intervallo relativo, THIS_MONTH_TO_DATE, configurato nella definizione del report.

Passaggi successivi