La sotto-API Reporting ti consente di recuperare dati sul rendimento e approfondimenti sui prodotti all'interno del tuo account Merchant Center. Puoi utilizzare questa API secondaria per:
- Identifica i problemi relativi ai prodotti.
- Scopri i tuoi prodotti e brand con il rendimento migliore.
- Comprendi meglio il panorama generale dei tuoi prodotti.
Questa guida illustra i casi d'uso comuni per aiutarti a utilizzare i report in modo efficace.
Interagisci con l'API secondaria Reporting principalmente tramite il metodo
reports.search
. Questo metodo richiede l'invio di una query scritta nel linguaggio di query di Merchant Center (MCQL). MCQL ti consente di:
- Specifica i campi di dati da recuperare.
- Filtra i risultati in base a vari segmenti, ad esempio intervalli di date o codici paese.
- Controlla l'ordinamento e i limiti dei risultati.
Informazioni sul linguaggio di query di Merchant Center
Recuperi i report inviando query scritte nel linguaggio di query di Merchant Center (MCQL). Il linguaggio ti consente di selezionare i dati di risorse diverse
(chiamate "visualizzazioni", come product_performance_view
o product_view
), filtrare per
segmenti (come date
o marketing_method
), selezionare metriche (come clicks
o
impressions
), ordinare i risultati e limitarne il numero.
Per informazioni dettagliate sulla struttura del linguaggio di query e sulle visualizzazioni, sui campi e sulle metriche disponibili, consulta la grammatica del linguaggio di query di Merchant Center.
Prerequisiti
Prima di utilizzare l'API secondaria Reporting, verifica di disporre di un account Merchant Center che contenga dati di prodotto.
Per dati specifici (report sul rendimento), devi disporre del ruolo Rendimento e approfondimenti. Per maggiori informazioni, consulta Ho bisogno di assistenza con le persone e i livelli di accesso e Requisiti.
Esempio: identificare i problemi relativi al prodotto
Puoi identificare i problemi che interessano i tuoi prodotti per intraprendere azioni correttive. In questo modo puoi mantenere la conformità e migliorare la visibilità dei tuoi prodotti. Ad esempio, la seguente query recupera tutti i problemi relativi ai prodotti nel tuo account, aiutandoti a verificare se i tuoi prodotti soddisfano i requisiti normativi e di qualità dei dati.
Chiamate
POST https://merchantapi.googleapis.com/reports/v1/accounts/{ACCOUNT_ID}/reports:search
con il seguente corpo della richiesta:
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'
produrrà una risposta simile alla seguente:
{
"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"
}
]
}
}
]
}
I seguenti esempi di codice mostrano come filtrare i prodotti non approvati.
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'\''"
}'
Esempio: cerca prodotti
Gli esempi di codice riportati di seguito mostrano come eseguire query su attributi di prodotto specifici. Puoi aggiornare i seguenti esempi di codice per vari casi d'uso commentando e annullando il commento di query specifiche.
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').v1beta;
/**
* 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"
}'