Merchant API code sample to list account services.

### 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.accountservices.v1;
    import com.google.api.gax.core.FixedCredentialsProvider;
    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.shopping.merchant.accounts.v1.AccountService;
    import com.google.shopping.merchant.accounts.v1.AccountServicesServiceClient;
    import com.google.shopping.merchant.accounts.v1.AccountServicesServiceClient.ListAccountServicesPagedResponse;
    import com.google.shopping.merchant.accounts.v1.AccountServicesServiceSettings;
    import com.google.shopping.merchant.accounts.v1.ListAccountServicesRequest;
    import shopping.merchant.samples.utils.Authenticator;
    import shopping.merchant.samples.utils.Config;

    /** This class demonstrates how to list all the account services of an account. */
    public class ListAccountServicesSample {

      private static String getParent(String accountId) {
        return String.format("accounts/%s", accountId);
      }

      public static void listAccountServices(Config config) throws Exception {

        // Obtains OAuth token based on the user's configuration.
        GoogleCredentials credential = new Authenticator().authenticate();

        // Creates service settings using the credentials retrieved above.
        AccountServicesServiceSettings accountsServicesServiceSettings =
            AccountServicesServiceSettings.newBuilder()
                .setCredentialsProvider(FixedCredentialsProvider.create(credential))
                .build();

        // Creates parent to identify the account from which to list all account services.
        String parent = getParent(config.getAccountId().toString());

        // Calls the API and catches and prints any network failures/errors.
        try (AccountServicesServiceClient accountServicesServiceClient =
            AccountServicesServiceClient.create(accountsServicesServiceSettings)) {

          ListAccountServicesRequest request =
              ListAccountServicesRequest.newBuilder().setParent(parent).build();

          System.out.println("Sending list account services request:");
          ListAccountServicesPagedResponse response =
              accountServicesServiceClient.listAccountServices(request);

          int count = 0;

          // Iterates over all rows in all pages and prints the service in each row.
          // Automatically uses the `nextPageToken` if returned to fetch all pages of data.
          for (AccountService accountService : response.iterateAll()) {
            System.out.println(accountService);
            count++;
          }
          System.out.print("The following count of account services were returned: ");
          System.out.println(count);
        } catch (Exception e) {
          System.out.println("An error has occured: ");
          System.out.println(e);
        }
      }

      public static void main(String[] args) throws Exception {
        Config config = Config.load();
        listAccountServices(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\Shopping\Merchant\Accounts\V1\Client\AccountServicesServiceClient;
    use Google\Shopping\Merchant\Accounts\V1\ListAccountServicesRequest;

    /**
     * This class demonstrates how to list all the account services of an account.
     */
    class ListAccountServicesSample
    {
        /**
         * A helper function to create the parent string.
         *
         * @param string $accountId The account that owns the product.
         *
         * @return string The parent has the format: `accounts/{account_id}`
         */
        private static function getParent(string $accountId): string
        {
            return sprintf('accounts/%s', $accountId);
        }

        /**
         * Lists all account services for a given account.
         *
         * @param array $config The configuration data used for authentication and
         *     getting the account ID.
         */
        public static function listAccountServices(array $config): void
        {
            // Gets the OAuth credentials to make the request.
            $credentials = Authentication::useServiceAccountOrTokenFile();

            // Creates options containing credentials for the client to use.
            $options = ['credentials' => $credentials];

            // Creates a client.
            $accountServicesServiceClient = new AccountServicesServiceClient($options);

            // Creates parent to identify the account from which to list all
            // account services.
            $parent = self::getParent($config['accountId']);

            // Calls the API and catches and prints any network failures/errors.
            try {
                $request = (new ListAccountServicesRequest())
                    ->setParent($parent);

                print "Sending list account services request:\n";
                $response = $accountServicesServiceClient->listAccountServices($request);

                $count = 0;

                // Iterates over all rows in all pages and prints the service in
                // each row. Automatically uses the `nextPageToken` if returned to
                // fetch all pages of data.
                foreach ($response->iterateAllElements() as $accountService) {
                    print $accountService->serializeToJsonString(true) . PHP_EOL;
                    $count++;
                }
                printf(
                    "The following count of account services were returned: %d%s",
                    $count,
                    PHP_EOL
                );
            } catch (ApiException $e) {
                printf("An error has occurred: %s%s", $e->getMessage(), PHP_EOL);
            }
        }

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

    // Run the script
    $sample = new ListAccountServicesSample();
    $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.
    """This class demonstrates how to list all the account services of an account."""

    from examples.authentication import configuration
    from examples.authentication import generate_user_credentials
    from google.shopping.merchant_accounts_v1 import AccountServicesServiceClient
    from google.shopping.merchant_accounts_v1 import ListAccountServicesRequest

    _ACCOUNT = configuration.Configuration().read_merchant_info()
    _PARENT = f"accounts/{_ACCOUNT}"


    def list_account_services() -> None:
      """Lists all account services for the configured account."""
      # Gets OAuth Credentials.
      credentials = generate_user_credentials.main()

      # Creates a client.
      client = AccountServicesServiceClient(credentials=credentials)

      # Creates the request.
      request = ListAccountServicesRequest(parent=_PARENT)

      # Makes the request and catches and prints any error messages.
      try:
        print("Sending list account services request:")
        response = client.list_account_services(request=request)

        count = 0

        # Iterates over all returned account services and prints them.
        # The client library automatically uses the `next_page_token` to fetch all
        # pages of data.
        for account_service in response:
          print(account_service)
          count += 1
        print(f"The following count of account services were returned: {count}")
      except RuntimeError as e:
        print(f"An error has occured: \n{e}")


    if __name__ == "__main__":
      list_account_services()