시작하기

Reporting 하위 API를 사용하면 판매자 센터 계정 내 제품에 관한 실적 데이터와 통계를 검색할 수 있습니다. 이 하위 API를 사용하여 다음 작업을 할 수 있습니다.

  • 제품 문제를 식별합니다.
  • 실적이 우수한 제품과 브랜드를 파악하세요.
  • 전반적인 제품 환경을 더 잘 파악할 수 있습니다.

이 가이드에서는 보고를 효과적으로 사용하는 데 도움이 되는 일반적인 사용 사례를 설명합니다.

주로 reports.search 메서드를 통해 Reporting 하위 API와 상호작용합니다. 이 방법을 사용하려면 판매자 센터 쿼리 언어 (MCQL)로 작성된 쿼리를 제출해야 합니다. MCQL을 사용하면 다음 작업을 할 수 있습니다.

  • 가져올 데이터 필드를 지정합니다.
  • 기간 또는 국가 코드와 같은 다양한 세그먼트를 기준으로 결과를 필터링합니다.
  • 결과의 순서와 제한을 제어합니다.

판매자 센터 쿼리 언어 이해하기

판매자 센터 쿼리 언어 (MCQL)로 작성된 쿼리를 전송하여 보고서를 가져옵니다. 이 언어를 사용하면 다양한 리소스(product_performance_view 또는 product_view과 같은 '뷰')에서 데이터를 선택하고, 세그먼트 (예: date 또는 marketing_method)별로 필터링하고, 측정항목 (예: clicks 또는 impressions)을 선택하고, 결과를 정렬하고, 결과 수를 제한할 수 있습니다.

쿼리 언어 구조와 사용 가능한 뷰, 필드, 측정항목에 관한 자세한 내용은 판매자 센터 쿼리 언어 문법을 참고하세요.

기본 요건

Reporting 하위 API를 사용하기 전에 제품 데이터가 포함된 판매자 센터 계정이 있는지 확인하세요.

특정 데이터 (실적 보고서)의 경우 실적 및 통계 역할이 있어야 합니다. 자세한 내용은 사용자 및 액세스 수준에 관한 도움이 필요합니다요구사항을 참고하세요.

예: 제품 문제 식별

제품에 영향을 미치는 문제를 파악하여 수정 조치를 취할 수 있습니다. 이렇게 하면 규정을 준수하고 제품의 노출 가능성을 높일 수 있습니다. 예를 들어 다음 쿼리는 계정의 제품에 대한 모든 문제를 가져와 제품이 정책 및 데이터 품질 요구사항을 충족하는지 확인할 수 있도록 지원합니다.

전화

POST https://merchantapi.googleapis.com/reports/v1/accounts/{ACCOUNT_ID}/reports:search

요청 본문은 다음과 같습니다.

SELECT
  id,
  offer_id,
  feed_label,
  title,
  aggregated_reporting_context_status,
  item_issues
FROM product_view
WHERE aggregated_reporting_context_status = 'NOT_ELIGIBLE_OR_DISAPPROVED'

다음과 같은 응답이 생성됩니다.

{
  "results": [
    {
      "productView": {
        "id": "en~US~id0"
        "offerId": "id0",
        "feedLabel": "US",
        "aggregatedReportingContextStatus": "NOT_ELIGIBLE_OR_DISAPPROVED",
        "itemIssues": [
          {
            "type": {
              "code": "invalid_string_value",
              "canonicalAttribute": "n:product_code"
            },
            "severity": {
              "severityPerReportingContext": [
                {
                  "reportingContext": "SHOPPING_ADS",
                  "disapprovedCountries": [
                    "US"
                  ]
                },
                {
                  "reportingContext": "FREE_LISTINGS",
                  "disapprovedCountries": [
                    "US"
                  ]
                }
              ],
              "aggregatedSeverity": "DISAPPROVED"
            },
            "resolution": "MERCHANT_ACTION"
          },
          {
            "type": {
              "code": "apparel_missing_brand",
              "canonicalAttribute": "n:brand"
            },
            "severity": {
              "severityPerReportingContext": [
                {
                  "reportingContext": "SHOPPING_ADS",
                  "disapprovedCountries": [
                    "US"
                  ]
                }
              ],
              "aggregatedSeverity": "DEMOTED"
            },
            "resolution": "MERCHANT_ACTION"
          }
        ]
      }
    }
  ]
}

다음 코드 샘플은 비승인 상품을 필터링하는 방법을 보여줍니다.

