Merchant API code sample to list sub accounts.

### AppsScript

    // 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.


    /**
     * Lists all sub-accounts for a given Provider ID
     */
    function listSubAccounts() {
      // IMPORTANT:
      // Enable the Merchant API Accounts sub-API Advanced Service and call it
      // "MerchantApiAccounts"

      // Replace this with the provider Merchant Center ID for which you want to list the sub-accounts
      // This is usually an advanced account
      const providerId = '<MERCHANT_CENTER_ID>';

      const parent = 'accounts/' + providerId;

      try {
        console.log('Sending list Sub-Accounts request');
        let pageToken;
        const pageSize = 500;
        // Call the Accounts.listSubAccounts API method. Use the pageToken to iterate through
        // all pages of results.
        do {
          const response =
              MerchantApiAccounts.Accounts.listSubaccounts(parent, {pageSize, pageToken});
          for (const account of response.accounts) {
            console.log(account);
          }
          pageToken = response.nextPageToken;
        } while (pageToken); // Exits when there is no next page token.
      } catch (e) {
        console.log('ERROR!');
        console.log(e);
      }
    }

### 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.accounts.v1;
    import com.google.api.gax.core.FixedCredentialsProvider;
    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.shopping.merchant.accounts.v1.Account;
    import com.google.shopping.merchant.accounts.v1.AccountsServiceClient;
    import com.google.shopping.merchant.accounts.v1.AccountsServiceClient.ListSubAccountsPagedResponse;
    import com.google.shopping.merchant.accounts.v1.AccountsServiceSettings;
    import com.google.shopping.merchant.accounts.v1.ListSubAccountsRequest;
    import shopping.merchant.samples.utils.Authenticator;
    import shopping.merchant.samples.utils.Config;

    /** This class demonstrates how to list all the subaccounts of an advanced account. */
    public class ListSubAccountsSample {

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

      public static ListSubAccountsPagedResponse listSubAccounts(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.
        AccountsServiceSettings accountsServiceSettings =
            AccountsServiceSettings.newBuilder()
                .setCredentialsProvider(FixedCredentialsProvider.create(credential))
                .build();

        // Creates parent/provider to identify the advanced account from which to list all sub-accounts.
        String parent = getParent(config.getAccountId().toString());

        // Calls the API and catches and prints any network failures/errors.
        try (AccountsServiceClient accountsServiceClient =
            AccountsServiceClient.create(accountsServiceSettings)) {

          // The parent has the format: accounts/{account}
          ListSubAccountsRequest request =
              ListSubAccountsRequest.newBuilder().setProvider(parent).build();
          System.out.println("Sending list subaccounts request:");

          ListSubAccountsPagedResponse response = accountsServiceClient.listSubAccounts(request);

          int count = 0;

          // 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 data.
          for (Account account : response.iterateAll()) {
            System.out.println(account);
            count++;
          }
          System.out.print("The following count of accounts were returned: ");
          System.out.println(count);
          return response;
        }
      }

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

    /**
     * This class demonstrates how to list all the subaccounts of an advanced account.
     */
    class ListSubAccounts
    {
        private static function getParent(string $accountId): string
        {
            return sprintf("accounts/%s", $accountId);
        }


        public static function listSubAccounts(array $config): void
        {
            // 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.
            $accountsServiceClient = new AccountsServiceClient($options);

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

            // Calls the API and catches and prints any network failures/errors.
            try {

                // The parent has the format: accounts/{account}
                $request = new ListSubAccountsRequest(['provider' => $parent]);
                print "Sending list subaccounts request:\n";

                $response = $accountsServiceClient->listSubAccounts($request);

                $count = 0;

                // 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 data.
                foreach ($response->iterateAllElements() as $account) {
                    print_r($account);
                    $count++;
                }
                print "The following count of accounts were returned: ";
                print $count . PHP_EOL;
            } catch (ApiException $e) {
                print "An error has occured: \n";
                print $e->getMessage();
            }
        }

        public function callSample(): void
        {
            $config = Config::generateConfig();
            self::listSubAccounts($config);
        }
    }

    $sample = new ListSubAccounts();
    $sample->callSample();

### Python

    # -*- coding: utf-8 -*-
    # 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
    #
    #     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.
    """A module to list all the subaccounts of an advanced account."""

    from examples.authentication import configuration
    from examples.authentication import generate_user_credentials
    from google.shopping.merchant_accounts_v1 import AccountsServiceClient
    from google.shopping.merchant_accounts_v1 import ListSubAccountsRequest


    def get_parent(account_id):
      return f"accounts/{account_id}"


    def list_sub_accounts(account_id: str):
      """Lists all the subaccounts of an advanced account."""

      # Get OAuth credentials.
      credentials = generate_user_credentials.main()

      # Create a client.
      client = AccountsServiceClient(credentials=credentials)

      # Get the parent advanced account ID.
      parent = get_parent(account_id)

      # Create the request.
      request = ListSubAccountsRequest(provider=parent)

      # Make the request and print the response.
      try:
        print("Sending list subaccounts request:")
        response = client.list_sub_accounts(request=request)

        count = 0
        for account in response:
          print(account)
          count += 1

        print(f"The following count of accounts were returned: {count}")
        return response

      except RuntimeError as e:
        print("An error has occured: ")
        print(e)
        raise


    if __name__ == "__main__":
      _account_id = configuration.Configuration().read_merchant_info()
      list_sub_accounts(_account_id)