List accounts

Merchant API code sample to list 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 accounts for which the logged-in user has access to
 */
function listAccounts() {
  // IMPORTANT:
  // Enable the Merchant API Accounts sub-API Advanced Service and call it
  // "MerchantApiAccounts"

  try {
    console.log('Sending list Accounts request');
    let pageToken;
    let pageSize = 500;
    // Call the Accounts.list API method. Use the pageToken to iterate through
    // all pages of results.
    do {
      response =
          MerchantApiAccounts.Accounts.list({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);
  }
}

CSharp

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

using System;
using static MerchantApi.Authenticator;
using Google.Api.Gax;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Http;
using Newtonsoft.Json;
using Google.Shopping.Merchant.Accounts.V1Beta;


namespace MerchantApi
{
    public class ListAccountsSample
    {
        public void ListAccounts()
        {
            Console.WriteLine("=================================================================");
            Console.WriteLine("Listing all Accounts the user has access to");
            Console.WriteLine("=================================================================");

            // Authenticate using either oAuth or service account
            ICredential auth = Authenticator.Authenticate(
                MerchantConfig.Load(),
                // Passing the default scope for Merchant API: https://www.googleapis.com/auth/content
                AccountsServiceClient.DefaultScopes[0]);

            // Create client
            AccountsServiceSettings accountsServiceSettings = AccountsServiceSettings.GetDefault();

            // Create the AccountsServiceClient with the credentials
            AccountsServiceClientBuilder accountsServiceClientBuilder = new AccountsServiceClientBuilder
            {
                Credential = auth
            };
            AccountsServiceClient client = accountsServiceClientBuilder.Build();

            // Initialize request argument(s)
            ListAccountsRequest request = new ListAccountsRequest
            {
                PageSize = 1000, // Optional: specify the maximum number of accounts to return per page
            };

            // List all accounts the user has access to
            PagedEnumerable<ListAccountsResponse, Account> response = client.ListAccounts(request);

            // Print the paginated results. This automatically handles pagination
            // and retrieves all accounts in the account.
            foreach (ListAccountsResponse page in response.AsRawResponses())
            {

                Console.WriteLine("A page of results:");
                foreach (Account item in page)
                {
                    // Pretty print the accounts
                    Console.WriteLine(JsonConvert.SerializeObject(item, Formatting.Indented));

                }
            }
        }


        internal static void Main(string[] args)
        {
            var sample = new ListAccountsSample();
            sample.ListAccounts();
        }
    }
}

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.v1beta;

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1beta.Account;
import com.google.shopping.merchant.accounts.v1beta.AccountsServiceClient;
import com.google.shopping.merchant.accounts.v1beta.AccountsServiceClient.ListAccountsPagedResponse;
import com.google.shopping.merchant.accounts.v1beta.AccountsServiceSettings;
import com.google.shopping.merchant.accounts.v1beta.ListAccountsRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/**
 * This class demonstrates how to list all the accounts the user making the request has access to.
 * Please note that "listAccounts" method charge API quota on behalf of each specific user running the
 * request. "listSubAccounts" method is more suitable to list large number of sub-accounts.
 */
public class ListAccountsSample {

  public static void listAccounts(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();

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

      ListAccountsRequest request = ListAccountsRequest.newBuilder().build();

      System.out.println("Sending list accounts request:");
      ListAccountsPagedResponse response = accountsServiceClient.listAccounts(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);
    } 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();
    listAccounts(config);
  }
}

Node.js

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

'use strict';
const authUtils = require('../../../authentication/authenticate.js');
const {AccountsServiceClient} = require('@google-shopping/accounts').v1beta;

/**
 * Lists all Merchant Center accounts accessible by the authenticated user.
 * Please note that "listAccounts" method charge API quota on behalf of each 
 * specific user running the request. "listSubAccounts" method is more suitable
 * to list large number of sub-accounts.
 */
async function listAccounts() {
  try {
    // Retrieve authenticated credentials for the API call.
    const authClient = await authUtils.getOrGenerateUserCredentials();

    // Create an options object containing the authenticated client.
    const options = {authClient};

    // Initialize the Accounts API client.
    const accountsClient = new AccountsServiceClient(options);

    // Construct the request to list accounts. No parameters are needed to list
    // all accessible accounts.
    const request = {};

    console.log('Sending list accounts request...');
    // Call the API method to list accounts. This returns an async iterable.
    const iterable = accountsClient.listAccountsAsync(request);

    let count = 0;
    // Iterate asynchronously over all the accounts returned in the response.
    for await (const account of iterable) {
      // Print the details of each account.
      console.log(account);
      count++;
    }
    // Print the total number of accounts found.
    console.log(`Found ${count} accounts.`);
  } catch (error) {
    // Log any errors encountered during the process.
    console.error(`Failed to list accounts: ${error.message}`);
  }
}

// Execute the function to list accounts.
listAccounts();

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\V1beta\Client\AccountsServiceClient;
use Google\Shopping\Merchant\Accounts\V1beta\ListAccountsRequest;


/**
 * This class demonstrates how to list all the accounts the user making the request has access to.
 * Please note that "listAccounts" method charge API quota on behalf of each specific 
 * user running the request. "listSubAccounts" method is more suitable to list 
 * large number of sub-accounts.
 */
class ListAccounts
{
    public static function listAccounts(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);

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

            $request = new ListAccountsRequest();

            print "Sending list accounts request:\n";
            $response = $accountsServiceClient->listAccounts($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::listAccounts($config);
    }
}

$sample = new ListAccounts();
$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 accounts the user making the request has access to."""

from examples.authentication import generate_user_credentials
from google.shopping.merchant_accounts_v1beta import AccountsServiceClient
from google.shopping.merchant_accounts_v1beta import ListAccountsRequest


def list_accounts():
  """Lists all the accounts the user making the request has access to.

  Please note that "list_accounts" method charge API quota on behalf of each
  specific user running the request. "list_sub_accounts" method is more suitable
  to list large number of sub-accounts.
  """

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

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

  # Create the request.
  request = ListAccountsRequest()

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

    count = 0
    for account in response:
      print(account)
      count += 1
    print(f"The following count of accounts were returned: {count}")

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


if __name__ == "__main__":
  list_accounts()