자바

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.products.v1.GetProductRequest;
import com.google.shopping.merchant.products.v1.Product;
import com.google.shopping.merchant.products.v1.ProductsServiceClient;
import com.google.shopping.merchant.products.v1.ProductsServiceSettings;
import com.google.shopping.merchant.reports.v1.ReportRow;
import com.google.shopping.merchant.reports.v1.ReportServiceClient;
import com.google.shopping.merchant.reports.v1.ReportServiceClient.SearchPagedResponse;
import com.google.shopping.merchant.reports.v1.ReportServiceSettings;
import com.google.shopping.merchant.reports.v1.SearchRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/**
 * This class demonstrates how to get the list of all the disapproved products for a given merchant
 * center account.
 */
public class FilterDisapprovedProductsSample {

  // Gets the product details for a given product using the GetProduct method.
  public static void getProduct(GoogleCredentials credential, Config config, String productName)
      throws Exception {

    // Creates service settings using the credentials retrieved above.
    ProductsServiceSettings productsServiceSettings =
        ProductsServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    // Calls the API and catches and prints any network failures/errors.
    try (ProductsServiceClient productsServiceClient =
        ProductsServiceClient.create(productsServiceSettings)) {

      // The name has the format: accounts/{account}/products/{productId}
      GetProductRequest request = GetProductRequest.newBuilder().setName(productName).build();
      Product response = productsServiceClient.getProduct(request);
      System.out.println(response);
    } catch (Exception e) {
      System.out.println(e);
    }
  }

  // Filters the disapproved products for a given Merchant Center account using the Reporting API.
  // Then, it prints the product details for each disapproved product.
  public static void filterDisapprovedProducts(Config config) throws Exception {
    GoogleCredentials credential = new Authenticator().authenticate();

    ReportServiceSettings reportServiceSettings =
        ReportServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    try (ReportServiceClient reportServiceClient =
        ReportServiceClient.create(reportServiceSettings)) {

      // The parent has the format: accounts/{accountId}
      String parent = String.format("accounts/%s", config.getAccountId().toString());
      // The query below is an example of a query for the productView that gets product informations
      // for all disapproved products.
      String query =
          "SELECT offer_id,"
              + "id,"
              + "title,"
              + "price"
              + " FROM product_view"
              // aggregated_reporting_context_status can be one of the following values:
              // NOT_ELIGIBLE_OR_DISAPPROVED, ELIGIBLE, PENDING, ELIGIBLE_LIMITED,
              // AGGREGATED_REPORTING_CONTEXT_STATUS_UNSPECIFIED
              + " WHERE aggregated_reporting_context_status = 'NOT_ELIGIBLE_OR_DISAPPROVED'";

      // Create the search report request.
      SearchRequest request = SearchRequest.newBuilder().setParent(parent).setQuery(query).build();

      System.out.println("Sending search report request for Product View.");
      // Calls the Reports.search API method.
      SearchPagedResponse response = reportServiceClient.search(request);
      System.out.println("Received search reports response: ");
      // Iterates over all report rows in all pages and prints each report row in separate line.
      // Automatically uses the `nextPageToken` if returned to fetch all pages of data.
      for (ReportRow row : response.iterateAll()) {
        System.out.println("Printing data from Product View:");
        System.out.println(row);
        // Optionally, you can get the full product details by calling the GetProduct method.
        String productName =
            "accounts/"
                + config.getAccountId().toString()
                + "/products/"
                + row.getProductView().getId();
        System.out.println("Getting full product details by calling GetProduct method:");
        getProduct(credential, config, productName);
      }

    } catch (Exception e) {
      System.out.println("Failed to search reports for Product View.");
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    filterDisapprovedProducts(config);
  }
}

Apps Script


/**
 * Demonstrates how to filter disapproved products using the Merchant API Reports service.
 */
function filterDisapprovedProducts() {
  // IMPORTANT:
  // Enable the Merchant API Reports sub-API Advanced Service and call it
  // "MerchantApiReports"
  // Enable the Merchant API Products sub-API Advanced Service and call it
  // "MerchantApiProducts"

  // Replace this with your Merchant Center ID.
  const accountId = '<INSERT_MERCHANT_CENTER_ID>';

  // Construct the parent name
  const parent = 'accounts/' + accountId;

  try {
    console.log('Sending search Report request');
    // Set pageSize to the maximum value (default: 1000)
    let pageSize = 1000;
    let pageToken;
    // The query below is an example of a query for the productView that gets product informations
    // for all disapproved products.
    let query = 'SELECT offer_id,' +
        'id,' +
        'price,' +
        'title' +
        ' FROM product_view' +
        ' WHERE aggregated_reporting_context_status = "NOT_ELIGIBLE_OR_DISAPPROVED"';


    // Call the Reports.search API method. Use the pageToken to iterate through
    // all pages of results.
    do {
      response =
          MerchantApiReports.Accounts.Reports.search({query, pageSize, pageToken}, parent);
      for (const reportRow of response.results) {
        console.log("Printing data from Product View:");
        console.log(reportRow);

        // OPTIONALLY, you can get the full product details by calling the GetProduct method.
        let productName = parent + "/products/" + reportRow.getProductView().getId();
        product = MerchantApiProducts.Accounts.Products.get(productName);
        console.log(product);
      }
      pageToken = response.nextPageToken;
    } while (pageToken);  // Exits when there is no next page token.

  } catch (e) {
    console.log('ERROR!');
    console.log('Error message:' + e.message);
  }
}

PHP

use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\Products\V1\Client\ProductsServiceClient;
use Google\Shopping\Merchant\Products\V1\GetProductRequest;
use Google\Shopping\Merchant\Reports\V1\Client\ReportServiceClient;
use Google\Shopping\Merchant\Reports\V1\SearchRequest;

/**
 * This class demonstrates how to get the list of all the disapproved products for a given merchant
 * center account.
 */
class FilterDisapprovedProducts
{
    /**
     * Gets the product details for a given product using the GetProduct method.
     *
     * @param mixed $credentials The OAuth credentials.
     * @param array $config The configuration data, including 'accountId'.
     * @param string $productName The full resource name of the product to retrieve.
     *      Format: accounts/{account}/products/{product}
     */
    private static function getProduct(
        $credentials,
        array $config,
        string $productName
    ): void {
        // Creates options config containing credentials for the client to use.
        $options = ['credentials' => $credentials];

        // Creates a ProductsServiceClient.
        $productsServiceClient = new ProductsServiceClient($options);

        // Calls the API and catches and prints any network failures/errors.
        try {
            // Construct the GetProductRequest.
            // The name has the format: accounts/{account}/products/{productId}
            $request = new GetProductRequest(['name' => $productName]);

            // Make the API call.
            $response = $productsServiceClient->getProduct($request);

            // Prints the retrieved product.
            // Protobuf messages are printed as JSON strings for readability.
            print $response->serializeToJsonString() . "\n";
        } catch (ApiException $e) {
            // Prints any errors that occur during the API call.
            printf("ApiException was thrown: %s\n", $e->getMessage());
        }
    }

