Filter accounts you can access

The accounts.list method lets you retrieve a list of Account resources that the authenticated user can access. You can use the filter query parameter to narrow down the results based on various criteria, such as the following:

  • Account properties
  • Relationships with other accounts (such as, providers in an advanced account structure)
  • Services associated with the accounts

This can be helpful for managing multiple accounts or finding specific business accounts that meet certain conditions.

You can use the following fields to filter at the account level:

  • access: Filters by the type of access the user has to the account. This filter accepts the following values:
    • DIRECT: Returns only accounts that the user has direct access to.
    • INDIRECT: Returns only accounts that the user has indirect access to.
    • ALL: Returns all accounts the user has access to (both direct and indirect). This is the default behavior if the filter is not specified.
  • capabilities: Filters by the capabilities of the account resource (note that this field is not available on the resource itself). Only the CAN_UPLOAD_PRODUCTS capability is supported. This field supports negation and uses the collection syntax.
  • relationship(...): Filters by the type of relationship the account has with another account. You can include multiple relationship(...) filters in one request.
  • accountName: Filters by the accountName of the account resource.

For more detailed information on the filter syntax, see the Filter syntax guide.

Examples

The following examples explain how to form the most typical queries. All the following examples use the accounts.list method. For more information, see the accounts.list reference documentation.

Find sub-accounts of a specific provider

The accounts.listSubaccounts method provides a direct way to list sub-accounts. You can also use the filtering capabilities as described in the following sections. If you manage an advanced account, you can list all its sub-accounts by filtering on the providerId. Replace PROVIDER_ID with the ID of your advanced account.

For example, use relationship(providerId=123) if the ID of the provider is 123.

This is useful for managing the structure of your accounts.

GET https://merchantapi.googleapis.com/accounts/v1beta/accounts?filter=relationship(providerId%20%3D%20PROVIDER_ID)

A successful request returns a 200 status code and a response body with the list of matching sub-accounts:

{
  "accounts": [
    {
      "name": "accounts/77777",
      "accountId": "77777",
      "accountName": "SubAccount A of Provider",
      "adultContent": false,
      "languageCode": "fr",
      "timeZone": {
        "id": "Europe/Paris"
      }
    },
    {
      "name": "accounts/88888",
      "accountId": "88888",
      "accountName": "SubAccount B of Provider",
      "adultContent": false,
      "languageCode": "de",
      "timeZone": {
        "id": "Europe/Berlin"
      }
    }
  ],
  "nextPageToken": "XYZ123abcDEF..."
}

Find accounts that cannot upload products

You can combine multiple filter conditions to create more specific searches.

The filter accountName=*store* AND -capabilities:CAN_UPLOAD_PRODUCTS finds all accounts with "store" in their name that are not configured to upload products directly. The - before capabilities acts as a negation operator. This can be useful to retrieve only advanced accounts.

GET https://merchantapi.googleapis.com/accounts/v1beta/accounts?filter=accountName%20%3D%20%22*store*%22%20AND%20-capabilities%3ACAN_UPLOAD_PRODUCTS

A successful request returns a 200 status code and a response body with the list of matching accounts:

{
  "accounts": [
    {
      "name": "accounts/54321",
      "accountId": "54321",
      "accountName": "Partner Store - US",
      "adultContent": false,
      "languageCode": "en",
      "timeZone": {
        "id": "America/New_York"
      }
    },
    {
      "name": "accounts/98765",
      "accountId": "98765",
      "accountName": "Auxiliary Brand Store",
      "adultContent": false,
      "languageCode": "fr",
      "timeZone": {
        "id": "Europe/Paris"
      }
    }
  ],
  "nextPageToken": "CDEfghIJKlmnOPQ..."
}

Find accounts by name

You can search for accounts whose display name matches a specific pattern.

For example, accountName=*store* would find all accounts with "store" in their name.

This helps in quickly locating specific business accounts.

GET https://merchantapi.googleapis.com/accounts/v1beta/accounts?filter=accountName%20%3D%20%22*store*%22

A successful request returns a 200 status code and a response body with the list of matching accounts:

{
  "accounts": [
    {
      "name": "accounts/12345",
      "accountId": "12345",
      "accountName": "My Awesome Store",
      "adultContent": false,
      "languageCode": "en",
      "timeZone": {
        "id": "America/Los_Angeles"
      }
    },
    {
      "name": "accounts/67890",
      "accountId": "67890",
      "accountName": "Another Store Online",
      "adultContent": false,
      "languageCode": "en",
      "timeZone": {
        "id": "Europe/London"
      }
    }
  ],
  "nextPageToken": "ABSdefGHIjklMNO..."
}

Find accounts linked to a provider for a specific service

You can find accounts that have a specific service relationship with a provider. For example, to find all accounts aggregated under the provider PROVIDER_ID for account aggregation, use the filter relationship(providerId=PROVIDER_ID) AND service(type="ACCOUNT_AGGREGATION").

GET https://merchantapi.googleapis.com/accounts/v1beta/accounts?filter=relationship(providerId%20%3D%20PROVIDER_ID%20AND%20service(type%20%3D%20%22ACCOUNT_AGGREGATION%22))

A successful request returns a 200 status code and a response body with the list of matching accounts:

{
  "accounts": [
    {
      "name": "accounts/54321",
      "accountId": "54321",
      "accountName": "Aggregated Account X",
      "adultContent": false,
      "languageCode": "en",
      "timeZone": {
        "id": "America/New_York"
      }
    }
  ]
}

