Вы можете использовать следующие методы для просмотра существующих users
под данным Client
.
Просмотр отдельного пользователя
Вы можете использовать метод buyers.clients.users.get
для получения информации о существующем ClientUser
.
В следующем примере показано, как можно получить отдельного ClientUser
с помощью метода get
.
Запрос
GET https://authorizedbuyersmarketplace.googleapis.com/v1/buyers/12345678/clients/873721984/users/4573638?alt=json Authorization: BearerACCESS_TOKEN Content-Type: application/json
Ответ
{ "name": "buyers/12345678/clients/873721984/users/4573638", "state": "INVITED", "email": "testemail87339346@test.com" }
/* Copyright 2022 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.Apis.AuthorizedBuyersMarketplace.v1;
using Google.Apis.AuthorizedBuyersMarketplace.v1.Data;
using Mono.Options;
using System;
using System.Collections.Generic;
namespace Google.Apis.AuthorizedBuyersMarketplace.Examples.v1.Buyers.Clients.Users
{
/// <summary>
/// Gets a single client user for the given buyer, client, and user IDs.
/// </summary>
public class GetClientUsers : ExampleBase
{
private AuthorizedBuyersMarketplaceService mkService;
/// <summary>
/// Constructor.
/// </summary>
public GetClientUsers()
{
mkService = Utilities.GetAuthorizedBuyersMarketplaceService();
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description
{
get => "This code example gets a specific user for a given client.";
}
/// <summary>
/// Parse specified arguments.
/// </summary>
protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
string[] requiredOptions = new string[] {"account_id", "client_id", "user_id"};
bool showHelp = false;
string accountId = null;
string clientId = null;
string userId = null;
OptionSet options = new OptionSet {
"Get a client user for a given buyer, client, and user ID.",
{
"h|help",
"Show help message and exit.",
h => showHelp = h != null
},
{
"a|account_id=",
("[Required] The resource ID of the buyers resource under which the parent " +
"client was created. This will be used to construct the name used as a " +
"path parameter for the users.get request."),
a => accountId = a
},
{
"c|client_id=",
("[Required] The resource ID of the buyers.clients resource under which the " +
"user was created. This will be used to construct the name used as a path " +
"parameter for the users.get request."),
c => clientId = c
},
{
"u|user_id=",
("[Required] The resource ID of the buyers.clients.users resource for which " +
"the user was created. This will be used to construct the name used as a " +
"path parameter for the users.get request."),
u => userId = u
},
};
List<string> extras = options.Parse(exampleArgs);
var parsedArgs = new Dictionary<string, object>();
// Show help message.
if (showHelp == true)
{
options.WriteOptionDescriptions(Console.Out);
Environment.Exit(0);
}
// Set optional arguments.
parsedArgs["account_id"] = accountId;
parsedArgs["client_id"] = clientId;
parsedArgs["user_id"] = userId;
// Validate that options were set correctly.
Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras);
return parsedArgs;
}
/// <summary>
/// Run the example.
/// </summary>
/// <param name="parsedArgs">Parsed arguments for the example.</param>
protected override void Run(Dictionary<string, object> parsedArgs)
{
string accountId = (string) parsedArgs["account_id"];
string clientId = (string) parsedArgs["client_id"];
string userId = (string) parsedArgs["user_id"];
string name = $"buyers/{accountId}/clients/{clientId}/users/{userId}";
BuyersResource.ClientsResource.UsersResource.GetRequest request =
mkService.Buyers.Clients.Users.Get(name);
ClientUser response = null;
Console.WriteLine("Getting client user with name: {0}", name);
try
{
response = request.Execute();
}
catch (Exception exception)
{
throw new ApplicationException(
$"Marketplace API returned error response:\n{exception.Message}");
}
Utilities.PrintClientUser(response);
}
}
}
/* * Copyright 2022 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 com.google.api.services.samples.authorizedbuyers.marketplace.v1.buyers.clients.users; import com.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplace; import com.google.api.services.authorizedbuyersmarketplace.v1.model.ClientUser; import com.google.api.services.samples.authorizedbuyers.marketplace.Utils; import java.io.IOException; import java.security.GeneralSecurityException; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; /** This sample illustrates how to get a client user for the given buyer, client, and user IDs. */ public class GetClientUsers { public static void execute(AuthorizedBuyersMarketplace marketplaceClient, Namespace parsedArgs) { Long accountId = parsedArgs.getLong("account_id"); Long clientId = parsedArgs.getLong("client_id"); Long clientUserId = parsedArgs.getLong("client_user_id"); String name = String.format("buyers/%d/clients/%d/users/%d", accountId, clientId, clientUserId); ClientUser clientUser = null; try { clientUser = marketplaceClient.buyers().clients().users().get(name).execute(); } catch (IOException ex) { System.out.printf("Marketplace API returned error response:%n%s", ex); System.exit(1); } System.out.printf("Found client user with name \"%s\":%n", name); Utils.printClientUser(clientUser); } public static void main(String[] args) { ArgumentParser parser = ArgumentParsers.newFor("GetClientUsers") .build() .defaultHelp(true) .description(("Get a client user for the given buyer, client, and client user IDs.")); parser .addArgument("-a", "--account_id") .help( "The resource ID of the buyers resource under which the parent client was created. " + "This will be used to construct the parent used as a path parameter for the " + "users.get request.") .required(true) .type(Long.class); parser .addArgument("-c", "--client_id") .help( "The resource ID of the buyers.clients resource for which the user was created. This" + " will be used to construct the name used as a path parameter for the users.get " + "request.") .required(true) .type(Long.class); parser .addArgument("-u", "--client_user_id") .help( "The resource ID of the buyers.clients.users resource that is being retrieved. This" + " will be used to construct the name used as a path parameter for the users.get " + "request.") .required(true) .type(Long.class); Namespace parsedArgs = null; try { parsedArgs = parser.parseArgs(args); } catch (ArgumentParserException ex) { parser.handleError(ex); System.exit(1); } AuthorizedBuyersMarketplace client = null; try { client = Utils.getMarketplaceClient(); } catch (IOException ex) { System.out.printf("Unable to create Marketplace API service:%n%s", ex); System.out.println("Did you specify a valid path to a service account key file?"); System.exit(1); } catch (GeneralSecurityException ex) { System.out.printf("Unable to establish secure HttpTransport:%n%s", ex); System.exit(1); } execute(client, parsedArgs); } }
#!/usr/bin/python # # Copyright 2021 Google Inc. All Rights Reserved. # # 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. """Gets a single client user for the given account, client, and user IDs.""" import argparse import os import pprint import sys sys.path.insert(0, os.path.abspath('../../../..')) from googleapiclient.errors import HttpError import util _CLIENT_USERS_NAME_TEMPLATE = 'buyers/%s/clients/%s/users/%s' DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE' DEFAULT_CLIENT_RESOURCE_ID = 'ENTER_CLIENT_RESOURCE_ID_HERE' DEFAULT_CLIENT_USER_RESOURCE_ID = 'ENTER_CLIENT_USER_RESOURCE_ID_HERE' def main(marketplace, args): client_user_name = _CLIENT_USERS_NAME_TEMPLATE % ( args.account_id, args.client_id, args.client_user_id) print(f'Get client user with name "{client_user_name}":') try: # Construct and execute the request. response = marketplace.buyers().clients().users().get( name=client_user_name).execute() except HttpError as e: print(e) sys.exit(1) pprint.pprint(response) if __name__ == '__main__': try: service = util.get_service(version='v1') except IOError as ex: print(f'Unable to create marketplace service - {ex}') print('Did you specify the key file in util.py?') sys.exit(1) parser = argparse.ArgumentParser( description=('Get a client for the given buyer account ID, client ID, ' 'and client user ID.')) # Required fields. parser.add_argument( '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID, help=('The resource ID of the buyers resource under which the ' 'client user was created. This will be used to construct the ' 'name used as a path parameter for the users.get request.')) parser.add_argument( '-c', '--client_id', default=DEFAULT_CLIENT_RESOURCE_ID, help=('The resource ID of the buyers.clients resource under which the ' 'client user was created. This will be used to construct the ' 'name used as a path parameter for the users.get request.')) parser.add_argument( '-u', '--client_user_id', default=DEFAULT_CLIENT_USER_RESOURCE_ID, help=('The resource ID of the buyers.clients.users resource for which ' 'the client user was created. This will be used to construct the ' 'name used as a path parameter for the users.get request.')) main(service, parser.parse_args())
Список нескольких пользователей
Вы можете использовать метод buyers.clients.users.list
для получения списка пользователей для данного Client
.
Например, вы можете использовать list
, чтобы проверить, имеет ли определенный адрес электронной почты доступ к пользовательскому интерфейсу торговой площадки авторизованных покупателей от имени определенного Client
.
В следующем примере показано, как можно получить список пользователей с помощью метода list
.
Запрос
GET https://authorizedbuyersmarketplace.googleapis.com/v1/buyers/12345678/clients/873721984/users?pageSize=3&alt=json Authorization: BearerACCESS_TOKEN Content-Type: application/json
Ответ
{ "clientUsers": [ { "name": "buyers/12345678/clients/873721984/users/4573638", "state": "INVITED", "email": "testemail87339346@test.com" }, { "name": "buyers/12345678/clients/873721984/users/4573641", "state": "INVITED", "email": "testemail88584947@test.com" }, { "name": "buyers/12345678/clients/873721984/users/4573644", "state": "INACTIVE", "email": "jessie@luxurymarscruises.mars" } ], "nextPageToken": "CAQQ4tWk59Td9gIY4tWk59Td9gI=" }
/* Copyright 2022 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.Apis.AuthorizedBuyersMarketplace.v1;
using Google.Apis.AuthorizedBuyersMarketplace.v1.Data;
using Mono.Options;
using System;
using System.Collections.Generic;
namespace Google.Apis.AuthorizedBuyersMarketplace.Examples.v1.Buyers.Clients.Users
{
/// <summary>
/// Lists client users for a given client.
/// </summary>
public class ListClientUsers : ExampleBase
{
private AuthorizedBuyersMarketplaceService mkService;
/// <summary>
/// Constructor.
/// </summary>
public ListClientUsers()
{
mkService = Utilities.GetAuthorizedBuyersMarketplaceService();
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description
{
get => "This code example lists all client users for a given client.";
}
/// <summary>
/// Parse specified arguments.
/// </summary>
protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
string[] requiredOptions = new string[] {"account_id", "client_id"};
bool showHelp = false;
string accountId = null;
string clientId = null;
int? pageSize = null;
OptionSet options = new OptionSet {
"List clients for the given buyer account.",
{
"h|help",
"Show help message and exit.",
h => showHelp = h != null
},
{
"a|account_id=",
("[Required] The resource ID of the buyers resource under which the " +
"clients were created. This will be used to construct the parent used as " +
"a path parameter for the users.list request."),
a => accountId = a
},
{
"c|client_id=",
("[Required] The resource ID of the buyers.clients resource under which the " +
"users were created. This will be used to construct the name used as a " +
"path parameter for the users.list request."),
c => clientId = c
},
{
"p|page_size=",
("The number of rows to return per page. The server may return fewer rows " +
"than specified."),
(int p) => pageSize = p
},
};
List<string> extras = options.Parse(exampleArgs);
var parsedArgs = new Dictionary<string, object>();
// Show help message.
if (showHelp == true)
{
options.WriteOptionDescriptions(Console.Out);
Environment.Exit(0);
}
// Set arguments.
parsedArgs["account_id"] = accountId;
parsedArgs["client_id"] = clientId;
parsedArgs["pageSize"] = pageSize ?? Utilities.MAX_PAGE_SIZE;
// Validate that options were set correctly.
Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras);
return parsedArgs;
}
/// <summary>
/// Run the example.
/// </summary>
/// <param name="parsedArgs">Parsed arguments for the example.</param>
protected override void Run(Dictionary<string, object> parsedArgs)
{
string accountId = (string) parsedArgs["account_id"];
string clientId = (string) parsedArgs["client_id"];
string parent = $"buyers/{accountId}/clients/{clientId}";
string pageToken = null;
Console.WriteLine(@"Listing client users for client with name: ""{0}""", parent);
do
{
BuyersResource.ClientsResource.UsersResource.ListRequest request =
mkService.Buyers.Clients.Users.List(parent);
request.PageSize = (int) parsedArgs["pageSize"];
request.PageToken = pageToken;
ListClientUsersResponse page = null;
try
{
page = request.Execute();
}
catch (Exception exception)
{
throw new ApplicationException(
$"Marketplace API returned error response:\n{exception.Message}");
}
var users = page.ClientUsers;
pageToken = page.NextPageToken;
if (users == null)
{
Console.WriteLine("No client users found for the given client.");
}
else
{
foreach (ClientUser user in users)
{
Utilities.PrintClientUser(user);
}
}
}
while(pageToken != null);
}
}
}
/* * Copyright 2022 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 com.google.api.services.samples.authorizedbuyers.marketplace.v1.buyers.clients.users; import com.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplace; import com.google.api.services.authorizedbuyersmarketplace.v1.model.ClientUser; import com.google.api.services.authorizedbuyersmarketplace.v1.model.ListClientUsersResponse; import com.google.api.services.samples.authorizedbuyers.marketplace.Utils; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.List; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; /** This sample illustrates how to list client users for a given client. */ public class ListClientUsers { public static void execute(AuthorizedBuyersMarketplace marketplaceClient, Namespace parsedArgs) { Long accountId = parsedArgs.getLong("account_id"); Long clientId = parsedArgs.getLong("client_id"); Integer pageSize = parsedArgs.getInt("page_size"); String parentClientName = String.format("buyers/%d/clients/%d", accountId, clientId); String pageToken = null; System.out.printf("Found client users for client with name \"%s\":%n", parentClientName); do { List<ClientUser> clientUsers = null; try { ListClientUsersResponse response = marketplaceClient .buyers() .clients() .users() .list(parentClientName) .setPageSize(pageSize) .setPageToken(pageToken) .execute(); clientUsers = response.getClientUsers(); pageToken = response.getNextPageToken(); } catch (IOException ex) { System.out.printf("Marketplace API returned error response:%n%s", ex); System.exit(1); } if (clientUsers == null) { System.out.println("No client users found."); } else { for (ClientUser clientUser : clientUsers) { Utils.printClientUser(clientUser); } } } while (pageToken != null); } public static void main(String[] args) { ArgumentParser parser = ArgumentParsers.newFor("ListClientUsers") .build() .defaultHelp(true) .description(("Lists client users associated with the given buyer account.")); parser .addArgument("-a", "--account_id") .help( "The resource ID of the buyers resource under which the parent client was created. " + "This will be used to construct the parent used as a path parameter for the " + "users.list request.") .required(true) .type(Long.class); parser .addArgument("-c", "--client_id") .help( "The resource ID of the buyers.clients resource we are retrieving client users on" + " behalf of. This will be used to construct the parent used as a path parameter" + " for the users.list request.") .required(true) .type(Long.class); parser .addArgument("-p", "--page_size") .help( "The number of rows to return per page. The server may return fewer rows than " + "specified.") .setDefault(Utils.getMaximumPageSize()) .type(Integer.class); Namespace parsedArgs = null; try { parsedArgs = parser.parseArgs(args); } catch (ArgumentParserException ex) { parser.handleError(ex); System.exit(1); } AuthorizedBuyersMarketplace client = null; try { client = Utils.getMarketplaceClient(); } catch (IOException ex) { System.out.printf("Unable to create Marketplace API service:%n%s", ex); System.out.println("Did you specify a valid path to a service account key file?"); System.exit(1); } catch (GeneralSecurityException ex) { System.out.printf("Unable to establish secure HttpTransport:%n%s", ex); System.exit(1); } execute(client, parsedArgs); } }
#!/usr/bin/python # # Copyright 2021 Google Inc. All Rights Reserved. # # 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. """This example lists client users for the specified buyer.""" import argparse import os import pprint import sys sys.path.insert(0, os.path.abspath('../../../..')) from googleapiclient.errors import HttpError import util _CLIENT_NAME_TEMPLATE = 'buyers/%s/clients/%s' DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE' DEFAULT_CLIENT_RESOURCE_ID = 'ENTER_CLIENT_RESOURCE_ID_HERE' def main(marketplace, args): client_name = _CLIENT_NAME_TEMPLATE % (args.account_id, args.client_id) page_size = args.page_size page_token = None more_pages = True print(f'Listing client users for client with name "{client_name}".') while more_pages: try: # Construct and execute the request. response = marketplace.buyers().clients().users().list( parent=client_name, pageToken=page_token, pageSize=page_size).execute() except HttpError as e: print(e) sys.exit(1) pprint.pprint(response) page_token = response.get('nextPageToken') more_pages = bool(page_token) if __name__ == '__main__': try: service = util.get_service(version='v1') except IOError as ex: print(f'Unable to create marketplace service - {ex}') print('Did you specify the key file in util.py?') sys.exit(1) parser = argparse.ArgumentParser( description=('Lists client users for the given buyer account and client ' 'IDS.')) # Required fields. parser.add_argument( '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID, help=('The resource ID of the buyers resource under which the clients ' 'were created. This will be used to construct the parent used as a ' 'path parameter for the users.list request.')) parser.add_argument( '-c', '--client_id', default=DEFAULT_BUYER_RESOURCE_ID, help=('The resource ID of the clients resource under which the client ' 'users were created. This will be used to construct the parent ' 'used as a path parameter for the users.list request.')) # Optional fields. parser.add_argument( '-p', '--page_size', default=util.MAX_PAGE_SIZE, help=('The number of rows to return per page. The server may return ' 'fewer rows than specified.')) main(service, parser.parse_args())