    /**
     * Filters disapproved products for a given Merchant Center account using the Reporting API,
     * then prints the details for each disapproved product.
     *
     * @param array $config The configuration data used for authentication and
     *      getting the account ID.
     */
    public static function filterDisapprovedProductsSample(array $config): void
    {
        // Gets the OAuth credentials to make the request.
        $credentials = Authentication::useServiceAccountOrTokenFile();

        // Creates options config containing credentials for the Report client to use.
        $reportClientOptions = ['credentials' => $credentials];

        // Creates a ReportServiceClient.
        $reportServiceClient = new ReportServiceClient($reportClientOptions);

        // The parent resource name for the report.
        // Format: accounts/{accountId}
        $parent = sprintf("accounts/%s", $config['accountId']);

        // The query to select disapproved products from the product_view.
        // This query retrieves offer_id, id, title, and price for products
        // that are 'NOT_ELIGIBLE_OR_DISAPPROVED'.
        $query = "SELECT offer_id, id, title, price FROM product_view"
            . " WHERE aggregated_reporting_context_status = 'NOT_ELIGIBLE_OR_DISAPPROVED'";

        // Create the search report request.
        $request = new SearchRequest([
            'parent' => $parent,
            'query' => $query
        ]);

        print "Sending search report request for Product View.\n";
        // Calls the Reports.search API method.
        try {
            $response = $reportServiceClient->search($request);
            print "Received search reports response: \n";

            // Iterates over all report rows in all pages.
            // The client library automatically handles pagination.
            foreach ($response->iterateAllElements() as $row) {
                print "Printing data from Product View:\n";
                // Prints the ReportRow object as a JSON string.
                print $row->serializeToJsonString() . "\n";

                // Get the full product resource name from the report row.
                // The `id` field in ProductView is the product's full resource name.
                // Format: `accounts/{account}/products/{product}`
                $productName = $parent . "/products/" . $row->getProductView()->getId();
                // OPTIONAL: Call getProduct to retrieve and print full product details.
                // Pass the original credentials and config.
                print "Getting full product details by calling GetProduct method:\n";
                self::getProduct($credentials, $config, $productName);
            }
        } catch (ApiException $e) {
            // Prints any errors that occur during the API call.
            printf("ApiException was thrown: %s\n", $e->getMessage());
        }
    }

