There are currently three versions of Authorized Buyer APIs:
- Real-time Bidding API (latest)
- Ad Exchange Buyer API II
- Ad Exchange Buyer API (deprecated)
These APIs allow your apps to interact with Authorized Buyers to:
- Access real-time bidding account information
- Submit and manage creatives undergoing review
- Retrieve performance reports
- Retrieve real-time bidding troubleshooting metrics
- Manage user lists
- Manage pretargeting configurations
- Configure client access for Marketplace
- Discover and manage proposals for deals in Marketplace
If you're unfamiliar with Authorized Buyers concepts, visit the Authorized Buyers Help Center and experiment with the UI.
Prepare for authorization
Complete the following steps to prepare for authentication using OAuth 2.0. The API supports many types of credentials; for this example we'll use a service account.
- Go to the Google API Console Enabled APIs page.
- From the project drop-down, select a project or create a new one.
- In the list of Enabled APIs, make sure Ad Exchange Buyer API is listed. If it's not listed, click the Google APIs tab, search for and select the Ad Exchange Buyer API, and click Enable API.
- Next, in the sidebar on the left select Credentials.
- Select the Create credentials drop-down, then choose Service account key.
- In the Service account drop-down, choose New service account.
- Enter a Name for the service account. The service account ID is automatically generated from the name and project name.
- Note the service account ID: you'll need it to grant access to the new service account in the Authorized Buyers UI in step 11.
- Choose a Key type, either the recommended JSON file, or P12 if backward compatibility with code using P12 format is needed.
- Click Create. The JSON or P12 file with the account's public/private key pair is saved to your Downloads folder. Keep the generated JSON or P12 file in a safe place.
- You must grant the service account access in the Authorized Buyers UI for it to work. Select Settings > Account Settings, then choose User Management > Account Users, and click +Service Account. Enter the service account ID you noted above in step 8. This creates a new user with the service account role.
OAuth scopes
When stepping through the OAuth 2.0 authorization flow, your application can specify scopes to indicate that it intends to access certain features in Google APIs for a given Google account. In order to access any of the Authorized Buyers APIs on behalf of an Authorized Buyers account, you must specify the scope associated with the API you intend to use.
Ad Exchange Buyer API scopes
The following are scopes used to access the Ad Exchange Buyer API APIs:
Scope | Meaning |
---|---|
https://www.googleapis.com/auth/adexchange.buyer |
Read/write access. |
Real-time Bidding API scopes
The following are scopes used to access the Real-time Bidding API:
Scope | Meaning |
---|---|
https://www.googleapis.com/auth/realtime-bidding |
Read/write access. |
Make an API call with Real-time Bidding API
The tabs below provide quickstarts for coding in each of the languages for which there is a client library.
Java
Here is a basic example that shows how to use the Real-time Bidding API with Java.
- Create a Maven project
Open the pom.xml and add these dependencies:
<dependencies> <dependency> <groupId>com.google.api-client</groupId> <artifactId>google-api-client</artifactId> <version>1.31.1</version> </dependency> <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-pubsub</artifactId> <version>v1-rev452-1.25.0</version> </dependency> <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-realtimebidding</artifactId> <version>v1-rev20210311-1.31.0</version> </dependency> <dependency> <groupId>com.google.auth</groupId> <artifactId>google-auth-library-oauth2-http</artifactId> <version>0.22.2</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.6</version> </dependency> <dependency> <groupId>com.google.http-client</groupId> <artifactId>google-http-client-jackson2</artifactId> <version>1.38.0</version> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.10.6</version> </dependency> <dependency> <groupId>net.sourceforge.argparse4j</groupId> <artifactId>argparse4j</artifactId> <version>0.8.1</version> </dependency> </dependencies>
- Set up your credentials
All calls to the API require authentication; create a
Credential
using the Service Account JSON key File discussed above.GoogleCredentials credentials = null; try (FileInputStream serviceAccountStream = new FileInputStream((JSON_FILE))) { Set<String> scopes = new HashSet<>(RealTimeBiddingScopes.all()); credentials = ServiceAccountCredentials .fromStream(serviceAccountStream) .createScoped(scopes); } catch(IOException ex) { System.out.println("Can't complete authorization step. Did you specify a JSON key file?"); System.out.println(ex); System.exit(1); }
- Construct a client for Real-time Bidding API
You can then create your Real-time Bidding API client using the Builder pattern:
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // Use the credentials to create a client for the API service. RealTimeBidding realtimeBidding = new RealTimeBidding.Builder(httpTransport, jsonFactory, requestInitializer).setApplicationName(APPLICATION_NAME) .build();
- Perform an operation
After you've instantiated a client to connect to the API, you can perform an operation. The following code returns all of a given Buyer's creatives.
List<Creative> creatives = realtimeBidding.buyers().creatives() .list(BUYER_NAME) .setView("FULL") .execute().getCreatives(); if (creatives != null && creatives.size() > 0) { System.out.printf("Listing of creatives associated with buyer '%s'%n", BUYER_NAME); for (Creative creative : creatives) { System.out.printf("* Creative name: %s\n", creative.getName()); } } else { System.out.printf("No creatives were found that were associated with buyer '%s'%n.", BUYER_NAME); }
For more detailed information about using the Real-time Bidding API with Java, refer to the README file in the Real-time Bidding API examples.
Python
Here is a basic example that shows how to use the Real-time Bidding API with Python.
- Download and install the Google API Python Client
Example using pip:
$ pip install --upgrade google-api-python-client
- Set up your credentials
All calls to the API require authentication; instantiate a
service_account.Credentials
instance using the Service Account JSON key file discussed above.credentials = service_account.Credentials.from_service_account_file( KEY_FILE, scopes=[SCOPE])
- Construct a client for the Real-time Bidding API
You can then create your Real-time Bidding API client using the authorized
service_account.Credentials
instance:realtimebidding = build('realtimebidding', VERSION, credentials=credentials)
- Perform an operation
After you've instantiated a client to connect to the API, you can perform an operation. The following code returns all of a given Buyer's creatives.
request = realtimebidding.buyers().creatives().list(parent=BUYER_NAME) pprint.pprint(request.execute())
For more detailed information about using the Ad Exchange Buyer API with Python, refer to the README file in the Real-time Bidding API examples.
PHP
Here is a basic example that shows how to use the Real-time Bidding API with PHP.
- Set up dependencies
If you haven't installed it yet, download and install Composer, then create a composer.json with contents such as the following:
{ "description": "Authorized Buyers Real-Time Bidding API PHP Samples", "require": { "php": ">=7.2", "google/apiclient": "^2.0" }, "require-dev": { "squizlabs/php_codesniffer": "3.*" }, "type": "project", "homepage": "https://github.com/googleads/authorized-buyers-rtb-api-samples/tree/master/php", "license": "Apache-2.0", "authors": [ { "name": "Google", "homepage": "https://github.com/googleads/authorized-buyers-rtb-api-samples/graphs/contributors" } ] }
Finally, run the following to install dependency libraries:
composer install
- Set up a client
Create a
Google_Client
, and use it to instantiateGoogle_Service_RealTimeBidding
.$client = new Google_Client(); $client->setApplicationName('Authorized Buyers Real-time Bidding API PHP Samples'); $service = new Google_Service_RealTimeBidding($client);
- Set up your credentials
All calls to the API require a valid access token. Configure your client to step through the OAuth 2.0 flow.
$client->setAuthConfig($keyFileLocation); $client->addScope('https://www.googleapis.com/auth/realtime-bidding'); if ($client->isAccessTokenExpired()) { $client->refreshTokenWithAssertion(); }
- Perform an operation
After you've instantiated a client to connect to the API, and configured OAuth 2.0, you can use it to make an API call. The following code returns all of a given Buyer's creatives:
$result = $service->buyers_creatives->listBuyersCreatives($buyerName, $queryParams); print "Creatives associated with buyer account\n"; if (empty($result['creatives'])) { print "No creatives found\n"; return; } else { foreach ($result['creatives'] as $creative) { print_r($creative); } }
For more detailed information about using the Ad Exchange Buyer API with PHP, refer to the README file in the Real-time Bidding API examples.
.NET
Here is a basic example that shows how to use the Real-time Bidding API with C#.
- Create a new project
Open Visual Studio Code and create a new project.
- Add required library references to your project
In your project's *.csproj file, add a
PackageReference
entry forGoogle.Apis
,Google.Apis.Auth
,Google.Apis.Core
,Google.Apis.Oauth2.v2
, andGoogle.Apis.RealTimeBidding.v1
. As an example, this might look like the following:<ItemGroup> <PackageReference Include="Google.Apis" Version="1.50.0" /> <PackageReference Include="Google.Apis.Auth" Version="1.50.0" /> <PackageReference Include="Google.Apis.Core" Version="1.50.0" /> <PackageReference Include="Google.Apis.Oauth2.v2" Version="1.50.0.1869" /> <PackageReference Include="Google.Apis.PubSub.v1" Version="1.50.0.2252" /> <PackageReference Include="Google.Apis.RealTimeBidding.v1" Version="1.50.0.2261" /> <PackageReference Include="log4net" Version="2.0.12" /> <PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.4" /> <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference> <PackageReference Include="Mono.Options" Version="6.6.0.161" /> <PackageReference Include="Newtonsoft.Json" Version="12.0.3" /> </ItemGroup>
You can find more information about these dependencies at: https://www.nuget.org/packages/.
- Set up your credentials
All calls to the API require authentication; create a
Credential
using the Service Account email and JSON File discussed above.var credentialParameters = NewtonsoftJsonSerializer.Instance .Deserialize<JsonCredentialParameters>( System.IO.File.ReadAllText(ServiceKeyFilePath)); // Create the credentials. var credentialInitializer = new ServiceAccountCredential.Initializer( credentialParameters.ClientEmail) { Scopes = new[] { RealTimeBiddingService.Scope.RealtimeBidding } }.FromPrivateKey(credentialParameters.PrivateKey); var oAuth2Credentials = new ServiceAccountCredential(credentialInitializer);
- Construct a client for the Real-time Bidding API
You can then create your
RealTimeBiddingService
:var serviceInitializer = new BaseClientService.Initializer { HttpClientInitializer = oAuth2Credentials, ApplicationName = "FirstAPICall" }; var realtimebidding = new RealTimeBiddingService(serviceInitializer);
- Perform an operation
After you've instantiated a client to connect to the API, you can perform an operation. The following code lists creatives for a specified Authorized Buyers buyer account associated with your credentials.
BuyersResource.CreativesResource.ListRequest request = realtimebidding.Buyers.Creatives.List(buyerName); request.View = BuyersResource.CreativesResource.ListRequest.ViewEnum.FULL; IList<Creative> creatives = request.Execute().Creatives; foreach (Creative creative in creatives) { Console.WriteLine("* Creative name: {0}", creative.Name); }
For more detailed information about using the Real-time Bidding API with C#, refer to the README file in the Real-time Bidding API examples.
Ruby
Here is a basic example that shows how to use the Real-time Bidding API with Ruby.
- Download and install the Google API Ruby Client
If you haven't installed it yet, download and install Bundler, then create a Gemfile with contents such as the following:
source "https://rubygems.org" ruby "2.6.0" gem 'google-apis-pubsub_v1', '0.3.0' gem 'google-apis-realtimebidding_v1', '~> 0.3.0'
Finally, run the following to install dependency libraries:
bundle
- Set up your credentials
All calls to the API require authentication; create credentials using the Service Account email and JSON file discussed above.
# Create credentials using the JSON key file. auth_options = { :json_key_io => File.open(KEY_FILE, "r"), :scope => 'https://www.googleapis.com/auth/realtime-bidding' } oauth_credentials = Google::Auth::ServiceAccountCredentials.make_creds( options=auth_options )
- Construct a client for the AdExchangeBuyer
You can then create your authorized AdExchange Buyer client using the credentials:
# Create the service and set credentials realtimebidding = ( Google::Apis::RealtimebiddingV1::RealtimeBiddingService.new ) realtimebidding.authorization = oauth_credentials realtimebidding.authorization.fetch_access_token!
- Perform an operation
After you've instantiated a client to connect to the API, you can perform an operation. The following code returns all of a given Buyer's creatives.
# Call the buyers.creatives.list method to get list of creatives for given buyer. creatives_list = realtimebidding.list_buyer_creatives( BUYER_NAME, view: 'FULL') if creatives_list.creatives.any? puts "Found the following creatives for buyer '%s':" % BUYER_NAME creatives_list.creatives.each do |creative| puts "* Creative name: #{creative.name}" end else puts "No creatives were found that were associated with buyer '%s'" % BUYER_NAME end
For more detailed information about using the Real-time Bidding API with Ruby, refer to the README file in the Real-time Bidding API examples.
Make an API call with Ad Exchange Buyer API (deprecated)
The tabs below provide quickstarts for coding in each of the languages for which there is a client library.
Java
Here is a basic example that shows how to use the Ad Exchange Buyer API with Java.
- Create an Eclipse maven project
Open the pom.xml and add these dependencies:
<dependencies> <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-adexchangebuyer</artifactId> <version>RELEASE</version> </dependency> <dependency> <groupId>com.google.http-client</groupId> <artifactId>google-http-client-jackson2</artifactId> <version>RELEASE</version> </dependency> </dependencies>
- Set up your credentials
All calls to the API require authentication; create a
Credential
using the Service Account email and P12 File discussed above.Credential oAuth2Credential = new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(jsonFactory) .setServiceAccountId(SERVICE_ACCOUNT_EMAIL) .setServiceAccountScopes(AdExchangeBuyerScopes.all()) .setServiceAccountPrivateKeyFromP12File(P12_FILE) .build();
- Construct a client for the AdExchangeBuyer
You can then create your
AdExchangeBuyer
using the Builder pattern:AdExchangeBuyer buyerService = new AdExchangeBuyer.Builder(httpTransport, jsonFactory, oAuth2Credential).setApplicationName(APPLICATION_NAME) .build();
- Perform an operation
After you've instantiated a client to connect to the API, you can perform an operation. The following code returns all of the Buyer
Account
associated with your authenticated account.List<Account> allAccounts = buyerService.accounts().list() .execute().getItems(); if (allAccounts != null && allAccounts.size() > 0) { System.out.printf("Listing of user associated accounts%n"); for (Account account : allAccounts) { System.out.printf("Account id: %d%n", account.getId()); } }
For more detailed information about using the Ad Exchange Buyer API with Java, refer to the README file in the Ad Exchange Buyer API examples.
Python
Here is a basic example that shows how to use the Ad Exchange Buyer API with Python.
- Download and install the Google API Python Client
Example using pip:
$ pip install --upgrade google-api-python-client
- Set up your credentials
All calls to the API require authentication; create credentials using the Service Account email and P12 File discussed above. Use them to authorize a
Http
object.credentials = service_account.Credentials.from_service_account_file( KEY_FILE, scopes=[SCOPE])
- Construct a client for the AdExchangeBuyer
You can then create your AdExchange Buyer client using the authorized
Http
object:buyer_service = build('adexchangebuyer', VERSION, credentials=credentials)
- Perform an operation
After you've instantiated a client to connect to the API, you can perform an operation. The following code returns all of the Buyer
Account
associated with your authenticated account.request = buyer_service.accounts().list()
For more detailed information about using the Ad Exchange Buyer API with Python, refer to the README file in the Ad Exchange Buyer API examples.
PHP
Here is a basic example that shows how to use the Ad Exchange Buyer API with PHP.
- Set up dependencies
Download and install google-api-php-client.
- Set up a client
Create a
Google_Client
object.$client = new Google_Client(); $client->setApplicationName( 'Authorized Buyers Ad Exchange Buyer API PHP Samples');
- Set up your credentials
All calls to the API require a valid access token. Obtain one by providing your pre-configured key.
$service = new Google_Service_AdExchangeBuyer($client); if (isset($_SESSION['service_token'])) { $client->setAccessToken($_SESSION['service_token']); } $client->setAuthConfig($keyFileLocation); $client->addScope('https://www.googleapis.com/auth/adexchange.buyer'); if ($client->isAccessTokenExpired()) { $client->refreshTokenWithAssertion(); } $_SESSION['service_token'] = $client->getAccessToken();
- Construct a client for the AdExchangeBuyer
You can then create your AdExchange Buyer client using the authorized
Google_Client
object:$service = new Google_Service_AdExchangeBuyer($client);
- Perform an operation
After you've instantiated a client to connect to the API, you can perform an operation. The following code returns all of the Buyer
Account
associated with your authenticated account.$result = $service->accounts->listAccounts(); print '<h2>Listing of user associated accounts</h2>'; if (empty($result['items'])) { print '<p>No accounts found</p>'; return; } else { foreach ($result['items'] as $account) { printf('<pre>'); print_r($account); printf('</pre>'); } }
For more detailed information about using the Ad Exchange Buyer API with PHP, refer to the README file in the Ad Exchange Buyer API examples.
.NET
Here is a basic example that shows how to use the Ad Exchange Buyer API with C#.
- Create a new project
Open Visual Studio and create a new project (i.e., Console Application).
- Add required library references to your project
Either:
- Use NuGet to add the latest version of
Google.Apis.AdExchangeBuyer
and its dependencies. - Download it manually and add a reference to the DLLs. Details on the library can be found here.
- Use NuGet to add the latest version of
- Set up your credentials
All calls to the API require authentication; create a
Credential
using the Service Account email and JSON File discussed above.ServiceAccountCredential oAuth2Credentials = new ServiceAccountCredential( new ServiceAccountCredential.Initializer( credentialParameters.ClientEmail) { Scopes = new[] { AdExchangeBuyerService.Scope.AdexchangeBuyer } }.FromPrivateKey(credentialParameters.PrivateKey));
- Construct a client for the AdExchangeBuyer
You can then create your
AdExchangeBuyerService
:AdExchangeBuyerService buyerService = new AdExchangeBuyerService( new BaseClientService.Initializer { HttpClientInitializer = oAuth2Credentials, ApplicationName = "FirstAPICall" });
- Perform an operation
After you've instantiated a client to connect to the API, you can perform an operation. The following code returns all of the Buyer
Account
associated with your authenticated account.AccountsList allAccounts = buyerService.Accounts.List().Execute(); foreach (Account account in allAccounts.Items) { Console.WriteLine("Account id: {0}", account.Id); }
For more detailed information about using the Ad Exchange Buyer API with C#, refer to the README file in the Ad Exchange Buyer API examples.
Ruby
Here is a basic example that shows how to use the Ad Exchange Buyer API with Ruby.
- Download and install the Google API Ruby Client
Example using gem:
$ gem install google-api-client $ gem update -y google-api-client
- Set up your credentials
All calls to the API require authentication; create credentials using the Service Account email and JSON file discussed above.
# Create credentials using the JSON key file. auth_options = { :json_key_io => File.open(KEY_FILE, "r"), :scope => "https://www.googleapis.com/auth/adexchange.buyer" } oauth_credentials = Google::Auth::ServiceAccountCredentials.make_creds( options=auth_options )
- Construct a client for the AdExchangeBuyer
You can then create your authorized AdExchange Buyer client using the credentials:
# Create the service and set credentials ad_exchange_buyer = ( Google::Apis::AdexchangebuyerV1_4::AdExchangeBuyerService.new ) ad_exchange_buyer.authorization = oauth_credentials ad_exchange_buyer.authorization.fetch_access_token!
- Perform an operation
After you've instantiated a client to connect to the API, you can perform an operation. The following code returns all of the Buyer
Account
associated with your authenticated account.# Call the Accounts resource on the service to retrieve a list of # Accounts for the service account. accounts_list = ad_exchange_buyer.list_accounts() if accounts_list.items.any? puts 'Found the following Authorized Buyers Accounts:' accounts_list.items.each do |account| puts 'AccountID: %d' % account.id puts "\tCookie matching nid: %s" % account.cookie_matching_nid puts "\tCookie matching URL: %s" % account.cookie_matching_url puts "\tMaximum active creatives: %d" % account.maximum_active_creatives puts "\tMaximum total QPS: %d" % account.maximum_total_qps puts "\tNumber active creatives: %d" % account.number_active_creatives unless account.bidder_location.nil? puts "\tBidder Locations:" account.bidder_location.each do |bidder_location| puts "\t\tURL: %s" % bidder_location.url puts "\t\t\tRegion: %s" % bidder_location.region puts "\t\t\tBid Protocol: %s" % bidder_location.bid_protocol puts "\t\t\tMaximum QPS: %s" % bidder_location.maximum_qps end end end else puts 'No Authorized Buyers Accounts were found.' end
For more detailed information about using the Ad Exchange Buyer API with Ruby, refer to the README file in the Ad Exchange Buyer API examples.
Make an API call with Ad Exchange Buyer API II
The tabs below provide quickstarts for coding in each of the languages for which there is a client library.
Java
/* * Copyright (c) 2016 Google Inc. * * 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. */ package com.google.api.services.samples.adexchangebuyer.cmdline.v2_x; import com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient; import com.google.api.services.adexchangebuyer2.v2beta1.AdExchangeBuyerII; import com.google.api.services.adexchangebuyer2.v2beta1.model.Client; import com.google.api.services.samples.adexchangebuyer.cmdline.BaseSample; import java.io.IOException; import java.util.List; /** * This sample illustrates how to retrieve all client buyers associated with a given account. * * See the <a href="Client Access Guide">https://developers.google.com/authorized-buyers/apis/guides/v2/client-access#clients</a> * for more details on the usage of this resource. */ public class GetAllClientBuyers extends BaseSample { @Override public ClientType getClientType() { return BaseSample.ClientType.ADEXCHANGEBUYERII; } @Override public String getName() { return "Get All Client Buyers"; } @Override public String getDescription() { return "Lists Client Buyers associated with the given Account."; } @Override public void execute(AbstractGoogleJsonClient client) throws IOException { AdExchangeBuyerII adXClient = (AdExchangeBuyerII) client; long accountId = getIntInput("AccountId", "Enter the Account ID"); List<Client> allClients = adXClient.accounts().clients().list(accountId).execute().getClients(); if (allClients != null && allClients.size() > 0) { System.out.println("========================================"); System.out.printf("Listing of Client Buyers associated with AdX Account \"%s\"%n", accountId); System.out.println("========================================"); for (Client clientBuyer : allClients) { System.out.printf("Client Account ID: %s%n", clientBuyer.getClientAccountId()); System.out.printf("\tClient Name: %s%n", clientBuyer.getClientName()); System.out.printf("\tEntity ID: %s%n", clientBuyer.getEntityId()); System.out.printf("\tEntity Name: %s%n", clientBuyer.getEntityName()); System.out.printf("\tEntity Type: %s%n", clientBuyer.getEntityType()); System.out.printf("\tRole: %s%n", clientBuyer.getRole()); System.out.printf("\tStatus: %s%n", clientBuyer.getStatus()); } } else { System.out.println("No Client Buyers were found associated to this Account."); } } }
Python
#!/usr/bin/python # # Copyright 2016 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 the client buyers for a given account.""" import argparse import pprint import os import sys sys.path.insert(0, os.path.abspath('..')) from googleapiclient.errors import HttpError import samples_util DEFAULT_ACCOUNT_ID = 'ENTER_ACCOUNT_ID_HERE' def main(ad_exchange_buyer, account_id): try: # Construct and execute the request. clients = ad_exchange_buyer.accounts().clients().list( accountId=account_id).execute() print(f'Client buyers for account ID: "{account_id}"') pprint.pprint(clients) except HttpError as e: print(e) if __name__ == '__main__': parser = argparse.ArgumentParser( description='Lists client buyers for a given Authorized Buyers account.') parser.add_argument( '-a', '--account_id', default=DEFAULT_ACCOUNT_ID, type=int, help='The integer id of the Authorized Buyers account.') args = parser.parse_args() try: service = samples_util.GetService('v2beta1') except IOError as ex: print(f'Unable to create adexchangebuyer service - {ex}') print('Did you specify the key file in samples_util.py?') sys.exit(1) main(service, args.account_id)
PHP
<?php /** * Copyright 2016 Google Inc. * * 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. */ require_once __DIR__ . '/../../BaseExample.php'; /** * This example illustrates how to retrieve all buyer clients associated * with a given account. */ class ListClientBuyers extends BaseExample { /** * @see BaseExample::getInputParameters() */ protected function getInputParameters() { return [ [ 'name' => 'accountId', 'display' => 'Account ID', 'required' => true ] ]; } /** * @see BaseExample::run() */ public function run() { $values = $this->formValues; $result = $this->service->accounts_clients->listAccountsClients( $values['accountId']); print '<h2>Listing buyer clients</h2>'; if (empty($result['clients'])) { print '<p>No buyer clients found</p>'; return; } else { foreach ($result['clients'] as $clients) { $this->printResult($clients); } } } /** * @see BaseExample::getClientType() */ public function getClientType() { return ClientType::AdExchangeBuyerII; } /** * @see BaseExample::getName() */ public function getName() { return 'Client Access: List Client Buyers'; } }
.NET
/* Copyright 2016, 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. */ using Google.Apis.AdExchangeBuyerII.v2beta1; using Google.Apis.AdExchangeBuyerII.v2beta1.Data; using Google.Apis.Services; using System; namespace Google.Apis.AdExchangeBuyer.Examples.v2_x { /// <summary> /// Retrieves the authenticated user's list of client buyers for the given account ID. /// </summary> public class ListClientBuyers : 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) { AdExchangeBuyerIIService service = Utilities.GetV2Service(); ExampleBase example = new ListClientBuyers(); Console.WriteLine(example.Description); example.Run(service); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example lists all client buyers for a given account ID."; } } /// <summary> /// Runs the code example. /// </summary> /// <param name="service">An authenticated AdExchangeBuyerIIService</param> public override void Run(BaseClientService service) { AdExchangeBuyerIIService adXService = (AdExchangeBuyerIIService)service; long accountId = long.Parse("INSERT ACCOUNT ID HERE"); ListClientsResponse response = adXService.Accounts.Clients.List(accountId).Execute(); Console.WriteLine("========================================\n"); Console.WriteLine("Listing of client buyers associated with Authorized Buyers " + "Account \"{0}\"", accountId); Console.WriteLine("========================================\n"); if (response.Clients.Count == 0) { Console.WriteLine("No client buyers found."); } else { foreach (Client clientBuyer in response.Clients) { Console.WriteLine("Client Account ID: {0}", clientBuyer.ClientAccountId); Console.WriteLine("\tClient Name: {0}", clientBuyer.ClientName); Console.WriteLine("\tEntity ID: {0}", clientBuyer.EntityId); Console.WriteLine("\tEntity Name: {0}", clientBuyer.EntityName); Console.WriteLine("\tEntity Type: {0}", clientBuyer.EntityType); Console.WriteLine("\tRole: {0}", clientBuyer.Role); Console.WriteLine("\tStatus: {0}", clientBuyer.Status); } } } public override ClientType getClientType() { return ClientType.ADEXCHANGEBUYERII; } } }
Ruby
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright:: Copyright 2016, Google Inc. All Rights Reserved. # # License:: 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. # # Lists the client buyers for a given account. # # To get Account IDs, run list_accounts.rb. # # Tags: Accounts.Clients.list require 'optparse' require_relative '../samples_util' def list_client_buyers(ad_exchange_buyer, account_id, page_size) begin client_buyers = ad_exchange_buyer.list_account_clients( account_id, page_size: page_size ) if !client_buyers.clients.nil? puts 'Found the following client buyers for account ID %s:' % account_id client_buyers.clients.each do |client_buyer| puts '* Client account ID: %s' % client_buyer.client_account_id puts "\tClient name: %s" % client_buyer.client_name puts "\tEntity ID: %s" % client_buyer.entity_id puts "\tEntity name: %s" % client_buyer.entity_name puts "\tEntity Type: %s" % client_buyer.entity_type puts "\tRole: %s" % client_buyer.role puts "\tStatus: %s" % client_buyer.status puts "\tVisible to seller: %s" % client_buyer.visible_to_seller end else puts 'No client buyers found for account ID %s.' % account_id end rescue Google::Apis::ServerError => e raise "The following server error occured:\n%s" % e.message rescue Google::Apis::ClientError => e raise "Invalid client request:\n%s" % e.message rescue Google::Apis::AuthorizationError => e raise "Authorization error occured:\n%s" % e.message end end if __FILE__ == $0 begin # Retrieve the service used to make API requests. service = get_service(ADEXCHANGEBUYER_V2BETA1) rescue ArgumentError => e raise 'Unable to create service, with error message: %s' % e.message rescue Signet::AuthorizationError => e raise ('Unable to create service, was the KEY_FILE in samples_util.rb ' + 'set? Error message: %s') % e.message end # Set options and default values for fields used in this example. options = [ Option.new( 'account_id', 'The integer ID of the Authorized Buyers account.', :type => Integer, :short_alias => 'a', :required => true, :default_value => nil # Insert default value here. ), Option.new( 'max_page_size', 'The maximum number of entries returned on one result page.', :type => Integer, :short_alias => 'm', :required => true, :default_value => MAX_PAGE_SIZE ) ] # Parse options. parser = Parser.new(options) opts = parser.parse(ARGV) list_client_buyers(service, opts['account_id'], opts['page_size']) end
Next steps
- Read the background guide to more fully understand what is happening in the samples and the options available to you in developing your solution.
- When you have got a client library up and running, try extending the code examples to meet your needs.
- Visit the reference documentation for the version you are working with to learn more about the API.
- If you need help, visit the Forum.
- If your application is expected to perform real-time bidding, read the RTB Protocol documentation.
- Read the Performance Tips.
Take a survey
Help us improve this documentation; tell us what worked and what we missed by filling out a quick survey.