Update Automatic Improvements

Merchant API Code Sample to Update Automatic Improvements

Java

// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package shopping.merchant.samples.accounts.automaticimprovements.v1beta;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.protobuf.FieldMask;
import com.google.shopping.merchant.accounts.v1beta.AutomaticImageImprovements;
import com.google.shopping.merchant.accounts.v1beta.AutomaticImageImprovements.ImageImprovementsAccountLevelSettings;
import com.google.shopping.merchant.accounts.v1beta.AutomaticImprovements;
import com.google.shopping.merchant.accounts.v1beta.AutomaticImprovementsName;
import com.google.shopping.merchant.accounts.v1beta.AutomaticImprovementsServiceClient;
import com.google.shopping.merchant.accounts.v1beta.AutomaticImprovementsServiceSettings;
import com.google.shopping.merchant.accounts.v1beta.AutomaticItemUpdates;
import com.google.shopping.merchant.accounts.v1beta.AutomaticItemUpdates.ItemUpdatesAccountLevelSettings;
import com.google.shopping.merchant.accounts.v1beta.AutomaticShippingImprovements;
import com.google.shopping.merchant.accounts.v1beta.UpdateAutomaticImprovementsRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to update AutomaticImprovements to be enabled. */
public class UpdateAutomaticImprovementsSample {

  public static void updateAutomaticImprovements(Config config) throws Exception {

    GoogleCredentials credential = new Authenticator().authenticate();

    AutomaticImprovementsServiceSettings automaticImprovementsServiceSettings =
        AutomaticImprovementsServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    // Creates AutomaticImprovements name to identify AutomaticImprovements.
    String name =
        AutomaticImprovementsName.newBuilder()
            .setAccount(config.getAccountId().toString())
            .build()
            .toString();

    // Create AutomaticImprovements with the updated fields.
    AutomaticImprovements automaticImprovements =
        AutomaticImprovements.newBuilder()
            .setName(name)
            .setItemUpdates(
                AutomaticItemUpdates.newBuilder()
                    .setAccountItemUpdatesSettings(
                        ItemUpdatesAccountLevelSettings.newBuilder()
                            .setAllowPriceUpdates(true)
                            .setAllowAvailabilityUpdates(true)
                            .setAllowStrictAvailabilityUpdates(true)
                            .setAllowConditionUpdates(true)
                            .build())
                    .build())
            .setImageImprovements(
                AutomaticImageImprovements.newBuilder()
                    .setAccountImageImprovementsSettings(
                        ImageImprovementsAccountLevelSettings.newBuilder()
                            .setAllowAutomaticImageImprovements(true)
                            .build())
                    .build())
            .setShippingImprovements(
                AutomaticShippingImprovements.newBuilder()
                    .setAllowShippingImprovements(true)
                    .build())
            .build();

    FieldMask fieldMask = FieldMask.newBuilder().addPaths("*").build();

    try (AutomaticImprovementsServiceClient automaticImprovementsServiceClient =
        AutomaticImprovementsServiceClient.create(automaticImprovementsServiceSettings)) {

      UpdateAutomaticImprovementsRequest request =
          UpdateAutomaticImprovementsRequest.newBuilder()
              .setAutomaticImprovements(automaticImprovements)
              .setUpdateMask(fieldMask)
              .build();

      System.out.println("Sending Update AutomaticImprovements request");
      AutomaticImprovements response =
          automaticImprovementsServiceClient.updateAutomaticImprovements(request);
      System.out.println("Updated AutomaticImprovements Name below");
      System.out.println(response.getName());
    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();

    updateAutomaticImprovements(config);
  }
}

PHP

<?php
/**
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

require_once __DIR__ . '/../../../../vendor/autoload.php';
require_once __DIR__ . '/../../../Authentication/Authentication.php';
require_once __DIR__ . '/../../../Authentication/Config.php';

use Google\ApiCore\ApiException;
use Google\Protobuf\FieldMask;
use Google\Shopping\Merchant\Accounts\V1beta\AutomaticImageImprovements;
use Google\Shopping\Merchant\Accounts\V1beta\AutomaticImageImprovements\ImageImprovementsAccountLevelSettings;
use Google\Shopping\Merchant\Accounts\V1beta\AutomaticImprovements;
use Google\Shopping\Merchant\Accounts\V1beta\Client\AutomaticImprovementsServiceClient;
use Google\Shopping\Merchant\Accounts\V1beta\AutomaticItemUpdates;
use Google\Shopping\Merchant\Accounts\V1beta\AutomaticItemUpdates\ItemUpdatesAccountLevelSettings;
use Google\Shopping\Merchant\Accounts\V1beta\AutomaticShippingImprovements;
use Google\Shopping\Merchant\Accounts\V1beta\UpdateAutomaticImprovementsRequest;

/**
 * This class demonstrates how to update AutomaticImprovements to be enabled.
 */
class UpdateAutomaticImprovementsSample
{
    /**
     * Helper function to construct the resource name for AutomaticImprovements.
     *
     * @param string $accountId The Merchant Center account ID.
     * @return string The resource name in the format: accounts/{account}/automaticImprovements
     */
    private static function getAutomaticImprovementsName(string $accountId): string
    {
        return sprintf("accounts/%s/automaticImprovements", $accountId);
    }