    /**
     * Helper to execute the sample.
     */
    public function callSample(): void
    {
        $config = Config::generateConfig();
        self::filterDisapprovedProductsSample($config);
    }
}

// Run the script
$sample = new FilterDisapprovedProducts();
$sample->callSample();

Python

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_products_v1 import GetProductRequest
from google.shopping.merchant_products_v1 import ProductsServiceClient
from google.shopping.merchant_reports_v1 import ReportServiceClient
from google.shopping.merchant_reports_v1 import SearchRequest

# Read the merchant account ID from the configuration file.
# This is a global variable used by the functions below.
_ACCOUNT_ID = configuration.Configuration().read_merchant_info()


def get_product(credentials, product_name: str):
  """Gets the product details for a given product name.

  Args:
    credentials: The OAuth2 credentials.
    product_name: The full resource name of the product, e.g.,
      "accounts/{account}/products/{product}".
  """
  # Create a Products API client.
  products_service_client = ProductsServiceClient(credentials=credentials)

  # Prepare the GetProduct request.
  # The name has the format: accounts/{account}/products/{productId}
  request = GetProductRequest(name=product_name)

  # Call the API and print the response or any errors.
  try:
    response = products_service_client.get_product(request=request)
    print(response)
  except RuntimeError as e:
    print(f"Failed to get product {product_name}:")
    print(e)


def filter_disapproved_products():
  """Filters disapproved products and prints their details."""
  # Get OAuth2 credentials.
  credentials = generate_user_credentials.main()

  # Create a Report API client.
  report_service_client = ReportServiceClient(credentials=credentials)

  # Construct the parent resource name for the account.
  # The parent has the format: accounts/{accountId}
  parent = f"accounts/{_ACCOUNT_ID}"

  # Define the query to select disapproved products.
  # This query retrieves product information for all disapproved products.
  # aggregated_reporting_context_status can be one of the following values:
  # NOT_ELIGIBLE_OR_DISAPPROVED, ELIGIBLE, PENDING, ELIGIBLE_LIMITED,
  # AGGREGATED_REPORTING_CONTEXT_STATUS_UNSPECIFIED
  query = (
      "SELECT offer_id, id, title, price "
      "FROM product_view "
      "WHERE aggregated_reporting_context_status ="
      "'NOT_ELIGIBLE_OR_DISAPPROVED'"
  )

  # Create the search report request.
  request = SearchRequest(parent=parent, query=query)

  print("Sending search report request for Product View.")
  try:
    # Call the Reports.search API method.
    response = report_service_client.search(request=request)
    print("Received search reports response: ")

    # Iterate over all report rows.
    # The client library automatically handles pagination.
    for row in response:
      print("Printing data from Product View:")
      print(row)

      # Construct the full product resource name using the product_view.id
      # (which is the REST ID like "online~en~GB~123") from the report.
      # The product_view.id from the report is the {product_id} part.
      product_name = (
          f"accounts/{_ACCOUNT_ID}/products/{row.product_view.id}"
      )

      # OPTIONAL, get full product details by calling the GetProduct method.
      print("Getting full product details by calling GetProduct method:")
      get_product(credentials, product_name)

  except RuntimeError as e:
    print(e)


if __name__ == "__main__":
  filter_disapproved_products()

cURL

curl -X POST -i \
-H "Authorization: Bearer <API_TOKEN>" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
"https://merchantapi.googleapis.com/reports/v1/accounts/{ACCOUNT_ID}/reports:search" \
-d '{
  "query": "SELECT offer_id, id, title, price FROM product_view WHERE aggregated_reporting_context_status = '\''NOT_ELIGIBLE_OR_DISAPPROVED'\''"
}'

예: 제품 검색

다음 코드 샘플은 특정 제품 속성을 쿼리하는 방법을 보여줍니다. 특정 쿼리를 주석 처리하거나 주석 처리를 해제하여 다양한 사용 사례에 맞게 다음 코드 샘플을 업데이트할 수 있습니다.

자바

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.reports.v1.ReportRow;
import com.google.shopping.merchant.reports.v1.ReportServiceClient;
import com.google.shopping.merchant.reports.v1.ReportServiceClient.SearchPagedResponse;
import com.google.shopping.merchant.reports.v1.ReportServiceSettings;
import com.google.shopping.merchant.reports.v1.SearchRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to search reports for a given Merchant Center account. */
public class SearchReportSample {

