Merchant API code sample to search report.

### AppsScript

    // Copyright 2025 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
    //
    //     https://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.


    /**
     * 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)
        const pageSize = 1000;
        let pageToken;
        // 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.
        const query = 'SELECT offer_id,' +
            'id,' +
            'price,' +
            'gtin,' +
            'item_issues,' +
            '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 {
          const 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);
        }
      }
    }



### Java

    // Copyright 2025 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
    //
    //     https://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 shopping.merchant.samples.reports.v1;

    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,"
                  + "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());
      }
    }

### Node.js

    // Copyright 2025 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
    //
    //     https://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.

    '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_v1/accounts.reports#ReportRow
      //
      // This is an example query for the product_view report.
      const query =
        'SELECT offer_id, id, price, gtin, item_issues, 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();

### PHP

    <?php
    /**
     * Copyright 2025 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
     *
     *     https://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.
     */

    require_once __DIR__ . '/../../../vendor/autoload.php';
    require_once __DIR__ . '/../../Authentication/Authentication.php';
    require_once __DIR__ . '/../../Authentication/Config.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_v1/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,"
                    . "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();

### Python

    # -*- coding: utf-8 -*-
    # Copyright 2025 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.
    """A module to search a report."""

    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_v1/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,"
          "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)