Stay organized with collections
Save and categorize content based on your preferences.
Merchant API code sample to insert local inventory asynchronously.
Java
// Copyright 2025 Google LLC//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.packageshopping.merchant.samples.inventories.v1;importcom.google.api.core.ApiFuture;importcom.google.api.core.ApiFutureCallback;importcom.google.api.core.ApiFutures;importcom.google.api.gax.core.FixedCredentialsProvider;importcom.google.auth.oauth2.GoogleCredentials;importcom.google.common.util.concurrent.MoreExecutors;importcom.google.shopping.merchant.inventories.v1.InsertLocalInventoryRequest;importcom.google.shopping.merchant.inventories.v1.LocalInventory;importcom.google.shopping.merchant.inventories.v1.LocalInventoryAttributes;importcom.google.shopping.merchant.inventories.v1.LocalInventoryAttributes.Availability;importcom.google.shopping.merchant.inventories.v1.LocalInventoryServiceClient;importcom.google.shopping.merchant.inventories.v1.LocalInventoryServiceSettings;importcom.google.shopping.merchant.products.v1.ListProductsRequest;importcom.google.shopping.merchant.products.v1.Product;importcom.google.shopping.merchant.products.v1.ProductsServiceClient;importcom.google.shopping.merchant.products.v1.ProductsServiceClient.ListProductsPagedResponse;importcom.google.shopping.merchant.products.v1.ProductsServiceSettings;importcom.google.shopping.type.Price;importjava.io.IOException;importjava.util.ArrayList;importjava.util.List;importjava.util.stream.Collectors;importshopping.merchant.samples.utils.Authenticator;importshopping.merchant.samples.utils.Config;/** * This class demonstrates how to insert Local inventory asynchronously for multiple products. Note, * this code sample will only work if you already have datasource and products available for local * products. You can create a datasource for local and products by looking at the DataSources and * Products samples. */publicclassInsertLocalInventoryAsyncSample{/* Gets the names of all the local products for a given merchant center account. */publicstaticList<String>getLocalProductNames(GoogleCredentialscredential,StringaccountId)throwsIOException{ProductsServiceSettingsproductsServiceSettings=ProductsServiceSettings.newBuilder().setCredentialsProvider(FixedCredentialsProvider.create(credential)).build();try(ProductsServiceClientproductsServiceClient=ProductsServiceClient.create(productsServiceSettings)){ListProductsRequestrequest=ListProductsRequest.newBuilder()// Creates parent to identify the account from which to list all products..setParent(String.format("accounts/%s",accountId)).build();System.out.println("Sending list products request:");ListProductsPagedResponseresponse=productsServiceClient.listProducts(request);// Iterates over all rows in all pages and prints the datasource in each row.// Automatically uses the `nextPageToken` if returned to fetch all pages of dataList<String>localProductNames=newArrayList<String>();for(Productproduct:response.iterateAll()){// Filters for only local products using the legacyLocal field.if(product.getLegacyLocal()){// The name is returned in the format:// accounts/{account}/products/{channel}~{contentLanguage}~{feedLabel}~{offerId}// These will be used to insert local inventory for each product.localProductNames.add(product.getName());}}returnlocalProductNames;}}publicstaticvoidinsertLocalInventoryAsync(GoogleCredentialscredential,StringaccountId,StringstoreCode)throwsException{LocalInventoryServiceSettingslocalInventoryServiceSettings=LocalInventoryServiceSettings.newBuilder().setCredentialsProvider(FixedCredentialsProvider.create(credential)).build();try(LocalInventoryServiceClientlocalInventoryServiceClient=LocalInventoryServiceClient.create(localInventoryServiceSettings)){// In this example, we are simply using the same price for all products.Priceprice=Price.newBuilder().setAmountMicros(33_450_000).setCurrencyCode("USD").build();// Checks that the account has local products.List<String>localProductNames=getLocalProductNames(credential,accountId);if(localProductNames.isEmpty()){thrownewException("No local products found for this account.");}// Creates requests to update the inventory for each product, set a fixed price and set the// availability to "out of stock".List<InsertLocalInventoryRequest>requests=localProductNames.stream().map(name->{returnInsertLocalInventoryRequest.newBuilder().setParent(name).setLocalInventory(LocalInventory.newBuilder().setLocalInventoryAttributes(LocalInventoryAttributes.newBuilder().setAvailability(Availability.OUT_OF_STOCK).setPrice(price).build()).setStoreCode(storeCode).build()).build();}).collect(Collectors.toList());// Inserts the local inventory for each product.System.out.println("Sending InsertLocalInventory requests");List<ApiFuture<LocalInventory>>futures=requests.stream().map(request->
localInventoryServiceClient.insertLocalInventoryCallable().futureCall(request)).collect(Collectors.toList());// Callback to handle the responses from the API once they are all returned.ApiFuture<List<LocalInventory>>responses=ApiFutures.allAsList(futures);ApiFutures.addCallback(responses,newApiFutureCallback<List<LocalInventory>>(){@OverridepublicvoidonSuccess(List<LocalInventory>results){System.out.println("Inserted LocalInventory below");System.out.println(results);}@OverridepublicvoidonFailure(Throwablethrowable){System.err.println("An error occurred while inserting local inventory: "+throwable.getMessage());}},MoreExecutors.directExecutor());}catch(Exceptione){System.err.println(e.getMessage());}}publicstaticvoidmain(String[]args)throwsException{GoogleCredentialscredential=newAuthenticator().authenticate();StringaccountId=Config.load().getAccountId().toString();// The code uniquely identifying each store.// This can be found in the Google Business Profile UI, by going to Business Profile Settings ->
// Advanced Settings. The store must have passed verification for this code sample to work.StringstoreCode="yourstorecode";insertLocalInventoryAsync(credential,accountId,storeCode);}}
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-13 UTC."],[[["\u003cp\u003eThis code sample demonstrates how to asynchronously insert local inventory for multiple products using the Merchant API in Java.\u003c/p\u003e\n"],["\u003cp\u003eThe code retrieves a list of local product names from a specified merchant account that have their channel set to "LOCAL", which is necessary for local inventory.\u003c/p\u003e\n"],["\u003cp\u003eIt uses the \u003ccode\u003eInsertLocalInventoryRequest\u003c/code\u003e to set a product's local inventory details, including store code, price, and availability, to "out of stock".\u003c/p\u003e\n"],["\u003cp\u003eThe code leverages asynchronous API calls via \u003ccode\u003eApiFuture\u003c/code\u003e and \u003ccode\u003eApiFutures\u003c/code\u003e to efficiently handle multiple inventory updates, with a callback to manage success or failure responses.\u003c/p\u003e\n"],["\u003cp\u003eThe sample code requires a Google Business Profile store code and prior setup of a local data source to work correctly.\u003c/p\u003e\n"]]],["This Java code asynchronously inserts local inventory for multiple products in a Google Merchant Center account. It first retrieves a list of existing local product names. Then, it creates `InsertLocalInventoryRequest` objects, setting a fixed price and \"out of stock\" availability for each product. Finally, it sends these requests, handles the responses via callbacks, and outputs whether the inventory updates were successful or if any errors occurred. The main method handles authentication and configuration.\n"],null,["# Insert local inventory asynchronously\n\nMerchant API code sample to insert local inventory asynchronously. \n\n### Java\n\n // Copyright 2025 Google LLC\n //\n // Licensed under the Apache License, Version 2.0 (the \"License\");\n // you may not use this file except in compliance with the License.\n // You may obtain a copy of the License at\n //\n // https://www.apache.org/licenses/LICENSE-2.0\n //\n // Unless required by applicable law or agreed to in writing, software\n // distributed under the License is distributed on an \"AS IS\" BASIS,\n // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n // See the License for the specific language governing permissions and\n // limitations under the License.\n\n package shopping.merchant.samples.inventories.v1;\n\n import com.google.api.core.ApiFuture;\n import com.google.api.core.ApiFutureCallback;\n import com.google.api.core.ApiFutures;\n import com.google.api.gax.core.FixedCredentialsProvider;\n import com.google.auth.oauth2.GoogleCredentials;\n import com.google.common.util.concurrent.MoreExecutors;\n import com.google.shopping.merchant.inventories.v1.InsertLocalInventoryRequest;\n import com.google.shopping.merchant.inventories.v1.LocalInventory;\n import com.google.shopping.merchant.inventories.v1.LocalInventoryAttributes;\n import com.google.shopping.merchant.inventories.v1.LocalInventoryAttributes.Availability;\n import com.google.shopping.merchant.inventories.v1.LocalInventoryServiceClient;\n import com.google.shopping.merchant.inventories.v1.LocalInventoryServiceSettings;\n import com.google.shopping.merchant.products.v1.ListProductsRequest;\n import com.google.shopping.merchant.products.v1.Product;\n import com.google.shopping.merchant.products.v1.ProductsServiceClient;\n import com.google.shopping.merchant.products.v1.ProductsServiceClient.ListProductsPagedResponse;\n import com.google.shopping.merchant.products.v1.ProductsServiceSettings;\n import com.google.shopping.type.Price;\n import java.io.IOException;\n import java.util.ArrayList;\n import java.util.List;\n import java.util.stream.Collectors;\n import shopping.merchant.samples.utils.Authenticator;\n import shopping.merchant.samples.utils.Config;\n\n /**\n * This class demonstrates how to insert Local inventory asynchronously for multiple products. Note,\n * this code sample will only work if you already have datasource and products available for local\n * products. You can create a datasource for local and products by looking at the DataSources and\n * Products samples.\n */\n public class InsertLocalInventoryAsyncSample {\n\n /* Gets the names of all the local products for a given merchant center account. */\n public static List\u003cString\u003e getLocalProductNames(GoogleCredentials credential, String accountId)\n throws IOException {\n\n ProductsServiceSettings productsServiceSettings =\n ProductsServiceSettings.newBuilder()\n .setCredentialsProvider(FixedCredentialsProvider.create(credential))\n .build();\n\n try (ProductsServiceClient productsServiceClient =\n ProductsServiceClient.create(productsServiceSettings)) {\n\n ListProductsRequest request =\n ListProductsRequest.newBuilder()\n // Creates parent to identify the account from which to list all products.\n .setParent(String.format(\"accounts/%s\", accountId))\n .build();\n\n System.out.println(\"Sending list products request:\");\n ListProductsPagedResponse response = productsServiceClient.listProducts(request);\n\n // Iterates over all rows in all pages and prints the datasource in each row.\n // Automatically uses the `nextPageToken` if returned to fetch all pages of data\n List\u003cString\u003e localProductNames = new ArrayList\u003cString\u003e();\n for (Product product : response.iterateAll()) {\n\n // Filters for only local products using the legacyLocal field.\n if (product.getLegacyLocal()) {\n\n // The name is returned in the format:\n // accounts/{account}/products/{channel}~{contentLanguage}~{feedLabel}~{offerId}\n // These will be used to insert local inventory for each product.\n localProductNames.add(product.getName());\n }\n }\n return localProductNames;\n }\n }\n\n public static void insertLocalInventoryAsync(\n GoogleCredentials credential, String accountId, String storeCode) throws Exception {\n\n LocalInventoryServiceSettings localInventoryServiceSettings =\n LocalInventoryServiceSettings.newBuilder()\n .setCredentialsProvider(FixedCredentialsProvider.create(credential))\n .build();\n\n try (LocalInventoryServiceClient localInventoryServiceClient =\n LocalInventoryServiceClient.create(localInventoryServiceSettings)) {\n\n // In this example, we are simply using the same price for all products.\n Price price = Price.newBuilder().setAmountMicros(33_450_000).setCurrencyCode(\"USD\").build();\n\n // Checks that the account has local products.\n List\u003cString\u003e localProductNames = getLocalProductNames(credential, accountId);\n if (localProductNames.isEmpty()) {\n throw new Exception(\"No local products found for this account.\");\n }\n\n // Creates requests to update the inventory for each product, set a fixed price and set the\n // availability to \"out of stock\".\n List\u003cInsertLocalInventoryRequest\u003e requests =\n localProductNames.stream()\n .map(\n name -\u003e {\n return InsertLocalInventoryRequest.newBuilder()\n .setParent(name)\n .setLocalInventory(\n LocalInventory.newBuilder()\n .setLocalInventoryAttributes(\n LocalInventoryAttributes.newBuilder()\n .setAvailability(Availability.OUT_OF_STOCK)\n .setPrice(price)\n .build())\n .setStoreCode(storeCode)\n .build())\n .build();\n })\n .collect(Collectors.toList());\n\n // Inserts the local inventory for each product.\n System.out.println(\"Sending InsertLocalInventory requests\");\n List\u003cApiFuture\u003cLocalInventory\u003e\u003e futures =\n requests.stream()\n .map(\n request -\u003e\n localInventoryServiceClient\n .insertLocalInventoryCallable()\n .futureCall(request))\n .collect(Collectors.toList());\n\n // Callback to handle the responses from the API once they are all returned.\n ApiFuture\u003cList\u003cLocalInventory\u003e\u003e responses = ApiFutures.allAsList(futures);\n ApiFutures.addCallback(\n responses,\n new ApiFutureCallback\u003cList\u003cLocalInventory\u003e\u003e() {\n @Override\n public void onSuccess(List\u003cLocalInventory\u003e results) {\n System.out.println(\"Inserted LocalInventory below\");\n System.out.println(results);\n }\n\n @Override\n public void onFailure(Throwable throwable) {\n System.err.println(\n \"An error occurred while inserting local inventory: \" + throwable.getMessage());\n }\n },\n MoreExecutors.directExecutor());\n } catch (Exception e) {\n System.err.println(e.getMessage());\n }\n }\n\n public static void main(String[] args) throws Exception {\n GoogleCredentials credential = new Authenticator().authenticate();\n String accountId = Config.load().getAccountId().toString();\n // The code uniquely identifying each store.\n // This can be found in the Google Business Profile UI, by going to Business Profile Settings -\u003e\n // Advanced Settings. The store must have passed verification for this code sample to work.\n String storeCode = \"yourstorecode\";\n insertLocalInventoryAsync(credential, accountId, storeCode);\n }\n } \n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/java/src/main/java/shopping/merchant/samples/inventories/v1/InsertLocalInventoryAsyncSample.java"]]