    /**
     * Updates the automatic improvements settings for a Merchant Center account.
     * This sample enables all automatic improvements.
     *
     * @param array $config The configuration array containing the account ID.
     * @return void
     */
    public static function updateAutomaticImprovementsSample(array $config): void
    {
        // Obtains OAuth credentials for authentication.
        $credentials = Authentication::useServiceAccountOrTokenFile();

        // Contructs an options array for the client.
        $options = ['credentials' => $credentials];

        // Creates a new AutomaticImprovementsServiceClient.
        $automaticImprovementsServiceClient = new AutomaticImprovementsServiceClient($options);

        // Constructs the full resource name for the automatic improvements settings.
        $name = self::getAutomaticImprovementsName($config['accountId']);

        // Prepares the AutomaticImprovements object with all settings enabled.
        $automaticImprovements = new AutomaticImprovements([
            'name' => $name,
            'item_updates' => new AutomaticItemUpdates([
                'account_item_updates_settings' => new ItemUpdatesAccountLevelSettings([
                    'allow_price_updates' => true,
                    'allow_availability_updates' => true,
                    'allow_strict_availability_updates' => true,
                    'allow_condition_updates' => true
                ])
            ]),
            'image_improvements' => new AutomaticImageImprovements([
                'account_image_improvements_settings' => new ImageImprovementsAccountLevelSettings([
                    'allow_automatic_image_improvements' => true
                ])
            ]),
            'shipping_improvements' => new AutomaticShippingImprovements([
                'allow_shipping_improvements' => true
            ])
        ]);

        // Creates a FieldMask to indicate that all paths provided in $automaticImprovements
        // should be updated. The "*" path means to replace all updatable fields.
        $fieldMask = new FieldMask(['paths' => ['*']]);

        // Creates the UpdateAutomaticImprovementsRequest.
        $request = new UpdateAutomaticImprovementsRequest([
            'automatic_improvements' => $automaticImprovements,
            'update_mask' => $fieldMask
        ]);

        printf("Sending Update AutomaticImprovements request%s", PHP_EOL);

        try {
            // Makes the API call to update automatic improvements settings.
            $response = $automaticImprovementsServiceClient->updateAutomaticImprovements($request);

            printf("Updated AutomaticImprovements Name below%s", PHP_EOL);
            printf("%s%s", $response->getName(), PHP_EOL);
        } catch (ApiException $e) {
            printf("ApiException was thrown: %s%s", $e->getMessage(), PHP_EOL);
        }
    }

    /**
     * Helper to execute the sample.
     *
     * @return void
     */
    public function callSample(): void
    {
        $config = Config::generateConfig();
        self::updateAutomaticImprovementsSample($config);
    }
}

// Runs the script.
$sample = new UpdateAutomaticImprovementsSample();
$sample->callSample();

Python

# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Updates the automatic improvements settings for a Merchant Center account."""
from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.protobuf import field_mask_pb2
from google.shopping.merchant_accounts_v1beta import AutomaticImageImprovements
from google.shopping.merchant_accounts_v1beta import AutomaticImprovements
from google.shopping.merchant_accounts_v1beta import AutomaticImprovementsServiceClient
from google.shopping.merchant_accounts_v1beta import AutomaticItemUpdates
from google.shopping.merchant_accounts_v1beta import AutomaticShippingImprovements
from google.shopping.merchant_accounts_v1beta import UpdateAutomaticImprovementsRequest


# Fetches the Merchant Center account ID from the configuration.
_ACCOUNT_ID = configuration.Configuration().read_merchant_info()

# The resource name for the AutomaticImprovements settings of the account.
# Format: accounts/{account}/automaticImprovements
_AUTOMATIC_IMPROVEMENTS_RESOURCE_NAME = (
    f"accounts/{_ACCOUNT_ID}/automaticImprovements"
)


def update_automatic_improvements_settings():
  """Updates automatic improvements settings for a Merchant Center account to enable all available automatic improvements.
  """

  # Generates OAuth 2.0 credentials for authenticating with the API.
  credentials = generate_user_credentials.main()

  # Creates a client for the AutomaticImprovementsService.
  client = AutomaticImprovementsServiceClient(credentials=credentials)

  # Prepares the AutomaticImprovements object with all improvements enabled.
  # The 'name' field specifies the AutomaticImprovements resource to update.
  automatic_improvements_config = AutomaticImprovements(
      name=_AUTOMATIC_IMPROVEMENTS_RESOURCE_NAME,
      item_updates=AutomaticItemUpdates(
          account_item_updates_settings=AutomaticItemUpdates.ItemUpdatesAccountLevelSettings(
              allow_price_updates=True,
              allow_availability_updates=True,
              allow_strict_availability_updates=True,
              allow_condition_updates=True,
          )
      ),
      image_improvements=AutomaticImageImprovements(
          account_image_improvements_settings=
          AutomaticImageImprovements.ImageImprovementsAccountLevelSettings(
              allow_automatic_image_improvements=True
          )
      ),
      shipping_improvements=AutomaticShippingImprovements(
          allow_shipping_improvements=True
      ),
  )

  # Creates a field mask to specify which fields of the
  # AutomaticImprovements resource should be updated.
  # Using "*" indicates that all fields provided in the
  # automatic_improvements_config object should be updated.
  field_mask = field_mask_pb2.FieldMask(paths=["*"])

  # Creates the update request, including the configured
  # AutomaticImprovements object and the field mask.
  request = UpdateAutomaticImprovementsRequest(
      automatic_improvements=automatic_improvements_config,
      update_mask=field_mask,
  )

  # Sends the request to update automatic improvements and handles the response.
  try:
    print("Sending Update AutomaticImprovements request")
    response = client.update_automatic_improvements(request=request)
    print("Updated AutomaticImprovements Name below")
    print(response.name)
  except RuntimeError as e:
    # Catches and prints any errors that occur during the API call.
    print(e)


if __name__ == "__main__":
  update_automatic_improvements_settings()