Merchant API code sample to list account relationships.
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.accountrelationships.v1;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1.AccountRelationship;
import com.google.shopping.merchant.accounts.v1.AccountRelationshipsServiceClient;
import com.google.shopping.merchant.accounts.v1.AccountRelationshipsServiceClient.ListAccountRelationshipsPagedResponse;
import com.google.shopping.merchant.accounts.v1.AccountRelationshipsServiceSettings;
import com.google.shopping.merchant.accounts.v1.ListAccountRelationshipsRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to list all the account relationships of an account. */
public class ListAccountRelationshipsSample {
private static String getParent(String accountId) {
return String.format("accounts/%s", accountId);
}
public static void listAccountRelationships(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.
AccountRelationshipsServiceSettings accountsRelationshipsServiceSettings =
AccountRelationshipsServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
// Creates parent to identify the account from which to list all account relationships.
String parent = getParent(config.getAccountId().toString());
// Calls the API and catches and prints any network failures/errors.
try (AccountRelationshipsServiceClient accountRelationshipsServiceClient =
AccountRelationshipsServiceClient.create(accountsRelationshipsServiceSettings)) {
ListAccountRelationshipsRequest request =
ListAccountRelationshipsRequest.newBuilder().setParent(parent).build();
System.out.println("Sending list account relationships request:");
ListAccountRelationshipsPagedResponse response =
accountRelationshipsServiceClient.listAccountRelationships(request);
int count = 0;
// Iterates over all rows in all pages and prints the relationship in each row.
// Automatically uses the `nextPageToken` if returned to fetch all pages of data.
for (AccountRelationship accountRelationship : response.iterateAll()) {
System.out.println(accountRelationship);
count++;
}
System.out.print("The following count of account relationships 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();
listAccountRelationships(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\AccountRelationshipsServiceClient;
use Google\Shopping\Merchant\Accounts\V1\ListAccountRelationshipsRequest;
/**
* This class demonstrates how to list all the relationships of an account.
*/
class ListAccountRelationshipsSample
{
/**
* Lists all account relationships for a given Merchant Center account.
*
* @param array $config The configuration file for authentication.
*/
public static function listAccountRelationshipsSample(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.
$accountRelationshipsServiceClient = new AccountRelationshipsServiceClient($options);
// The parent account from which to list all account relationships.
// Format: accounts/{account}
$parent = AccountRelationshipsServiceClient::accountName($config['accountId']);
// Creates the request.
$request = new ListAccountRelationshipsRequest([
'parent' => $parent
]);
// Calls the API and catches and prints any network failures/errors.
try {
printf("Sending list account relationships request:%s", PHP_EOL);
$response = $accountRelationshipsServiceClient->listAccountRelationships($request);
$count = 0;
// Iterates over all relationships and prints them.
// The `iterateAllElements` method automatically handles pagination.
foreach ($response->iterateAllElements() as $accountRelationship) {
print $accountRelationship->serializeToJsonString(true) . PHP_EOL;
$count++;
}
printf("The following count of account relationships were returned: %d%s", $count, PHP_EOL);
} catch (ApiException $e) {
printf("An error has occured: %s", PHP_EOL);
print $e->getMessage() . PHP_EOL;
}
}
/**
* Helper to execute the sample.
*/
public function callSample(): void
{
$config = Config::generateConfig();
self::listAccountRelationshipsSample($config);
}
}
// Runs the sample.
$sample = new ListAccountRelationshipsSample();
$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.
"""Sample for listing account relationships."""
from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_accounts_v1 import AccountRelationshipsServiceClient
from google.shopping.merchant_accounts_v1 import ListAccountRelationshipsRequest
# Gets the account ID from the configuration file.
_ACCOUNT_ID = configuration.Configuration().read_merchant_info()
_PARENT = f"accounts/{_ACCOUNT_ID}"
def list_account_relationships() -> None:
"""Lists all the account relationships of an account."""
# Gets OAuth Credentials.
credentials = generate_user_credentials.main()
# Creates a client.
client = AccountRelationshipsServiceClient(credentials=credentials)
# Creates the request.
request = ListAccountRelationshipsRequest(parent=_PARENT)
# Makes the request and catches and prints any error messages.
try:
print("Sending list account relationships request:")
response = client.list_account_relationships(request=request)
count = 0
# Iterates over all relationships and prints them.
# The client library automatically handles pagination.
for relationship in response:
print(relationship)
count += 1
print(
f"The following count of account relationships were returned: {count}"
)
except RuntimeError as e:
print("An error has occured: ")
print(e)
if __name__ == "__main__":
list_account_relationships()