Stay organized with collections
Save and categorize content based on your preferences.
Merchant API code sample to list users.
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.packageshopping.merchant.samples.accounts.users.v1;importcom.google.api.gax.core.FixedCredentialsProvider;importcom.google.auth.oauth2.GoogleCredentials;importcom.google.shopping.merchant.accounts.v1.ListUsersRequest;importcom.google.shopping.merchant.accounts.v1.User;importcom.google.shopping.merchant.accounts.v1.UserServiceClient;importcom.google.shopping.merchant.accounts.v1.UserServiceClient.ListUsersPagedResponse;importcom.google.shopping.merchant.accounts.v1.UserServiceSettings;importshopping.merchant.samples.utils.Authenticator;importshopping.merchant.samples.utils.Config;/** This class demonstrates how to list all the users for a given Merchant Center account. */publicclassListUsersSample{privatestaticStringgetParent(StringaccountId){returnString.format("accounts/%s",accountId);}publicstaticvoidlistUsers(Configconfig)throwsException{// Obtains OAuth token based on the user's configuration.GoogleCredentialscredential=newAuthenticator().authenticate();// Creates service settings using the credentials retrieved above.UserServiceSettingsuserServiceSettings=UserServiceSettings.newBuilder().setCredentialsProvider(FixedCredentialsProvider.create(credential)).build();// Creates parent to identify the account from which to list all users.Stringparent=getParent(config.getAccountId().toString());// Calls the API and catches and prints any network failures/errors.try(UserServiceClientuserServiceClient=UserServiceClient.create(userServiceSettings)){// The parent has the format: accounts/{account}ListUsersRequestrequest=ListUsersRequest.newBuilder().setParent(parent).build();System.out.println("Sending list users request:");ListUsersPagedResponseresponse=userServiceClient.listUsers(request);intcount=0;// Iterates over all rows in all pages and prints the user// in each row.// `response.iterateAll()` automatically uses the `nextPageToken` and recalls the// request to fetch all pages of data.for(Userelement:response.iterateAll()){System.out.println(element);count++;}System.out.print("The following count of elements were returned: ");System.out.println(count);}catch(Exceptione){System.out.println(e);}}publicstaticvoidmain(String[]args)throwsException{Configconfig=Config.load();listUsers(config);}}
<?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. *//** * Demonstrates how to list all the users for a given Merchant Center account. */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\ListUsersRequest;use Google\Shopping\Merchant\Accounts\V1\Client\UserServiceClient;/** * Lists users. * * @param array $config The configuration data. * @return void */function listUsers($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. $userServiceClient = new UserServiceClient($options); // Creates parent to identify the account from which to list all users. $parent = sprintf("accounts/%s", $config['accountId']); // Calls the API and catches and prints any network failures/errors. try { $request = new ListUsersRequest(['parent' => $parent]); print "Sending list users request:\n"; $response = $userServiceClient->listUsers($request); $count = 0; foreach ($response->iterateAllElements() as $element) { print_r($element); $count++; } print "The following count of elements were returned: "; print $count . "\n"; } catch (ApiException $e) { print $e->getMessage(); }}$config = Config::generateConfig();listUsers($config);
# -*- 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 users."""fromexamples.authenticationimportconfigurationfromexamples.authenticationimportgenerate_user_credentialsfromgoogle.shopping.merchant_accounts_v1importListUsersRequestfromgoogle.shopping.merchant_accounts_v1importUserServiceClient_ACCOUNT=configuration.Configuration().read_merchant_info()defget_parent(account_id):returnf"accounts/{account_id}"deflist_users():"""Lists all the users for a given Merchant Center account."""# Get OAuth credentialscredentials=generate_user_credentials.main()# Create a UserServiceClientclient=UserServiceClient(credentials=credentials)# Create parent stringparent=get_parent(_ACCOUNT)# Create the requestrequest=ListUsersRequest(parent=parent)try:print("Sending list users request:")response=client.list_users(request=request)count=0forelementinresponse:print(element)count+=1print("The following count of elements were returned: ")print(count)exceptRuntimeErrorase:print(e)if__name__=="__main__":list_users()
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-13 UTC."],[[["\u003cp\u003eThis webpage provides code samples in Java, PHP, and Python demonstrating how to list all users associated with a specific Merchant Center account.\u003c/p\u003e\n"],["\u003cp\u003eThe code examples utilize the Merchant API to create a \u003ccode\u003eListUsersRequest\u003c/code\u003e and retrieve a \u003ccode\u003eListUsersPagedResponse\u003c/code\u003e or equivalent response object to get users.\u003c/p\u003e\n"],["\u003cp\u003eEach code sample authenticates using OAuth credentials and configures a \u003ccode\u003eUserServiceClient\u003c/code\u003e or equivalent before making the API request.\u003c/p\u003e\n"],["\u003cp\u003eThe provided code demonstrates iterating over the API response to print and count the users retrieved from the account.\u003c/p\u003e\n"]]],["The code samples demonstrate listing all users for a Merchant Center account using the Merchant API in Java, PHP, and Python. Each sample authenticates via OAuth, creates a `UserServiceClient`, and defines the account parent. They then construct a `ListUsersRequest` and send it to the API. Finally, they iterate through the API's paged response, printing each user and the total count, handling any network or API exceptions.\n"],null,["# List users\n\nMerchant API code sample to list users. \n\n### Java\n\n // Copyright 2024 Google LLC\n //\n // Licensed under the Apache License, Version 2.0 (the \"License\");\n // you may not use this file except in compliance with the License.\n // You may obtain a copy of the License at\n //\n // https://www.apache.org/licenses/LICENSE-2.0\n //\n // Unless required by applicable law or agreed to in writing, software\n // distributed under the License is distributed on an \"AS IS\" BASIS,\n // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n // See the License for the specific language governing permissions and\n // limitations under the License.\n\n package shopping.merchant.samples.accounts.users.v1;\n import com.google.api.gax.core.FixedCredentialsProvider;\n import com.google.auth.oauth2.GoogleCredentials;\n import com.google.shopping.merchant.accounts.v1.ListUsersRequest;\n import com.google.shopping.merchant.accounts.v1.User;\n import com.google.shopping.merchant.accounts.v1.UserServiceClient;\n import com.google.shopping.merchant.accounts.v1.UserServiceClient.ListUsersPagedResponse;\n import com.google.shopping.merchant.accounts.v1.UserServiceSettings;\n import shopping.merchant.samples.utils.Authenticator;\n import shopping.merchant.samples.utils.Config;\n\n /** This class demonstrates how to list all the users for a given Merchant Center account. */\n public class ListUsersSample {\n\n private static String getParent(String accountId) {\n return String.format(\"accounts/%s\", accountId);\n }\n\n public static void listUsers(Config config) throws Exception {\n\n // Obtains OAuth token based on the user's configuration.\n GoogleCredentials credential = new Authenticator().authenticate();\n\n // Creates service settings using the credentials retrieved above.\n UserServiceSettings userServiceSettings =\n UserServiceSettings.newBuilder()\n .setCredentialsProvider(FixedCredentialsProvider.create(credential))\n .build();\n\n // Creates parent to identify the account from which to list all users.\n String parent = getParent(config.getAccountId().toString());\n\n // Calls the API and catches and prints any network failures/errors.\n try (UserServiceClient userServiceClient = UserServiceClient.create(userServiceSettings)) {\n\n // The parent has the format: accounts/{account}\n ListUsersRequest request = ListUsersRequest.newBuilder().setParent(parent).build();\n\n System.out.println(\"Sending list users request:\");\n ListUsersPagedResponse response = userServiceClient.listUsers(request);\n\n int count = 0;\n\n // Iterates over all rows in all pages and prints the user\n // in each row.\n // `response.iterateAll()` automatically uses the `nextPageToken` and recalls the\n // request to fetch all pages of data.\n for (User element : response.iterateAll()) {\n System.out.println(element);\n count++;\n }\n System.out.print(\"The following count of elements were returned: \");\n System.out.println(count);\n } catch (Exception e) {\n System.out.println(e);\n }\n }\n\n public static void main(String[] args) throws Exception {\n Config config = Config.load();\n\n listUsers(config);\n }\n } \n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/java/src/main/java/shopping/merchant/samples/accounts/users/v1/ListUsersSample.java\n\n### PHP\n\n \u003c?php\n /**\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n /**\n * Demonstrates how to list all the users for a given Merchant Center account.\n */\n\n require_once __DIR__ . '/../../../../vendor/autoload.php';\n require_once __DIR__ . '/../../../Authentication/Authentication.php';\n require_once __DIR__ . '/../../../Authentication/Config.php';\n use Google\\ApiCore\\ApiException;\n use Google\\Shopping\\Merchant\\Accounts\\V1\\ListUsersRequest;\n use Google\\Shopping\\Merchant\\Accounts\\V1\\Client\\UserServiceClient;\n\n\n /**\n * Lists users.\n *\n * @param array $config The configuration data.\n * @return void\n */\n function listUsers($config): void\n {\n // Gets the OAuth credentials to make the request.\n $credentials = Authentication::useServiceAccountOrTokenFile();\n\n // Creates options config containing credentials for the client to use.\n $options = ['credentials' =\u003e $credentials];\n\n // Creates a client.\n $userServiceClient = new UserServiceClient($options);\n\n // Creates parent to identify the account from which to list all users.\n $parent = sprintf(\"accounts/%s\", $config['accountId']);\n\n // Calls the API and catches and prints any network failures/errors.\n try {\n $request = new ListUsersRequest(['parent' =\u003e $parent]);\n\n print \"Sending list users request:\\n\";\n $response = $userServiceClient-\u003elistUsers($request);\n\n $count = 0;\n foreach ($response-\u003eiterateAllElements() as $element) {\n print_r($element);\n $count++;\n }\n print \"The following count of elements were returned: \";\n print $count . \"\\n\";\n } catch (ApiException $e) {\n print $e-\u003egetMessage();\n }\n }\n\n\n $config = Config::generateConfig();\n listUsers($config); \n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/php/examples/accounts/users/v1/ListUsersSample.php\n\n### Python\n\n # -*- coding: utf-8 -*-\n # Copyright 2024 Google LLC\n #\n # Licensed under the Apache License, Version 2.0 (the \"License\");\n # you may not use this file except in compliance with the License.\n # You may obtain a copy of the License at\n #\n # http://www.apache.org/licenses/LICENSE-2.0\n #\n # Unless required by applicable law or agreed to in writing, software\n # distributed under the License is distributed on an \"AS IS\" BASIS,\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \"\"\"A module to list users.\"\"\"\n\n\n from examples.authentication import configuration\n from examples.authentication import generate_user_credentials\n from google.shopping.merchant_accounts_v1 import ListUsersRequest\n from google.shopping.merchant_accounts_v1 import UserServiceClient\n\n _ACCOUNT = configuration.Configuration().read_merchant_info()\n\n\n def get_parent(account_id):\n return f\"accounts/{account_id}\"\n\n\n def list_users():\n \"\"\"Lists all the users for a given Merchant Center account.\"\"\"\n\n # Get OAuth credentials\n credentials = generate_user_credentials.main()\n\n # Create a UserServiceClient\n client = UserServiceClient(credentials=credentials)\n\n # Create parent string\n parent = get_parent(_ACCOUNT)\n\n # Create the request\n request = ListUsersRequest(parent=parent)\n\n try:\n print(\"Sending list users request:\")\n response = client.list_users(request=request)\n\n count = 0\n for element in response:\n print(element)\n count += 1\n\n print(\"The following count of elements were returned: \")\n print(count)\n\n except RuntimeError as e:\n print(e)\n\n\n if __name__ == \"__main__\":\n list_users()\n\n\n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/python/examples/accounts/users/v1/list_users_sample.py"]]