Find accounts based on service relationship approval state

You can filter accounts based on the status of their service relationship with a provider. For example, to find all accounts that haven't accepted an account link request (handshakeState = "PENDING") from a specific provider PROVIDER_ID.

For example, to find accounts where the provider ID is 123, the service type is ACCOUNT_MANAGEMENT and the status is PENDING, use relationship(service(handshakeState = "PENDING" AND type = "ACCOUNT_MANAGEMENT") AND providerId = 123).

GET https://merchantapi.googleapis.com/accounts/v1beta/accounts?filter=relationship(service(handshakeState%20%3D%20%22PENDING%22%20AND%20type%20%3D%20%22ACCOUNT_MANAGEMENT%22)%20AND%20providerId%20%3D%20PROVIDER_ID)

A successful request returns a 200 status code and a response body with the list of matching accounts:

{
  "accounts": [
    {
      "name": "accounts/98765",
      "accountId": "98765",
      "accountName": "Managed Account Y",
      "adultContent": false,
      "languageCode": "es",
      "timeZone": {
        "id": "Europe/Madrid"
      }
    }
  ]
}

Filter accounts using client libraries

The following examples demonstrate how to use client libraries to filter accounts based on combined criteria, such as account name and relationship with a provider. These examples use the accounts.list method. For more information, see the accounts.list reference documentation.

Java

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 filter the accounts the user making the request has access to. */
public class FilterAccountsSample {

  public static void filterAccounts(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)) {

      // Filter for accounts with display names containing "store" and a provider with the ID "123":
      String filter = "accountName = \"*store*\" AND relationship(providerId = 123)";

      // Filter for all subaccounts of account "123":
      // String filter2 = "relationship(providerId = 123 AND service(type =
      // \"ACCOUNT_AGGREGATION\"))";

      // String filter3 = "relationship(service(handshakeState = \"APPROVED\" AND type =
      // \"ACCOUNT_MANAGEMENT\") AND providerId = 123)";

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

      System.out.println("Sending list accounts request with filter:");
      ListAccountsPagedResponse response = accountsServiceClient.listAccounts(request);

      int count = 0;

      // Iterates over all rows in all pages and prints the sub-account
      // in each row.
      // `response.iterateAll()` automatically uses the `nextPageToken` and recalls the
      // request to fetch all pages of data.
      for (Account account : response.iterateAll()) {
        System.out.println(account);
        count++;
      }
      System.out.print("The following count of elements were returned: ");
      System.out.println(count);
    } catch (Exception e) {
      System.out.println(e);
    }
  }

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

    filterAccounts(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 filter the accounts the user making the request has access to.
 */
class FilterAccounts
{
    public static function filterAccounts(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 {

            // Filter for accounts with display names containing "store" and a provider with the ID "123":
            $filter = "accountName = \"*store*\" AND relationship(providerId = 123)";

            // Filter for all subaccounts of account "123":
            // $filter = "relationship(providerId = 123 AND service(type = \"ACCOUNT_AGGREGATION\"))";

            // $filter = "relationship(service(handshakeState = \"APPROVED\" AND type =
            // \"ACCOUNT_MANAGEMENT\") AND providerId = 123)";

            $request = new ListAccountsRequest(['filter' => $filter]);

            print "Sending list accounts request with filter:\n";
            $response = $accountsServiceClient->listAccounts($request);

            $count = 0;

            // Iterates over all rows in all pages and prints the sub-account
            // in each row.
            // `response.iterateAll()` automatically uses the `nextPageToken` and recalls the
            // request to fetch all pages of data.
            foreach ($response->iterateAllElements() as $account) {
                print_r($account); 
                $count++;
            }
            print "The following count of elements were returned: ";
            print $count . PHP_EOL;
        } catch (ApiException $e) {
            print $e->getMessage();
        }
    }

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

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

Python

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


def filter_accounts():
  """Filters the accounts the user making the request has access to."""

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

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

  # Create the filter string.
  filter_string = 'accountName = "*store*" AND relationship(providerId = 123)'

  # Create the request.
  request = ListAccountsRequest(filter=filter_string)

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

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

    print(f"The following count of elements were returned: {count}")

  except RuntimeError as e:
    print(e)


if __name__ == "__main__":
  filter_accounts()

AppsScript


/**
 * Filters and lists accounts for which the logged-in user has access to
 */
function filterAccounts() {
  // IMPORTANT:
  // Enable the Merchant API Accounts sub-API Advanced Service and call it
  // "MerchantApiAccounts"

  // Create the filter string.
  // Documentation can be found at
  // https://developers.google.com/merchant/api/guides/accounts/filter-syntax
  const filter = 'accountName = "*store*" AND relationship(providerId = 123)';
  try {
    console.log('Sending filter Accounts request');
    let pageToken;
    let pageSize = 500;
    // Call the Accounts.list API method with a filter. Use the pageToken to iterate through
    // all pages of results.
    do {
      response =
          MerchantApiAccounts.Accounts.list({pageSize, pageToken, filter});
      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);
  }
}

cURL

curl --location 'https://merchantapi.googleapis.com/accounts/v1beta/accounts?filter=accountName%20%3D%20%22*store*%22%20AND%20relationship(providerId%20%3D%20PROVIDER_ID)' \
--header 'Authorization: Bearer <API_TOKEN>'