A sub-API Reporting permite recuperar dados de performance e insights sobre produtos na sua conta do Merchant Center. É possível usar essa sub-API para fazer o seguinte:
- Identificar problemas com produtos.
- Descubra os produtos e marcas com melhor performance.
- Entenda melhor o panorama geral dos seus produtos.
Este guia mostra casos de uso comuns para ajudar você a usar os relatórios de maneira eficaz.
Você interage com a sub-API Reporting principalmente pelo método
reports.search. Esse método exige que você envie uma consulta escrita na linguagem de consulta do Merchant Center (MCQL, na sigla em inglês). Com a MCQL, é possível:
- Especifique os campos de dados a serem recuperados.
- Filtre os resultados com base em vários segmentos, como períodos ou códigos de países.
- Controle a ordem e os limites dos resultados.
Entenda a linguagem de consulta do Merchant Center
Para recuperar relatórios, envie consultas escritas na linguagem de consulta do Merchant Center (MCQL). Com ela, é possível selecionar dados de diferentes recursos (chamados de "visualizações", como product_performance_view ou product_view), filtrar por segmentos (como date ou marketing_method), selecionar métricas (como clicks ou impressions), ordenar os resultados e limitar o número deles.
Para informações detalhadas sobre a estrutura da linguagem de consulta e as visualizações, campos e métricas disponíveis, consulte a gramática da linguagem de consulta do Merchant Center.
Pré-requisitos
Antes de usar a sub-API Reporting, verifique se você tem uma conta do Merchant Center com dados de produtos.
Para dados específicos (relatórios de performance), você precisa ter a função Performance e insights. Para mais informações, consulte Preciso de ajuda com pessoas e níveis de acesso e Requisitos.
Exemplo: identificar problemas com o produto
Você pode identificar problemas que afetam seus produtos para tomar medidas corretivas. Isso ajuda você a manter a conformidade e melhorar a visibilidade dos seus produtos. Por exemplo, a consulta a seguir recupera todos os problemas dos produtos na sua conta, ajudando você a verificar se eles atendem aos requisitos de política e qualidade de dados.
Chamadas
POST https://merchantapi.googleapis.com/reports/v1/accounts/{ACCOUNT_ID}/reports:search
com o seguinte corpo da solicitação:
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'
vai gerar uma resposta como:
{
  "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"
          }
        ]
      }
    }
  ]
}
Os exemplos de código a seguir mostram como filtrar produtos reprovados.
Java
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'\''"
}'
Exemplo: pesquisar produtos
Os exemplos de código a seguir mostram como consultar atributos específicos do produto. É possível atualizar os exemplos de código a seguir para vários casos de uso comentando e removendo o comentário de consultas específicas.
Java
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"
}'