  public static void searchReports(String accountId) throws Exception {
    GoogleCredentials credential = new Authenticator().authenticate();

    ReportServiceSettings reportServiceSettings =
        ReportServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    try (ReportServiceClient reportServiceClient =
        ReportServiceClient.create(reportServiceSettings)) {

      // The parent has the format: accounts/{accountId}
      String parent = String.format("accounts/%s", accountId);

      // Uncomment the desired query from below. Documentation can be found at
      // https://developers.google.com/merchant/api/reference/rest/reports_v1/accounts.reports#ReportRow
      // The query below is an example of a query for the product_view.
      String query =
          "SELECT offer_id,"
              + "id,"
              + "price,"
              + "gtin,"
              + "item_issues,"
              + "channel,"
              + "language_code,"
              + "feed_label,"
              + "title,"
              + "brand,"
              + "category_l1,"
              + "product_type_l1,"
              + "availability,"
              + "shipping_label,"
              + "thumbnail_link,"
              + "click_potential"
              + " FROM product_view";

      /*
      // The query below is an example of a query for the price_competitiveness_product_view.
      String query =
              "SELECT offer_id,"
                   + "id,"
                   + "benchmark_price,"
                   + "report_country_code,"
                   + "price,"
                   + "title,"
                   + "brand,"
                   + "category_l1,"
                   + "product_type_l1"
                  + " FROM price_competitiveness_product_view"
                  + " WHERE date BETWEEN '2023-03-03' AND '2025-03-10'"; */
      /*
      // The query below is an example of a query for the price_insights_product_view.
      String query =
                  "SELECT offer_id,"
                       + "id,"
                       + "suggested_price,"
                       + "price,"
                       + "effectiveness,"
                       + "title,"
                       + "brand,"
                       + "category_l1,"
                       + "product_type_l1,"
                       + "predicted_impressions_change_fraction,"
                       + "predicted_clicks_change_fraction,"
                       + "predicted_conversions_change_fraction"
                      + " FROM price_insights_product_view"; */

      /*
      // The query below is an example of a query for the product_performance_view.
      String query =
          "SELECT offer_id,"
              + "conversion_value,"
              + "marketing_method,"
              + "customer_country_code,"
              + "title,"
              + "brand,"
              + "category_l1,"
              + "product_type_l1,"
              + "custom_label0,"
              + "clicks,"
              + "impressions,"
              + "click_through_rate,"
              + "conversions,"
              + "conversion_rate"
              + " FROM product_performance_view"
              + " WHERE date BETWEEN '2023-03-03' AND '2025-03-10'"; */

      // Create the search report request.
      SearchRequest request = SearchRequest.newBuilder().setParent(parent).setQuery(query).build();

      System.out.println("Sending search reports request.");
      SearchPagedResponse response = reportServiceClient.search(request);
      System.out.println("Received search reports response: ");
      // Iterates over all report rows in all pages and prints the report row in each row.
      // Automatically uses the `nextPageToken` if returned to fetch all pages of data.
      for (ReportRow row : response.iterateAll()) {
        System.out.println(row);
      }

    } catch (Exception e) {
      System.out.println("Failed to search reports.");
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    searchReports(config.getAccountId().toString());
  }
}

Apps Script


/**
 * Searches a report for a given Merchant Center account.
 */
function searchReport() {
  // IMPORTANT:
  // Enable the Merchant API Reports sub-API Advanced Service and call it
  // "MerchantApiReports"

  // Replace this with your Merchant Center ID.
  const accountId = '<MERCHANT_CENTER_ID>';

  // Construct the parent name
  const parent = 'accounts/' + accountId;

  try {
    console.log('Sending search Report request');
    // Set pageSize to the maximum value (default: 1000)
    let pageSize = 1000;
    let pageToken;
    // Uncomment the desired query from below. Documentation can be found at
    // https://developers.google.com/merchant/api/reference/rest/reports_v1beta/accounts.reports#ReportRow
    // The query below is an example of a query for the product_view.
    let query = 'SELECT offer_id,' +
        'id,' +
        'price,' +
        'gtin,' +
        'item_issues,' +
        'channel,' +
        'language_code,' +
        'feed_label,' +
        'title,' +
        'brand,' +
        'category_l1,' +
        'product_type_l1,' +
        'availability,' +
        'shipping_label,' +
        'thumbnail_link,' +
        'click_potential' +
        ' FROM product_view';

    /*
    // The query below is an example of a query for the
    price_competitiveness_product_view. let query = "SELECT offer_id,"
                 + "id,"
                 + "benchmark_price,"
                 + "report_country_code,"
                 + "price,"
                 + "title,"
                 + "brand,"
                 + "category_l1,"
                 + "product_type_l1"
                + " FROM price_competitiveness_product_view"
                + " WHERE date BETWEEN '2023-03-03' AND '2025-03-10'"; */
    /*
    // The query below is an example of a query for the
    price_insights_product_view. let query = "SELECT offer_id,"
                     + "id,"
                     + "suggested_price,"
                     + "price,"
                     + "effectiveness,"
                     + "title,"
                     + "brand,"
                     + "category_l1,"
                     + "product_type_l1,"
                     + "predicted_impressions_change_fraction,"
                     + "predicted_clicks_change_fraction,"
                     + "predicted_conversions_change_fraction"
                    + " FROM price_insights_product_view"; */

    /*
    // The query below is an example of a query for the
    product_performance_view. let query = "SELECT offer_id,"
            + "conversion_value,"
            + "marketing_method,"
            + "customer_country_code,"
            + "title,"
            + "brand,"
            + "category_l1,"
            + "product_type_l1,"
            + "custom_label0,"
            + "clicks,"
            + "impressions,"
            + "click_through_rate,"
            + "conversions,"
            + "conversion_rate"
            + " FROM product_performance_view"
            + " WHERE date BETWEEN '2023-03-03' AND '2025-03-10'"; */

    // Call the Reports.search API method. Use the pageToken to iterate through
    // all pages of results.
    do {
      response =
          MerchantApiReports.Accounts.Reports.search({query, pageSize, pageToken}, parent);
      for (const reportRow of response.results) {
        console.log(reportRow);
      }
      pageToken = response.nextPageToken;
    } while (pageToken);  // Exits when there is no next page token.

  } catch (e) {
    console.log('ERROR!');
    console.log(e);
    console.log('Error message:' + e.message);
    if (e.stack) {
      console.log('Stack trace:' + e.stack);
    }
  }
}


PHP

use Google\Shopping\Merchant\Reports\V1\Client\ReportServiceClient;
use Google\Shopping\Merchant\Reports\V1\SearchRequest;

/**
 * This class demonstrates how to search reports for a given Merchant Center account.
 */
class SearchReportSample
{
    /**
     * A helper function to create the parent string.
     *
     * @param string $accountId
     *      The account that owns the report.
     *
     * @return string The parent has the format: `accounts/{account_id}`
     */
    private static function getParent($accountId)
    {
        return sprintf("accounts/%s", $accountId);
    }

