### Run Product Listing Sample Source: https://github.com/google/merchant-api-samples/blob/main/nodejs/README.md Start a sample application to list products using the v1 Merchant API. This is a basic example to get started. ```bash node examples/products/v1/list_products_sample.js ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/google/merchant-api-samples/blob/main/nodejs/README.md Run this command to install all necessary dependencies for the Node.js samples. ```bash npm install ``` -------------------------------- ### Install Dependencies with Composer Source: https://github.com/google/merchant-api-samples/blob/main/php/README.md Run this command to install the necessary PHP dependencies for the samples. ```bash composer install ``` -------------------------------- ### Install dependencies Source: https://github.com/google/merchant-api-samples/blob/main/python/README.md Install all needed dependencies via pip. ```bash pip install -r requirements.txt ``` -------------------------------- ### Set up a virtual environment Source: https://github.com/google/merchant-api-samples/blob/main/python/README.md Use this command to set up a Python virtual environment and install dependencies. ```bash python3 -m venv source /bin/activate pip install -r requirements.txt ``` -------------------------------- ### Install Merchant API Agent Skill Locally Source: https://github.com/google/merchant-api-samples/blob/main/agent-skills/README.md Clone the repository, navigate to the skill directory, and install the skill locally using the Gemini CLI. Verify the installation by listing installed skills. ```bash git clone https://github.com/google/merchant-api-samples.git ``` ```bash cd agent-skills/mapi-developer-assistant ``` ```bash gemini skills install . ``` ```bash gemini skills list ``` -------------------------------- ### Example: Find Merchant API Code Sample for Product Insertion Source: https://github.com/google/merchant-api-samples/blob/main/agent-skills/mapi-developer-assistant/SKILL.md This example shows how to use the find_mapi_code_sample.sh script to get a code sample for inserting a product in Java. This is useful when migrating from Content API or needing new code examples. ```shell bash /scripts/find_mapi_code_sample.sh "insert product" java ``` -------------------------------- ### List products sample Source: https://github.com/google/merchant-api-samples/blob/main/python/README.md Start a sample to list products from the Google Merchant API. ```python python -m examples.products.v1.list_products_sample ``` -------------------------------- ### Register GCP project Source: https://github.com/google/merchant-api-samples/blob/main/python/README.md Run this sample to register your GCP project before calling any v1 Merchant API methods. More information can be found in the quickstart guide. ```python python -m examples.accounts.developerregistration.v1.register_gcp_sample ``` -------------------------------- ### Example: Query Merchant API for Content API Equivalent Source: https://github.com/google/merchant-api-samples/blob/main/agent-skills/mapi-developer-assistant/SKILL.md This example demonstrates how to use the query_mapi_docs.sh script to find the Merchant API equivalent for a specific Content API method. This is useful for migration inquiries. ```shell bash /scripts/query_mapi_docs.sh "What is the Merchant API equivalent for the accountstatuses.get method?" ``` -------------------------------- ### Install Dependencies with Go Mod Tidy Source: https://github.com/google/merchant-api-samples/blob/main/golang/README.md Run this command in the root of the Go directory to download and install all necessary libraries specified in go.mod. ```bash go mod tidy ``` -------------------------------- ### Register GCP Project for Merchant API Source: https://github.com/google/merchant-api-samples/blob/main/nodejs/README.md Execute this script to register your GCP project before calling v1 Merchant API methods. Refer to the quickstart guide for more details. ```javascript node examples/accounts/developerregistration/v1/register_gcp_sample.js ``` -------------------------------- ### Install/Update Gemini CLI Source: https://github.com/google/merchant-api-samples/blob/main/agent-skills/README.md Use this command to install or update the Gemini CLI to the latest version. Verify the installation by checking the version number. ```bash npm install -g @google/gemini-cli@latest ``` ```bash gemini --version ``` -------------------------------- ### Insert Local Inventory in Python Source: https://context7.com/google/merchant-api-samples/llms.txt Use this Python snippet to insert local inventory data for a product. Ensure you have user credentials generated and the necessary client library installed. ```python from google.shopping import merchant_inventories_v1 from google.shopping.merchant_inventories_v1.types import LocalInventoryAttributes def insert_local_inventory(account_id, product_id, store_code): credentials = generate_user_credentials.main() client = merchant_inventories_v1.LocalInventoryServiceClient(credentials=credentials) # Parent format: accounts/{account}/products/{product} parent = f"accounts/{account_id}/products/{product_id}" local_inventory = merchant_inventories_v1.LocalInventory() local_inventory.store_code = store_code local_inventory.local_inventory_attributes.availability = ( LocalInventoryAttributes.Availability.IN_STOCK ) local_inventory.local_inventory_attributes.price = { "currency_code": "USD", "amount_micros": 33450000, # $33.45 } request = merchant_inventories_v1.InsertLocalInventoryRequest( parent=parent, local_inventory=local_inventory, ) response = client.insert_local_inventory(request=request) print(f"Inserted local inventory: {response}") ``` -------------------------------- ### Register GCP Project with Merchant API (Java) Source: https://context7.com/google/merchant-api-samples/llms.txt Registers your GCP project with the Merchant API. This is a one-time setup requirement before making other API calls. Ensure you have authenticated credentials. ```java import com.google.api.gax.core.FixedCredentialsProvider; import com.google.auth.oauth2.GoogleCredentials; import com.google.shopping.merchant.accounts.v1.DeveloperRegistration; import com.google.shopping.merchant.accounts.v1.DeveloperRegistrationName; import com.google.shopping.merchant.accounts.v1.DeveloperRegistrationServiceClient; import com.google.shopping.merchant.accounts.v1.DeveloperRegistrationServiceSettings; import com.google.shopping.merchant.accounts.v1.RegisterGcpRequest; public class RegisterGcpSample { public static void registerGcp(String accountId, String developerEmail) throws Exception { GoogleCredentials credential = new Authenticator().authenticate(); DeveloperRegistrationServiceSettings settings = DeveloperRegistrationServiceSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(credential)) .build(); // Resource name format: accounts/{account}/developerRegistration String name = DeveloperRegistrationName.newBuilder() .setAccount(accountId) .build() .toString(); try (DeveloperRegistrationServiceClient client = DeveloperRegistrationServiceClient.create(settings)) { RegisterGcpRequest request = RegisterGcpRequest.newBuilder() .setName(name) .setDeveloperEmail(developerEmail) .build(); DeveloperRegistration response = client.registerGcp(request); System.out.println(response); } } } ``` -------------------------------- ### Get Shipping Settings in Java Source: https://context7.com/google/merchant-api-samples/llms.txt This Java code retrieves shipping settings for a specified Merchant Center account. It requires authentication and the appropriate client library. ```java // [Java] Get shipping settings import com.google.shopping.merchant.accounts.v1.*; public class GetShippingSettingsSample { public static void getShippingSettings(String accountId) throws Exception { GoogleCredentials credential = new Authenticator().authenticate(); ShippingSettingsServiceSettings settings = ShippingSettingsServiceSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(credential)) .build(); // Name format: accounts/{account}/shippingSettings String name = ShippingSettingsName.newBuilder() .setAccount(accountId) .build() .toString(); try (ShippingSettingsServiceClient client = ShippingSettingsServiceClient.create(settings)) { GetShippingSettingsRequest request = GetShippingSettingsRequest.newBuilder() .setName(name) .build(); ShippingSettings response = client.getShippingSettings(request); System.out.println("Shipping Settings: " + response); } } } ``` -------------------------------- ### Manage Merchant API Agent Skill Source: https://github.com/google/merchant-api-samples/blob/main/agent-skills/README.md Commands to manage the installed Merchant API Agent Skill within the Gemini CLI. Use 'list' to view, 'disable' to deactivate, and 'enable' to reactivate. ```bash gemini skills list ``` ```bash gemini skills disable mapi-developer-assistant ``` ```bash gemini skills enable mapi-developer-assistant ``` -------------------------------- ### List Available Samples Source: https://github.com/google/merchant-api-samples/blob/main/golang/README.md Execute the program without any arguments to display a list of all runnable code samples. ```bash go run . ``` -------------------------------- ### Run a Specific Sample Source: https://github.com/google/merchant-api-samples/blob/main/golang/README.md To execute a particular sample, provide its name as a command-line argument to the program. ```bash go run . accounts.accounts.v1.get_account ``` -------------------------------- ### Compile Samples with Maven Source: https://github.com/google/merchant-api-samples/blob/main/java/README.md Navigate to the directory containing the pom.xml file and run this command to compile all samples. This is a prerequisite before executing individual samples. ```bash mvn compile ``` -------------------------------- ### Run ListProductsSample Project Source: https://github.com/google/merchant-api-samples/blob/main/dotnet/README.md Command to execute the ListProductsSample project using the .NET CLI. Ensure you are in the samples' root directory. ```bash dotnet run --project examples/products/v1/ListProductsSample.csproj --framework netcoreapp8.0 ``` -------------------------------- ### Go - Insert Product Input Source: https://context7.com/google/merchant-api-samples/llms.txt Use this Go code to insert a product input. Ensure you have authenticated and created the necessary client. The product details include pricing, shipping, and attributes like title, description, and GTIN. ```go // [Go] Insert a product input package main import ( "context" "fmt" products "cloud.google.com/go/shopping/merchant/products/apiv1" "cloud.google.com/go/shopping/merchant/products/apiv1/productspb" "cloud.google.com/go/shopping/type/typepb" "google.golang.org/api/option" ) func insertProductInput(ctx context.Context, accountID, dataSourceID string) error { tokenSource, err := authWithGoogle(ctx) if err != nil { return fmt.Errorf("failed to authenticate: %w", err) } client, err := products.NewProductInputsClient(ctx, option.WithTokenSource(tokenSource)) if err != nil { return fmt.Errorf("could not create client: %w", err) } defer client.Close() parent := fmt.Sprintf("accounts/%s", accountID) dataSource := fmt.Sprintf("accounts/%s/dataSources/%s", accountID, dataSourceID) price := &typepb.Price{ AmountMicros: ptr(int64(33450000)), CurrencyCode: ptr("USD"), } req := &productspb.InsertProductInputRequest{ Parent: parent, DataSource: dataSource, ProductInput: &productspb.ProductInput{ ContentLanguage: "en", FeedLabel: "US", OfferId: "sku123", ProductAttributes: &productspb.ProductAttributes{ Title: ptr("A Tale of Two Cities"), Description: ptr("A classic novel about the French Revolution"), Link: ptr("https://example.com/tale-of-two-cities.html"), ImageLink: ptr("https://example.com/tale-of-two-cities.jpg"), Availability: ptr(productspb.Availability_IN_STOCK), Condition: ptr(productspb.Condition_NEW), GoogleProductCategory: ptr("Media > Books"), Gtins: []string{"9780007350896"}, Shipping: []*productspb.Shipping{ {Price: price, Country: "US", Service: "Standard"}, }, }, }, } resp, err := client.InsertProductInput(ctx, req) if err != nil { return fmt.Errorf("could not insert product: %w", err) } fmt.Println("Product Name:", resp.Name) return nil } ``` -------------------------------- ### List Products using Java Source: https://context7.com/google/merchant-api-samples/llms.txt Lists all products for a Merchant Center account with automatic pagination. Ensure you have authenticated credentials. ```java // [Java] List all products import com.google.shopping.merchant.products.v1.*; public class ListProductsSample { public static void listProducts(String accountId) throws Exception { GoogleCredentials credential = new Authenticator().authenticate(); ProductsServiceSettings settings = ProductsServiceSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(credential)) .build(); String parent = String.format("accounts/%s", accountId); try (ProductsServiceClient client = ProductsServiceClient.create(settings)) { ListProductsRequest request = ListProductsRequest.newBuilder() .setParent(parent) .setPageSize(1000) // Maximum page size .build(); int count = 0; for (Product product : client.listProducts(request).iterateAll()) { System.out.println(product); // product.getProductStatus() shows approval/disapproval info count++; } System.out.println("Total products: " + count); } } } ``` -------------------------------- ### Register GCP Project Source: https://github.com/google/merchant-api-samples/blob/main/php/README.md Run this PHP sample to register your GCP project, which is a prerequisite for calling v1 Merchant API methods. ```bash php examples/accounts/developerregistration/v1/RegisterGcpSample.php ``` -------------------------------- ### Execute a Sample with Maven Source: https://github.com/google/merchant-api-samples/blob/main/java/README.md General command to execute a sample using Maven. Replace '' with the fully qualified name of the sample class you wish to run. ```bash mvn exec:java -Dexec.mainClass="" ``` -------------------------------- ### Run ListProductsSample with Maven Source: https://github.com/google/merchant-api-samples/blob/main/java/README.md Use this command to execute the ListProductsSample class. Ensure you have compiled the code successfully using 'mvn compile' first. ```bash mvn exec:java -Dexec.mainClass="shopping.merchant.samples.products.v1.ListProductsSample" ``` -------------------------------- ### Register GCP Project with Maven Source: https://github.com/google/merchant-api-samples/blob/main/java/README.md Before calling any v1 Merchant API methods, register your GCP project using this sample. Refer to the provided link for more information on the registration process. ```bash mvn exec:java -Dexec.mainClass="shopping.merchant.samples.accounts.developerregistration.v1.RegisterGcpSample" ``` -------------------------------- ### List Products with Merchant API Source: https://github.com/google/merchant-api-samples/blob/main/php/README.md Execute this PHP script to list products using the v1 Merchant API. Ensure authentication is set up prior to running. ```bash php examples/products/v1/ListProductsSample.php ``` -------------------------------- ### Search Product Reports with SQL-like Queries in Python Source: https://context7.com/google/merchant-api-samples/llms.txt Use the ReportServiceClient to query product data and issues from the product_view. Requires authentication credentials. ```python from google.shopping.merchant_reports_v1 import ReportServiceClient, SearchRequest def search_product_report(account_id): credentials = generate_user_credentials.main() client = ReportServiceClient(credentials=credentials) parent = f"accounts/{account_id}" # Query product_view for product data and issues query = """ SELECT offer_id, id, price, gtin, item_issues, channel, language_code, feed_label, title, brand, category_l1, availability, click_potential FROM product_view """ request = SearchRequest(parent=parent, query=query) # Iterate with automatic pagination for row in client.search(request=request): print(row) ``` -------------------------------- ### List Data Sources using Python Source: https://context7.com/google/merchant-api-samples/llms.txt Lists all data sources (feeds) for a Merchant Center account, distinguishing between primary and supplemental sources. Requires user credentials. ```python # [Python] List data sources from google.shopping import merchant_datasources_v1 def list_data_sources(account_id): credentials = generate_user_credentials.main() client = merchant_datasources_v1.DataSourcesServiceClient(credentials=credentials) parent = f"accounts/{account_id}" request = merchant_datasources_v1.ListDataSourcesRequest(parent=parent) response = client.list_data_sources(request=request) primary_sources = [] supplemental_sources = [] for data_source in response.data_sources: # PrimaryProductDataSource is a oneOf field if data_source.primary_product_data_source: primary_sources.append(data_source) else: supplemental_sources.append(data_source) print(f"Total data sources: {len(response.data_sources)}") print(f"Primary: {len(primary_sources)}, Supplemental: {len(supplemental_sources)}") for ds in response.data_sources: print(f"Name: {ds.name}, Display Name: {ds.display_name}") ``` -------------------------------- ### Search Performance Reports with SQL-like Queries in Python Source: https://context7.com/google/merchant-api-samples/llms.txt Use the ReportServiceClient to query performance metrics from the product_performance_view. Requires authentication credentials and a date range. ```python def search_performance_report(account_id, start_date, end_date): credentials = generate_user_credentials.main() client = ReportServiceClient(credentials=credentials) parent = f"accounts/{account_id}" # Query product_performance_view for metrics query = f""" SELECT offer_id, title, brand, clicks, impressions, click_through_rate, conversions, conversion_rate, conversion_value FROM product_performance_view WHERE date BETWEEN '{start_date}' AND '{end_date}' """ request = SearchRequest(parent=parent, query=query) for row in client.search(request=request): print(f"Product: {row.product_view.title}, Clicks: {row.product_performance_view.clicks}") ``` -------------------------------- ### List Promotions in Java Source: https://context7.com/google/merchant-api-samples/llms.txt Retrieve all promotions for a Merchant Center account using the PromotionsService. Supports automatic pagination. ```java import com.google.shopping.merchant.promotions.v1.*; public class ListPromotionsSample { public static void listPromotions(String accountId) throws Exception { GoogleCredentials credential = new Authenticator().authenticate(); PromotionsServiceSettings settings = PromotionsServiceSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(credential)) .build(); try (PromotionsServiceClient client = PromotionsServiceClient.create(settings)) { ListPromotionsRequest request = ListPromotionsRequest.newBuilder() .setParent(String.format("accounts/%s", accountId)) .build(); int count = 0; for (Promotion promotion : client.listPromotions(request).iterateAll()) { System.out.println(promotion); count++; } System.out.println("Total promotions: " + count); } } } ``` -------------------------------- ### Query Merchant API Documentation Source: https://github.com/google/merchant-api-samples/blob/main/agent-skills/mapi-developer-assistant/SKILL.md Use this script to query official Merchant API documentation for concepts, migration guidance, and API explanations. Provide your specific question as an argument. ```shell bash /scripts/query_mapi_docs.sh "Your specific question here" ``` -------------------------------- ### Insert Product Input in Python Source: https://context7.com/google/merchant-api-samples/llms.txt This Python script demonstrates how to insert a product into Merchant Center. It requires user credentials and specifies product details like title, description, and shipping. ```python from google.shopping import merchant_products_v1 from google.shopping.merchant_products_v1 import Availability, Condition from google.shopping.type import Price def insert_product_input(account_id, data_source_id): credentials = generate_user_credentials.main() client = merchant_products_v1.ProductInputsServiceClient(credentials=credentials) parent = f"accounts/{account_id}" data_source = f"accounts/{account_id}/dataSources/{data_source_id}" price = Price() price.amount_micros = 33_450_000 price.currency_code = "USD" shipping = merchant_products_v1.Shipping() shipping.price = price shipping.country = "US" shipping.service = "Standard" attributes = merchant_products_v1.ProductAttributes() attributes.title = "A Tale of Two Cities" attributes.description = "A classic novel about the French Revolution" attributes.link = "https://example.com/tale-of-two-cities.html" attributes.image_link = "https://example.com/tale-of-two-cities.jpg" attributes.availability = Availability.IN_STOCK attributes.condition = Condition.NEW attributes.google_product_category = "Media > Books" attributes.gtins = ["9780007350896"] attributes.shipping = [shipping] product_input = merchant_products_v1.ProductInput( content_language="en", feed_label="US", offer_id="sku123", product_attributes=attributes, ) request = merchant_products_v1.InsertProductInputRequest( parent=parent, product_input=product_input, data_source=data_source, ) response = client.insert_product_input(request=request) print(f"Inserted product: {response.name}") ``` -------------------------------- ### .NET - Insert Product Input Source: https://context7.com/google/merchant-api-samples/llms.txt This C#/.NET code inserts a product input into the Google Merchant Center. It requires authentication and uses the ProductInputsServiceClient. The product details include pricing, shipping, and attributes like title, description, and GTIN. ```csharp // [C#/.NET] Insert a product input using Google.Shopping.Merchant.Products.V1; using Google.Shopping.Type; public class InsertProductInputSample { public void InsertProductInput(string merchantId, string dataSourceId) { var auth = Authenticator.Authenticate(MerchantConfig.Load(), ProductsServiceClient.DefaultScopes[0]); var client = new ProductInputsServiceClientBuilder { Credential = auth }.Build(); string parent = $"accounts/{merchantId}"; string dataSource = $"accounts/{merchantId}/dataSources/{dataSourceId}"; var price = new Price { AmountMicros = 33_450_000, CurrencyCode = "USD" }; var shipping = new Shipping { Price = price, Country = "US", Service = "Standard" }; var attributes = new ProductAttributes { Title = "A Tale of Two Cities", Description = "A classic novel about the French Revolution", Link = "https://example.com/tale-of-two-cities.html", ImageLink = "https://example.com/tale-of-two-cities.jpg", Availability = Availability.InStock, Condition = Condition.New, GoogleProductCategory = "Media > Books", Gtins = { "9780007350896" }, Shipping = { shipping } }; var productInput = new ProductInput { ContentLanguage = "en", FeedLabel = "US", OfferId = "sku123", ProductAttributes = attributes }; var request = new InsertProductInputRequest { Parent = parent, DataSource = dataSource, ProductInput = productInput }; ProductInput response = client.InsertProductInput(request); Console.WriteLine($"Product Name: {response.Name}"); } } ``` -------------------------------- ### Create Notification Subscription in Java Source: https://context7.com/google/merchant-api-samples/llms.txt Subscribe to push notifications for product status changes using the NotificationsApiService. Requires authentication and a callback URL. ```java import com.google.shopping.merchant.notifications.v1.*; public class CreateNotificationSubscriptionSample { public static void createSubscription(String accountId) throws Exception { GoogleCredentials credential = new Authenticator().authenticate(); NotificationsApiServiceSettings settings = NotificationsApiServiceSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(credential)) .build(); String parent = "accounts/" + accountId; try (NotificationsApiServiceClient client = NotificationsApiServiceClient.create(settings)) { NotificationSubscription subscription = NotificationSubscription.newBuilder() .setTargetAccount(parent) // For all managed accounts: .setAllManagedAccounts(true) .setCallBackUri("https://your-webhook-endpoint.com/notifications") .setRegisteredEvent(NotificationSubscription.NotificationEventType.PRODUCT_STATUS_CHANGE) .build(); CreateNotificationSubscriptionRequest request = CreateNotificationSubscriptionRequest.newBuilder() .setParent(parent) .setNotificationSubscription(subscription) .build(); NotificationSubscription response = client.createNotificationSubscription(request); System.out.println("Created subscription: " + response.getName()); } } } ``` -------------------------------- ### Insert Product Input in Node.js Source: https://context7.com/google/merchant-api-samples/llms.txt This Node.js snippet demonstrates how to insert product input data into a specified merchant account and data source. It uses the @google-shopping/products library and requires user authentication. ```javascript // [Node.js] Insert a product input const { ProductInputsServiceClient, protos } = require('@google-shopping/products').v1; const Availability = protos.google.shopping.merchant.products.v1.Availability; const Condition = protos.google.shopping.merchant.products.v1.Condition; async function insertProductInput(merchantId, dataSourceId) { const authClient = await getOrGenerateUserCredentials(); const client = new ProductInputsServiceClient({ authClient }); const parent = `accounts/${merchantId}`; const dataSource = `accounts/${merchantId}/dataSources/${dataSourceId}`; const request = { parent, dataSource, productInput: { contentLanguage: 'en', feedLabel: 'US', offerId: 'sku123', productAttributes: { title: 'A Tale of Two Cities', description: 'A classic novel about the French Revolution', link: 'https://example.com/tale-of-two-cities.html', imageLink: 'https://example.com/tale-of-two-cities.jpg', availability: Availability.IN_STOCK, condition: Condition.NEW, googleProductCategory: 'Media > Books', gtins: ['9780007350896'], price: { amountMicros: 33450000, currencyCode: 'USD' }, shipping: [ { price: { amountMicros: 3000000, currencyCode: 'USD' }, country: 'US', service: 'Standard' } ] } } }; try { const [response] = await client.insertProductInput(request); console.log('Product Name:', response.name); console.log('Product:', response.product); } catch (error) { console.error(error.message); } } ``` -------------------------------- ### Insert Product Input in Java Source: https://context7.com/google/merchant-api-samples/llms.txt Use this Java code to insert a product into a Merchant Center account. Ensure you have the necessary authentication and API client libraries configured. ```java import com.google.shopping.merchant.products.v1.*; import com.google.shopping.type.Price; public class InsertProductInputSample { public static void insertProductInput(String accountId, String dataSourceId) throws Exception { GoogleCredentials credential = new Authenticator().authenticate(); ProductInputsServiceSettings settings = ProductInputsServiceSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(credential)) .build(); String parent = String.format("accounts/%s", accountId); String dataSource = String.format("accounts/%s/dataSources/%s", accountId, dataSourceId); Price shippingPrice = Price.newBuilder() .setAmountMicros(33_450_000) // $33.45 .setCurrencyCode("USD") .build(); Shipping shipping = Shipping.newBuilder() .setPrice(shippingPrice) .setCountry("US") .setService("Standard") .build(); ProductAttributes attributes = ProductAttributes.newBuilder() .setTitle("A Tale of Two Cities") .setDescription("A classic novel about the French Revolution") .setLink("https://example.com/tale-of-two-cities.html") .setImageLink("https://example.com/tale-of-two-cities.jpg") .setAvailability(Availability.IN_STOCK) .setCondition(Condition.NEW) .setGoogleProductCategory("Media > Books") .addGtins("9780007350896") .addShipping(shipping) .build(); ProductInput productInput = ProductInput.newBuilder() .setContentLanguage("en") .setFeedLabel("US") .setOfferId("sku123") .setProductAttributes(attributes) .build(); try (ProductInputsServiceClient client = ProductInputsServiceClient.create(settings)) { InsertProductInputRequest request = InsertProductInputRequest.newBuilder() .setParent(parent) .setDataSource(dataSource) .setProductInput(productInput) .build(); ProductInput response = client.insertProductInput(request); // Product ID format: contentLanguage~feedLabel~offerId System.out.println("Product Name: " + response.getName()); System.out.println("Product: " + response.getProduct()); } } } ``` -------------------------------- ### Generate User Credentials Source: https://github.com/google/merchant-api-samples/blob/main/php/README.md Execute this PHP script to generate and store your OAuth 2.0 refresh token, client ID, and client secret in a 'token.json' file. ```bash php examples/Authentication/GenerateUserCredentials.php ``` -------------------------------- ### List Accessible Accounts (Java) Source: https://context7.com/google/merchant-api-samples/llms.txt Lists all Merchant Center accounts the authenticated user has access to. For a large number of sub-accounts, consider using `listSubAccounts` to avoid quota limits. Requires authentication. ```java import com.google.shopping.merchant.accounts.v1.Account; import com.google.shopping.merchant.accounts.v1.AccountsServiceClient; import com.google.shopping.merchant.accounts.v1.AccountsServiceSettings; import com.google.shopping.merchant.accounts.v1.ListAccountsRequest; public class ListAccountsSample { public static void listAccounts() throws Exception { GoogleCredentials credential = new Authenticator().authenticate(); AccountsServiceSettings settings = AccountsServiceSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(credential)) .build(); try (AccountsServiceClient client = AccountsServiceClient.create(settings)) { ListAccountsRequest request = ListAccountsRequest.newBuilder().build(); // Automatically handles pagination via nextPageToken for (Account account : client.listAccounts(request).iterateAll()) { System.out.println("Account: " + account.getName()); System.out.println("Account ID: " + account.getAccountId()); } } } } ``` -------------------------------- ### Find Merchant API Code Sample Source: https://github.com/google/merchant-api-samples/blob/main/agent-skills/mapi-developer-assistant/SKILL.md Use this script to find code samples for Merchant API operations. You can filter by language. Supported languages include: java, python, php, nodejs, dotnet, apps_script. ```shell bash /scripts/find_mapi_code_sample.sh "operation description" [language] ``` -------------------------------- ### Register GCP Project for Merchant API v1 Source: https://github.com/google/merchant-api-samples/blob/main/apps_script/README.md Run this Apps Script code to register your GCP project. This is a prerequisite for calling v1 Merchant API methods. Ensure you have an Apps Script project with runtime v8. ```javascript /** * @OnlyCurrentDoc */ // TODO(developer): set your project number and project id const PROJECT_NUMBER = "YOUR_PROJECT_NUMBER"; const PROJECT_ID = "YOUR_PROJECT_ID"; /** * Registers the GCP project with the Merchant API. */ function registerGcp() { try { // The Merchant Center API requires that the calling project be registered // with the Merchant Center API. This is done by calling the // `registerGcpProject` method on the `AccountsService`. // See https://developers.google.com/shopping-content/reference/rest/v1/accounts/registerGcpProject const response = Shopping.Accounts.registerGcpProject({ projectNumber: PROJECT_NUMBER, projectId: PROJECT_ID }); Logger.log("GCP project registered successfully."); Logger.log(response); } catch (err) { // TODO(developer): Handle error Logger.log(`The API returned the following error: ${err}`); } } ``` -------------------------------- ### Add Merchant API Agent Skill for Claude Code Source: https://github.com/google/merchant-api-samples/blob/main/agent-skills/README.md Clone the repository and copy the skill directory to the specified location for Claude Code to recognize it. Ensure the skills directory exists. ```bash git clone https://github.com/google/merchant-api-samples.git ``` ```bash mkdir -p .claude/skills/ ``` ```bash cp -r merchant-api-samples/agent-skills/mapi-developer-assistant .claude/skills/ ``` -------------------------------- ### Enable Agent Skills in Gemini CLI Source: https://github.com/google/merchant-api-samples/blob/main/agent-skills/README.md Configure Gemini CLI to enable Agent Skills. This can be done through the settings interface or directly via the command line. ```bash gemini config set experimental.skills true ``` -------------------------------- ### PHP: Insert Product Input Source: https://context7.com/google/merchant-api-samples/llms.txt Use this snippet to insert a product input into your Merchant Center account. Ensure you have authenticated and set up the necessary client and request objects. ```php $credentials]); $parent = sprintf("accounts/%s", $accountId); $dataSource = sprintf("accounts/%s/dataSources/%s", $accountId, $dataSourceId); $price = new Price([ 'amount_micros' => 33450000, 'currency_code' => 'USD' ]); $shipping = new Shipping([ 'price' => $price, 'country' => 'US', 'service' => 'Standard' ]); $attributes = new ProductAttributes([ 'title' => 'A Tale of Two Cities', 'description' => 'A classic novel about the French Revolution', 'link' => 'https://example.com/tale-of-two-cities.html', 'image_link' => 'https://example.com/tale-of-two-cities.jpg', 'availability' => Availability::IN_STOCK, 'condition' => Condition::PBNEW, 'google_product_category' => 'Media > Books', 'gtins' => ['9780007350896'], 'shipping' => [$shipping] ]); $productInput = new ProductInput([ 'content_language' => 'en', 'feed_label' => 'US', 'offer_id' => 'sku123', 'product_attributes' => $attributes ]); $request = new InsertProductInputRequest([ 'parent' => $parent, 'data_source' => $dataSource, 'product_input' => $productInput ]); $response = $client->insertProductInput($request); print "Product Name: " . $response->getName() . "\n"; } } ``` -------------------------------- ### Delete Product Input using Java Source: https://context7.com/google/merchant-api-samples/llms.txt Deletes a product's input data from a Merchant Center account. Deleting from a primary feed removes the product completely; deleting from a supplemental feed only removes that feed's data. Requires account ID, product ID, and data source ID. ```java // [Java] Delete a product input import com.google.shopping.merchant.products.v1.*; public class DeleteProductInputSample { public static void deleteProductInput(String accountId, String productId, String dataSourceId) throws Exception { GoogleCredentials credential = new Authenticator().authenticate(); ProductInputsServiceSettings settings = ProductInputsServiceSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(credential)) .build(); // Product name format: accounts/{account}/productInputs/{productInput} String name = ProductInputName.newBuilder() .setAccount(accountId) .setProductinput(productId) // Format: contentLanguage~feedLabel~offerId .build() .toString(); String dataSource = String.format("accounts/%s/dataSources/%s", accountId, dataSourceId); try (ProductInputsServiceClient client = ProductInputsServiceClient.create(settings)) { DeleteProductInputRequest request = DeleteProductInputRequest.newBuilder() .setName(name) .setDataSource(dataSource) .build(); client.deleteProductInput(request); // No response on success System.out.println("Product deleted successfully"); } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.