Lấy thông tin và xem báo cáo đã hoàn tất

Thao tác chạy báo cáo sẽ thực thi không đồng bộ dưới dạng một thao tác diễn ra trong thời gian dài, được biểu thị bằng đối tượng Operation. Đầu ra của một thao tác chạy báo cáo là kết quả báo cáo dựa trên đối tượng Report.

Hướng dẫn này mô tả cách bạn có thể sử dụng Curation Partners API để nhận một thao tác chạy báo cáo nhằm thăm dò trạng thái của thao tác đó và tìm nạp kết quả báo cáo của thao tác chạy báo cáo đã hoàn tất.

Trước khi bắt đầu

Trước khi tiếp tục, bạn phải hoàn tất các bước sau:

Lấy trạng thái của một lần chạy báo cáo

Để kiểm tra trạng thái thực thi của một thao tác chạy báo cáo, hãy sử dụng phương thức curators.reports.operations.get.

Ví dụ sau đây đưa ra yêu cầu GET để thăm dò một thao tác:

REST

Yêu cầu

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

Thay thế nội dung sau:

  • ACCOUNT_ID: mã tài khoản của bạn.
  • ACCESS_TOKEN: mã truy cập của bạn.

Phản hồi

Khi hoàn tất thành công, phản hồi sẽ là Operation với trường done được đặt thành true và tải trọng response được điền tên tài nguyên 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);
    }
  }
}

Sau đây mô tả cách bạn có thể sử dụng trường done để thăm dò trạng thái của thao tác:

  • Nếu trường done trong phản hồi là giá trị false, thì thao tác chạy báo cáo vẫn đang xử lý.
  • Nếu trường done trong phản hồi là giá trị true, thì thao tác chạy báo cáo đã hoàn tất. Đối tượng Operation trong phần nội dung phản hồi cũng chứa một trong các trường sau:
    • response: Cho biết thao tác chạy báo cáo đã thành công. Trường này là một đối tượng được điền sẵn bằng một trường @type được đặt thành loại type.googleapis.com/google.ads.curationpartners.v1.RunReportResponse. Loại RunReportResponse được điền sẵn bằng một trường reportResult chứa tên của báo cáo tương ứng result.
    • error: Cho biết rằng thao tác chạy báo cáo không thành công. Trường error được điền bằng một đối tượng Status mô tả lý do khiến quá trình chạy báo cáo không thành công.

Tìm nạp các hàng trong một báo cáo đã hoàn tất

Bạn có thể truy xuất nội dung của một thao tác chạy báo cáo đã hoàn tất bằng phương thức curators.reports.results.fetchRows. Bạn phải điền tham số đường dẫn name cho kết quả báo cáo, đây là tên tài nguyên trong trường reportResult của một thao tác chạy báo cáo hoàn chỉnh.

Ví dụ sau đây đưa ra yêu cầu GET để tìm nạp các hàng kết quả:

REST

Yêu cầu

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

Phản hồi

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

Bạn có thể chỉ định các tham số truy vấn sau:

  • pageSize: số lượng hàng tối đa cần trả về. Số hàng mặc định là 1.000 và số hàng tối đa là 10.000.
  • pageToken: mã thông báo trang được trả về trong phản hồi fetchRows trước đó để tìm nạp lô hàng tiếp theo của các hàng.

Phản hồi chứa các trường sau:

  • rows: Một mảng các đối tượng Row. Mỗi hàng chứa:
    • dimensionValues: Giá trị cho từng phương diện được yêu cầu, được sắp xếp giống hệt với các phương diện trong định nghĩa báo cáo.
    • metricValueGroups: Các nhóm giá trị chỉ số tương ứng với phạm vi ngày. Mỗi nhóm chứa một danh sách primaryValues được sắp xếp giống hệt với các chỉ số trong định nghĩa báo cáo.
  • dateRanges: Phạm vi ngày cố định được tính cho báo cáo. Trường dateRanges chỉ được đưa vào nội dung phản hồi của trang đầu tiên.
  • totalRowCount: Tổng số hàng trong kết quả báo cáo. Trường totalRowCount chỉ được đưa vào nội dung phản hồi của trang đầu tiên.
  • nextPageToken: Mã thông báo để truyền trong các yêu cầu tiếp theo nhằm truy xuất trang tiếp theo của các hàng. Nếu không có hàng nào khác, thì Curation Partners API sẽ bỏ qua trường này trong nội dung phản hồi.

Trong ví dụ về REST curators.reports.results.fetchRows, mỗi mục trong rows liên kết trực tiếp với ReportDefinition được định cấu hình trong báo cáo:

  • dimensionValues: chứa các giá trị tương ứng với từng phương diện trong trường reportDefinition.dimensions theo đúng thứ tự mà bạn đã chỉ định. Trong ví dụ này, giá trị đầu tiên 2026-08-01 tương ứng với phương diện DATE và giá trị thứ hai segment-1001 tương ứng với phương diện CURATION_DATA_SEGMENT_ID.
  • metricValueGroups: chứa các giá trị chỉ số được nhóm theo phạm vi ngày của báo cáo. Trong mỗi nhóm, trường primaryValues chứa các giá trị tương ứng với từng chỉ số trong trường reportDefinition.metrics theo đúng thứ tự mà bạn đã chỉ định. Trong ví dụ này, 4 giá trị tương ứng với các giá trị enum Metric sau:

    • IMPRESSIONS: 150000
    • CLICKS: 3200
    • SPEND: 450.75
    • CURATION_PARTNER_FEE: 45.08
  • dateRanges: chứa phạm vi ngày cố định mà Google đã tính toán cho phạm vi tương đối, THIS_MONTH_TO_DATE, được định cấu hình trong định nghĩa báo cáo.

Các bước tiếp theo