    /**
     * Searches reports for a given Merchant Center account.
     *
     * @param array $config
     *      The configuration data used for authentication and getting the account ID.
     * @throws \Google\ApiCore\ApiException
     */
    public static function searchReports($config)
    {
        // Gets the OAuth credentials to make the request.
        $credentials = Authentication::useServiceAccountOrTokenFile();

        // Creates options config containing credentials for the client to use.
        $options = ['credentials' => $credentials];

        // Creates a client.
        $reportServiceClient = new ReportServiceClient($options);

        // The parent has the format: accounts/{accountId}
        $parent = self::getParent($config['accountId']);

        // Uncomment the desired query from below. Documentation can be found at
        // https://developers.google.com/merchant/api/reference/rest/reports_v1beta/accounts.reports#ReportRow
        // The query below is an example of a query for the product_view.
        $query =
            "SELECT offer_id,"
                . "id,"
                . "price,"
                . "gtin,"
                . "item_issues,"
                . "channel,"
                . "language_code,"
                . "feed_label,"
                . "title,"
                . "brand,"
                . "category_l1,"
                . "product_type_l1,"
                . "availability,"
                . "shipping_label,"
                . "thumbnail_link,"
                . "click_potential"
                . " FROM product_view"; 

      /*
      // The query below is an example of a query for the price_competitiveness_product_view.
      $query =
            "SELECT offer_id,"
                . "id,"
                . "benchmark_price,"
                . "report_country_code,"
                . "price,"
                . "title,"
                . "brand,"
                . "category_l1,"
                . "product_type_l1"
                . " FROM price_competitiveness_product_view"
                . " WHERE date BETWEEN '2023-03-03' AND '2025-03-10'"; */
      /*
      // The query below is an example of a query for the price_insights_product_view.
      $query =
            "SELECT offer_id,"
                . "id,"
                . "suggested_price,"
                . "price,"
                . "effectiveness,"
                . "title,"
                . "brand,"
                . "category_l1,"
                . "product_type_l1,"
                . "predicted_impressions_change_fraction,"
                . "predicted_clicks_change_fraction,"
                . "predicted_conversions_change_fraction"
                . " FROM price_insights_product_view"; */

        /*
        // The query below is an example of a query for the product_performance_view.
        $query =
            "SELECT offer_id,"
                . "conversion_value,"
                . "marketing_method,"
                . "customer_country_code,"
                . "title,"
                . "brand,"
                . "category_l1,"
                . "product_type_l1,"
                . "custom_label0,"
                . "clicks,"
                . "impressions,"
                . "click_through_rate,"
                . "conversions,"
                . "conversion_rate"
                . " FROM product_performance_view"
                . " WHERE date BETWEEN '2023-03-03' AND '2025-03-10'"; */

        // Create the search report request.
        $request = new SearchRequest(
            [
                'parent' => $parent,
                'query' => $query,
            ]
        );

        print "Sending search reports request.\n";
        // Calls the API and catches and prints any network failures/errors.
        try {
            $response = $reportServiceClient->search($request);
            print "Received search reports response: \n";
            // Iterates over all report rows in all pages and prints the report row in each row.
            // Automatically uses the `nextPageToken` if returned to fetch all pages of data.
            foreach ($response->iterateAllElements() as $row) {
                print_r($row);
            }
        } catch (\Google\ApiCore\ApiException $e) {
            print "Failed to search reports.\n";
            print $e->getMessage() . "\n";
        }
    }

