Google Ads API is returning to beta status. Please read our blog post for more details.

Listing Accounts

You can list customers accessible to you with the ListAccessibleCustomers method in CustomerService. However, it is necessary to understand which customers are returned in this type of request.

Listing accessible customers is one of the few requests in the Google Ads API that does not require you to specify a customer ID in the request, and will ignore any supplied login-customer-id.

The resulting list of customers is based on your OAuth credentials. The request returns a list of all accounts that you are able to act upon directly given your current credentials. This will not necessarily include all accounts within the account hierarchy; rather, it will only include accounts where your authenticated user has been added with admin or other rights in the account.

Imagine you are user A who is an admin for M1 and C3 in the two hierarchies pictured above. If you were to make a call to the Google Ads API, for example to GoogleAdsService, you could access information for accounts M1, C1, C2, and C3. However, a call to CustomerService.ListAccessibleCustomers would return only M1 and C3 since those are the only accounts where user A has direct access.

Here is a code example illustrating the use of the ListAccessibleCustomers method:

Java

private void runExample(GoogleAdsClient client) {
  // Optional: Change credentials to use a different refresh token, to retrieve customers
  //           available for a specific user.
  //
  // UserCredentials credentials =
  //     UserCredentials.newBuilder()
  //         .setClientId("INSERT_OAUTH_CLIENT_ID")
  //         .setClientSecret("INSERT_OAUTH_CLIENT_SECRET")
  //         .setRefreshToken("INSERT_REFRESH_TOKEN")
  //         .build();
  //
  // client = client.toBuilder().setCredentials(credentials).build();

  try (CustomerServiceClient customerService =
      client.getLatestVersion().createCustomerServiceClient()) {
    ListAccessibleCustomersResponse response =
        customerService.listAccessibleCustomers(
            ListAccessibleCustomersRequest.newBuilder().build());

    System.out.printf("Total results: %d%n", response.getResourceNamesCount());

    for (String customerResourceName : response.getResourceNamesList()) {
      System.out.printf("Customer resource name: %s%n", customerResourceName);
    }
  }
}

C#

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

using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V2.Errors;
using Google.Ads.GoogleAds.V2.Services;

using System;

namespace Google.Ads.GoogleAds.Examples.V2
{
    /// <summary>
    /// This code example lists the resource names for the customers that the authenticating user
    /// has access to. This example may can be used to display a list of customer IDs that can be
    /// selected by the user for setting the login-customer-id in a subsequent call. See
    /// https://developers.google.com/google-ads/api/docs/concepts/call-structure#login-customer-id
    /// to learn more about the login-customer-id header.
    /// </summary>
    public class ListAccessibleCustomers : ExampleBase
    {
        /// <summary>
        /// Main method, to run this code example as a standalone application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            ListAccessibleCustomers codeExample = new ListAccessibleCustomers();

            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient());
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get
            {
                return "This code example lists the resource names for the customers that the " +
                    "authenticating user has access to. This example may be used to display a " +
                    "list of customer IDs that can be selected by the user for setting the " +
                    "login-customer-id in a subsequent call. See "+
                    "https://developers.google.com/google-ads/api/docs/concepts/call-structure#login-customer-id "+
                    "to learn more about the login-customer-id header.";
            }
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        public void Run(GoogleAdsClient client)
        {
            // Get the CustomerService.
            CustomerServiceClient customerService = client.GetService(Services.V2.CustomerService);

            try
            {
                // Retrieve the list of customer resources.
                string[] customerResourceNames = customerService.ListAccessibleCustomers();

                // Display the result.
                foreach (string customerResourceName in customerResourceNames)
                {
                    Console.WriteLine(
                        $"Found customer with resource name = '{customerResourceName}'.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
            }
        }
    }
}

PHP

<?php
/**
 * Copyright 2019 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.
 */

namespace Google\Ads\GoogleAds\Examples\AccountManagement;

require __DIR__ . '/../../vendor/autoload.php';

use Google\Ads\GoogleAds\Lib\V2\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V2\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V2\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\V2\Errors\GoogleAdsError;
use Google\ApiCore\ApiException;

/**
 * This example lists the resource names for the customers that the authenticating user has access
 * to.
 *
 * The customer IDs retrieved from the resource names can be used to set
 * the login-customer-id configuration. For more information see this
 * documentation:
 * https://developers.google.com/google-ads/api/docs/concepts/call-structure#login-customer-id
 */
class ListAccessibleCustomers
{
    const PAGE_SIZE = 1000;

    public static function main()
    {
        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            ->build();

        try {
            self::runExample($googleAdsClient);
        } catch (GoogleAdsException $googleAdsException) {
            printf(
                "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
                $googleAdsException->getRequestId(),
                PHP_EOL,
                PHP_EOL
            );
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
                /** @var GoogleAdsError $error */
                printf(
                    "\t%s: %s%s",
                    $error->getErrorCode()->getErrorCode(),
                    $error->getMessage(),
                    PHP_EOL
                );
            }
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     */
    public static function runExample(GoogleAdsClient $googleAdsClient)
    {
        $customerServiceClient = $googleAdsClient->getCustomerServiceClient();

        // Issues a request for listing all accessible customers.
        $accessibleCustomers = $customerServiceClient->listAccessibleCustomers();
        print 'Total results: ' . count($accessibleCustomers->getResourceNames()) . PHP_EOL;

        // Iterates over all accessible customers' resource names and prints them.
        foreach ($accessibleCustomers->getResourceNames() as $resourceName) {
            /** @var string $resourceName */
            printf("Customer resource name: '%s'%s", $resourceName, PHP_EOL);
        }
    }
}

ListAccessibleCustomers::main();

Python

def main(client):
    customer_service = client.get_service('CustomerService', version='v2')

    try:
        accessible_customers = customer_service.list_accessible_customers()
        result_total = len(accessible_customers.resource_names)
        print('Total results: %i' % result_total)

        resource_names = accessible_customers.resource_names
        for resource_name in resource_names:
            print('Customer resource name: "%s"' % resource_name)
    except google.ads.google_ads.errors.GoogleAdsException as ex:
        print('Request with ID "%s" failed with status "%s" and includes the '
              'following errors:' % (ex.request_id, ex.error.code().name))
        for error in ex.failure.errors:
            print('\tError with message "%s".' % error.message)
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print('\t\tOn field: %s' % field_path_element.field_name)
        sys.exit(1)

Ruby

def list_accessible_customers()
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  accessible_customers = client.service.customer.list_accessible_customers().resource_names

  accessible_customers.each do |resource_name|
    puts "Customer resource name: #{resource_name}"
  end
end