    /**
     * Helper to execute the sample.
     *
     * @return void
     * @throws \Google\ApiCore\ApiException
     */
    public function callSample(): void
    {
        $config = Config::generateConfig();
        self::searchReports($config);
    }
}

// Run the script
$sample = new SearchReportSample();
$sample->callSample();

JavaScript

'use strict';
const fs = require('fs');
const authUtils = require('../../authentication/authenticate.js');
const {ReportServiceClient} = require('@google-shopping/reports').v1;

/**
 * Searches reports for a given Merchant Center account and prints them.
 * @param {string} accountId The Merchant Center account ID.
 */
async function searchAndPrintReports(accountId) {
  // Authenticate and get the auth client using the utility from the example.
  const authClient = await authUtils.getOrGenerateUserCredentials();

  // Configure the client with authentication details.
  const clientOptions = {authClient: authClient};

  // Instantiate the Report Service Client.
  const reportServiceClient = new ReportServiceClient(clientOptions);

  // Construct the parent resource name required by the API.
  // The format is "accounts/{accountId}".
  const parent = `accounts/${accountId}`;

  // Define the Merchant Query Language (MQL) query.
  // The commented-out queries below are examples for different report types.
  // For detailed documentation on MQL and available fields, refer to:
  // https://developers.google.com/merchant/api/reference/rest/reports_v1beta/accounts.reports#ReportRow
  //
  // This is an example query for the product_view report.
  let query =
      'SELECT offer_id, id, price, gtin, item_issues, channel, language_code, ' +
      'feed_label, title, brand, category_l1, product_type_l1, availability, ' +
      'shipping_label, thumbnail_link, click_potential ' +
      'FROM product_view';

  /*
  // An example query for the price_competitiveness_product_view report.
  query =
    'SELECT offer_id, id, benchmark_price, report_country_code, price, title, '
  + 'brand, category_l1, product_type_l1 ' + "FROM
  price_competitiveness_product_view " + "WHERE date BETWEEN '2023-03-03' AND
  '2025-03-10'";
  */
  /*
  // An example query for the price_insights_product_view report.
  query =
    'SELECT offer_id, id, suggested_price, price, effectiveness, title, brand, '
  + 'category_l1, product_type_l1, predicted_impressions_change_fraction, ' +
    'predicted_clicks_change_fraction, predicted_conversions_change_fraction ' +
    'FROM price_insights_product_view';
  */
  /*
  // An example query for the product_performance_view report.
  query =
    'SELECT offer_id, conversion_value, marketing_method, customer_country_code,
  ' + 'title, brand, category_l1, product_type_l1, custom_label0, clicks, ' +
    'impressions, click_through_rate, conversions, conversion_rate ' +
    "FROM product_performance_view " +
    "WHERE date BETWEEN '2023-03-03' AND '2025-03-10'";
  */

  // Prepare the search request object for the API call.
  const request = {
    parent: parent,
    query: query,
    // pageSize: 100 // Optional: Define the number of results per page.
    // The API will use a default page size if not specified.
  };

  console.log('Sending search reports request.');
  // Call the `search` method of the ReportServiceClient.
  // This method returns an iterable that yields each ReportRow.
  const response = await reportServiceClient.search(request);

  console.log('Received search reports response: ');
  // Iterate through each row in the response stream and print it to the
  // console. The client library transparently handles pagination to fetch all
  // results.
  for await (const row of response) {
    // Each 'row' is a ReportRow protobuf message object.
    console.log(row);  // Prints the object, typically in a compact format.
  }
}

/**
 * Main function that orchestrates the script.
 */
async function main() {
  try {
    // Load application configuration, e.g., path to credentials and merchant
    // info.
    const config = authUtils.getConfig();

    // Read the merchant ID (referred to as accountId in this API context)
    // from the JSON configuration file specified in the config.
    const merchantInfo =
        JSON.parse(fs.readFileSync(config.merchantInfoFile, 'utf8'));
    const accountId = merchantInfo.merchantId;

    // Execute the core logic to search and print reports.
    await searchAndPrintReports(accountId.toString());

  } catch (error) {
    console.log('Failed to search reports.');
    console.log(error);
  }
}

main();

Python

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_reports_v1 import ReportServiceClient
from google.shopping.merchant_reports_v1 import SearchRequest

_ACCOUNT = configuration.Configuration().read_merchant_info()


def search_report(account_id):
  """Searches a report for a given Merchant Center account."""

  # Gets OAuth Credentials.
  credentials = generate_user_credentials.main()

  # Creates a client.
  report_service_client = ReportServiceClient(credentials=credentials)

  # The parent has the format: accounts/{accountId}
  parent = f"accounts/{account_id}"

  # Uncomment the desired query from below. Documentation can be found at
  # https://developers.google.com/merchant/api/reference/rest/reports_v1beta/accounts.reports#ReportRow
  # The query below is an example of a query for the product_view.
  query = (
      "SELECT offer_id,"
      "id,"
      "price,"
      "gtin,"
      "item_issues,"
      "channel,"
      "language_code,"
      "feed_label,"
      "title,"
      "brand,"
      "category_l1,"
      "product_type_l1,"
      "availability,"
      "shipping_label,"
      "thumbnail_link,"
      "click_potential"
      " FROM product_view"
  )

  # The query below is an example of a query for the
  # price_competitiveness_product_view.
  # query = (
  #     "SELECT offer_id,"
  #     "id,"
  #     "benchmark_price,"
  #     "report_country_code,"
  #     "price,"
  #     "title,"
  #     "brand,"
  #     "category_l1,"
  #     "product_type_l1"
  #     " FROM price_competitiveness_product_view"
  #     " WHERE date BETWEEN '2023-03-03' AND '2025-03-10'"
  # )

  # The query below is an example of a query for the
  # price_insights_product_view.
  # query = (
  #     "SELECT offer_id,"
  #     "id,"
  #     "suggested_price,"
  #     "price,"
  #     "effectiveness,"
  #     "title,"
  #     "brand,"
  #     "category_l1,"
  #     "product_type_l1,"
  #     "predicted_impressions_change_fraction,"
  #     "predicted_clicks_change_fraction,"
  #     "predicted_conversions_change_fraction"
  #     " FROM price_insights_product_view"
  # )

  # The query below is an example of a query for the product_performance_view.
  # query = (
  #   "SELECT offer_id,"
  #    "conversion_value,"
  #    "marketing_method,"
  #    "customer_country_code,"
  #    "title,"
  #    "brand,"
  #    "category_l1,"
  #    "product_type_l1,"
  #    "custom_label0,"
  #    "clicks,"
  #    "impressions,"
  #    "click_through_rate,"
  #    "conversions,"
  #    "conversion_rate"
  #    " FROM product_performance_view"
  #    " WHERE date BETWEEN '2023-03-03' AND '2025-03-10'"
  # )

  # Create the search report request.
  request = SearchRequest(parent=parent, query=query)

  print("Sending search reports request.")
  try:
    response = report_service_client.search(request=request)
    print("Received search reports response: ")
    # Iterates over all report rows in all pages and prints the report row in
    # each row. Automatically uses the `nextPageToken` if returned to fetch all
    # pages of data.
    for row in response:
      print(row)
  except RuntimeError as e:
    print("Failed to search reports.")
    print(e)


if __name__ == "__main__":
  search_report(_ACCOUNT)

cURL

curl -X POST -i \
-H "Authorization: Bearer <API_TOKEN>" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
"https://merchantapi.googleapis.com/reports/v1/accounts/{ACCOUNT_ID}/reports:search" \
-d '{
  "query": "SELECT offer_id, title, price FROM product_view"
}'