Google APIs use theOAuth 2.0 protocolfor
authentication and authorization. Here's how to set up authentication for the
Real-time Bidding API using OAuth 2.0.
From the project drop-down, select a project or create a new one.
In the list ofEnabled APIs, make sure Real-time Bidding API is listed. If
it's not listed, click theGoogle APIstab, search for and select the
Real-time Bidding API, and clickEnable API.
Next, in the sidebar on the left selectCredentials.
Select theCreate credentialsdrop-down, then chooseService account
key.
In theService accountdrop-down, chooseNew service account.
Enter aNamefor the service account. Theservice account IDis
automatically generated from the name and project name.
Note the service account ID: you need it to grant access to the new service
account in the Authorized Buyers UI in step 11.
Choose the recommended JSON file as theKey type.
ClickCreate. The JSON file with the account's public/private key pair
is saved to your Downloads folder. Keep the generated JSON file in a
safe place.
You must grant the service account access in theAuthorized Buyers
UIfor it to work. SelectSettings >
Account Settings, then chooseUser 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.
Make sure multiple people have Admin access to your cloud project, in case you
need to change the permissions.
Request API access
When stepping through the OAuth 2.0 authorization flow, your application can
specifyscopesto request access to certain
features on behalf of other Google Accounts. Use the following scopes to gain
read/write access to any of the Authorized Buyers APIs on behalf of an
Authorized Buyers account:
Ad Exchange Buyer API II: https://www.googleapis.com/auth/adexchange.buyer
Make an API call
Here are some samples you can use to get started in our supported languages:
Marketplace API
Java
/** Copyright 2021 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.*/packagecom.google.api.services.samples.authorizedbuyers.marketplace.v1;importcom.google.api.client.googleapis.javanet.GoogleNetHttpTransport;importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.HttpTransport;importcom.google.api.client.json.JsonFactory;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplace;importcom.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplaceScopes;importcom.google.api.services.authorizedbuyersmarketplace.v1.model.Client;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importcom.google.auth.oauth2.ServiceAccountCredentials;importjava.io.FileInputStream;importjava.io.IOException;importjava.util.HashSet;importjava.util.List;importjava.util.Set;/*** A sample application that authenticates and runs a request against the Authorized Buyers* Marketplace API.*/publicclassFirstApiRequest{/*** Be sure to specify the name of your application. If the application name is {@code null} or* blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".*/privatestaticfinalStringAPPLICATION_NAME="APPLICATION_NAME_HERE";// Full path to JSON Key file - include file name.privatestaticfinaljava.io.FileJSON_FILE=newjava.io.File("INSERT_PATH_TO_JSON_FILE");// Name of the buyer resource for which the API call is being made.privatestaticfinalStringBUYER_NAME="INSERT_BUYER_RESOURCE_NAME";// Global instance of the HTTP transport.privatestaticHttpTransporthttpTransport;// Global instance of the JSON factory.privatestaticfinalJsonFactoryjsonFactory=GsonFactory.getDefaultInstance();publicstaticvoidmain(String[]args)throwsException{// Create credentials using the JSON key file.GoogleCredentialscredentials=null;try(FileInputStreamserviceAccountStream=newFileInputStream((JSON_FILE))){Set<String>scopes=newHashSet<>(AuthorizedBuyersMarketplaceScopes.all());credentials=ServiceAccountCredentials.fromStream(serviceAccountStream).createScoped(scopes);}catch(IOExceptionex){System.out.println("Can't complete authorization step. Did you specify a JSON key file?");System.out.println(ex);System.exit(1);}HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials);httpTransport=GoogleNetHttpTransport.newTrustedTransport();// Use the credentials to create a client for the API service.AuthorizedBuyersMarketplacemarketplaceClient=newAuthorizedBuyersMarketplace.Builder(httpTransport,jsonFactory,requestInitializer).setApplicationName(APPLICATION_NAME).build();// Call the buyers.clients.list method to get a list of clients for the given buyer.List<Client>clients=marketplaceClient.buyers().clients().list(BUYER_NAME).execute().getClients();if(clients!=null&&clients.size()>0){System.out.printf("Listing of clients associated with buyer \"%s\"%n",BUYER_NAME);for(Clientclient:clients){System.out.printf("* Client name: %s\n",client.getName());}}else{System.out.printf("No clients were found that were associated with buyer \"%s\"%n.",BUYER_NAME);}}}
Python
#!/usr/bin/python## 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."""Sample application that authenticates and makes an API request."""importpprintfromgoogleapiclient.discoveryimportbuildfromgoogle.oauth2importservice_account# A Service Account key file can be generated via the Google Developers# Console.KEY_FILE='PATH_TO_JSON_KEY_FILE'# Path to Service Account JSON key file.# Authorized Buyers Marketplace API authorization scope.SCOPE='https://www.googleapis.com/auth/authorized-buyers-marketplace'VERSION='v1'# Version of Authorized Buyers Marketplace API to use.# Name of the buyer resource for which the API call is being made.BUYER_NAME='BUYER_RESOURCE_NAME'defmain():# Create credentials using the Service Account JSON key file.credentials=service_account.Credentials.from_service_account_file(KEY_FILE,scopes=[SCOPE])# Build a client for the authorizedbuyersmarketplace API service.marketplace=build('authorizedbuyersmarketplace',VERSION,credentials=credentials)# Call the buyers.clients.list method to get a list of clients for the# given buyer.request=marketplace.buyers().clients().list(parent=BUYER_NAME)pprint.pprint(request.execute())if__name__=='__main__':main()
.NET
/* Copyright 2021 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.*/usingGoogle.Apis.AuthorizedBuyersMarketplace.v1;usingGoogle.Apis.AuthorizedBuyersMarketplace.v1.Data;usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Json;usingGoogle.Apis.Services;usingSystem;usingSystem.Collections.Generic;namespaceGoogle.Apis.AuthorizedBuyersMarketplace.Examples.v1{/// <summary>/// Self contained sample to return a list of clients for a given buyer account./// Primarily used by the Getting Started guide:/// https://developers.google.com/authorized-buyers/apis/getting_started////// Note: To run this sample, you will need to configure it as the StartupObject in/// Google.Apis.AuthorizedBuyersMarketplace.Examples.csproj./// </summary>internalclassFirstApiRequest{privatestaticvoidMain(string[]args){// See the README.md for details of these fields.// Retrieved from https://console.developers.google.comvarServiceKeyFilePath="PATH TO JSON KEY FILE HERE";// Name of the buyer resource for which the API call is being made.varbuyerName="INSERT_BUYER_RESOURCE_NAME_HERE";// Retrieve credential parameters from the key JSON file.varcredentialParameters=NewtonsoftJsonSerializer.Instance.Deserialize<JsonCredentialParameters>(System.IO.File.ReadAllText(ServiceKeyFilePath));// Create the credentials.varcredentialInitializer=newServiceAccountCredential.Initializer(credentialParameters.ClientEmail){Scopes=new[]{AuthorizedBuyersMarketplaceService.Scope.AuthorizedBuyersMarketplace}}.FromPrivateKey(credentialParameters.PrivateKey);varoAuth2Credentials=newServiceAccountCredential(credentialInitializer);// Use the credentials to create a client for the API service.varserviceInitializer=newBaseClientService.Initializer{HttpClientInitializer=oAuth2Credentials,ApplicationName="FirstAPICall"};varmkService=newAuthorizedBuyersMarketplaceService(serviceInitializer);// Call the buyers.clients.list method to list clients for the given buyer.BuyersResource.ClientsResource.ListRequestrequest=mkService.Buyers.Clients.List(buyerName);IList<Client>clients=request.Execute().Clients;foreach(Clientclientinclients){Console.WriteLine("* Client name: {0}",client.Name);}Console.ReadLine();}}}
PHP
<?php/*** 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.*//*** Sample application that authenticates and makes an API request.*/namespace Google\Ads\AuthorizedBuyers\Marketplace\Examples\V1;/*** Provide path to client library. See README.md for details.*/require_once __DIR__ . '/../../vendor/autoload.php';use Google_Client;use Google_Service_AuthorizedBuyersMarketplace;session_start();/*** You can retrieve this file from the Google Developers Console.** See README.md for details.*/$keyFileLocation = "INSERT_PATH_TO_JSON_KEYFILE";/*** Name of the buyer resource for which the API call is being made.*/$buyerName = "INSERT_BUYER_RESOURCE_NAME";if ($keyFileLocation === 'INSERT_PATH_TO_JSON_KEYFILE') {print "WARNING: Authorization details not provided!\n";exit(1);}$client = new Google_Client();$client->setApplicationName('Authorized Buyers Marketplace API PHP Samples');$service = new Google_Service_AuthorizedBuyersMarketplace($client);$client->setAuthConfig($keyFileLocation);$client->addScope('https://www.googleapis.com/auth/authorized-buyers-marketplace');if ($client->isAccessTokenExpired()) {$client->refreshTokenWithAssertion();}if ($client->getAccessToken()) {// Call the buyers.clients.list method to get a list of clients for the given buyer.$result = $service->buyers_clients->listBuyersClients($buyerName);print "Clients associated with buyer account\n";if (empty($result['clients'])) {print "No clients found\n";return;} else {foreach ($result['clients'] as $client) {print_r($client);}}}
Ruby
#!/usr/bin/env ruby# Encoding: utf-8## Copyright:: Copyright 2022 Google LLC## 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.## Sample application that authenticates and makes an API request.require'google/apis/authorizedbuyersmarketplace_v1'require'googleauth/service_account'# You can download the JSON keyfile used for authentication from the Google# Developers Console.KEY_FILE='path_to_key'# Path to JSON file containing your private key.# Name of the buyer resource for which the API call is being made.BUYER_NAME='insert_buyer_resource_name'deffirst_api_request()# Create credentials using the JSON key file.auth_options={:json_key_io=>File.open(KEY_FILE,"r"),:scope=>'https://www.googleapis.com/auth/authorized-buyers-marketplace'}oauth_credentials=Google::Auth::ServiceAccountCredentials.make_creds(options=auth_options)# Create the service and set credentialsmarketplace=(Google::Apis::AuthorizedbuyersmarketplaceV1::AuthorizedBuyersMarketplaceService.new)marketplace.authorization=oauth_credentialsmarketplace.authorization.fetch_access_token!begin# Call the buyers.clients.list method to get list of clients for given buyer.clients_list=marketplace.list_buyer_clients(BUYER_NAME)ifclients_list.clients.any?puts"Found the following clients for buyer '%s':"%BUYER_NAMEclients_list.clients.eachdo|client|puts"* Client name:#{client.name}"endelseputs"No clients were found that were associated with buyer '%s'"%BUYER_NAMEendrescueGoogle::Apis::ServerError=>eraise"The following server error occured:\n%s"%e.messagerescueGoogle::Apis::ClientError=>eraise"Invalid client request:\n%s"%e.messagerescueGoogle::Apis::AuthorizationError=>eraise"Authorization error occured:\n%s"%e.messageendendif__FILE__==$0beginfirst_api_request()endend
Real-time Bidding API
Java
Here is a basic example that shows how to use the Real-time Bidding API with Java.
All calls to the API require authentication; create aCredentialusing the Service Account JSON key File discussed
above.
GoogleCredentialscredentials=null;try(FileInputStreamserviceAccountStream=newFileInputStream((JSON_FILE))){Set<String>scopes=newHashSet<>(RealTimeBiddingScopes.all());credentials=ServiceAccountCredentials.fromStream(serviceAccountStream).createScoped(scopes);}catch(IOExceptionex){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:
HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials);httpTransport=GoogleNetHttpTransport.newTrustedTransport();// Use the credentials to create a client for the API service.RealTimeBiddingrealtimeBidding=newRealTimeBidding.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(Creativecreative: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);}
Finally, run the following to install dependency libraries:
composer install
Set up a client
Create aGoogle_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.
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);}}
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*.csprojfile, add aPackageReferenceentry 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:
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.
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 credentialsrealtimebidding=(Google::Apis::RealtimebiddingV1::RealtimeBiddingService.new)realtimebidding.authorization=oauth_credentialsrealtimebidding.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')ifcreatives_list.creatives.any?puts"Found the following creatives for buyer '%s':"%BUYER_NAMEcreatives_list.creatives.eachdo|creative|puts"* Creative name:#{creative.name}"endelseputs"No creatives were found that were associated with buyer '%s'"%BUYER_NAMEend
/** Copyright (c) 2017 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.*/packagecom.google.api.services.samples.adexchangebuyer.cmdline.v2_x;importcom.google.api.client.googleapis.services.json.AbstractGoogleJsonClient;importcom.google.api.services.adexchangebuyer2.v2beta1.AdExchangeBuyerII;importcom.google.api.services.adexchangebuyer2.v2beta1.model.AbsoluteDateRange;importcom.google.api.services.adexchangebuyer2.v2beta1.model.Client;importcom.google.api.services.adexchangebuyer2.v2beta1.model.Date;importcom.google.api.services.adexchangebuyer2.v2beta1.model.FilterSet;importcom.google.api.services.adexchangebuyer2.v2beta1.model.RealtimeTimeRange;importcom.google.api.services.adexchangebuyer2.v2beta1.model.RelativeDateRange;importcom.google.api.services.samples.adexchangebuyer.cmdline.BaseSample;importjava.io.IOException;importjava.util.List;/*** This sample illustrates how to retrieve all Bidder-level Filter Sets.*/publicclassGetAllBidderLevelFilterSetsextendsBaseSample{@OverridepublicClientTypegetClientType(){returnClientType.ADEXCHANGEBUYERII;}@OverridepublicStringgetName(){return"Get All Bidder-level Filter Sets.";}@OverridepublicStringgetDescription(){return"Lists Filter Sets associated with the given Bidder.";}@Overridepublicvoidexecute(AbstractGoogleJsonClientclient)throwsIOException{AdExchangeBuyerIIadXClient=(AdExchangeBuyerII)client;StringbidderResourceId=getStringInput("bidderResourceId","Enter the Bidder's resource ID");StringownerName=String.format("bidders/%s",bidderResourceId);List<FilterSet>allFilterSets=adXClient.bidders().filterSets().list(ownerName).execute().getFilterSets();if(allFilterSets!=null&&allFilterSets.size()>0){System.out.println("========================================");System.out.printf("Listing of Filter Sets associated with Bidder \"%s\"%n",ownerName);System.out.println("========================================");for(FilterSetfilterSet:allFilterSets){System.out.printf("* Filter Set name: %s%n",filterSet.getName());AbsoluteDateRangeabsDateRange=filterSet.getAbsoluteDateRange();if(absDateRange!=null){System.out.println("AbsoluteDateRange");System.out.printf("\tStart date: %s%n",convertDateToString(absDateRange.getStartDate()));System.out.printf("\tEnd date: %s%n",convertDateToString(absDateRange.getEndDate()));}RelativeDateRangerelDateRange=filterSet.getRelativeDateRange();if(relDateRange!=null){Integeroffset=relDateRange.getOffsetDays();System.out.println("RelativeDateRange");System.out.printf("\tOffset days: %s%n",offset!=null?offset:0);System.out.printf("\tDuration days: %s%n",relDateRange.getDurationDays());}RealtimeTimeRangertTimeRange=filterSet.getRealtimeTimeRange();if(rtTimeRange!=null){System.out.println("RealtimeTimeRange");System.out.printf("\tStart timestamp: %s%n",rtTimeRange.getStartTimestamp());}StringtimeSeriesGranularity=filterSet.getTimeSeriesGranularity();if(timeSeriesGranularity!=null){System.out.printf("Time series granularity: %s%n",timeSeriesGranularity);}Stringformat=filterSet.getFormat();if(format!=null){System.out.printf("\tFormat: %s%n",format);}Stringenvironment=filterSet.getEnvironment();if(environment!=null){System.out.printf("Environment: %s%n",environment);}List<String>platforms=filterSet.getPlatforms();if(platforms!=null){System.out.println("Platforms:");for(Stringplatform:platforms){System.out.printf("\t%s%n",platform);}}List<Integer>sellerNetworkIds=filterSet.getSellerNetworkIds();if(filterSet.getSellerNetworkIds()!=null){System.out.println("Seller network IDS:");for(IntegersellerNetworkId:sellerNetworkIds){System.out.printf("\t%d%n",sellerNetworkId);}}}}else{System.out.printf("No Filter Sets were found associated with Bidder \"%s\"%n",ownerName);}}privateStringconvertDateToString(Datedate){returnString.format("%d%02d%02d",date.getYear(),date.getMonth(),date.getDay());}}
Python
#!/usr/bin/python## Copyright 2017 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 bidder-level filter sets."""importargparseimportosimportpprintimportsyssys.path.insert(0,os.path.abspath('..'))fromgoogleapiclient.errorsimportHttpErrorimportsamples_util_OWNER_NAME_TEMPLATE='bidders/{bidders_resource_id}'DEFAULT_BIDDER_RESOURCE_ID='ENTER_BIDDER_RESOURCE_ID_HERE'defmain(ad_exchange_buyer,owner_name):try:# Construct and execute the request.filter_sets=ad_exchange_buyer.bidders().filterSets().list(ownerName=owner_name).execute()print(f'Listing FilterSets for bidder: "{owner_name}".')pprint.pprint(filter_sets)exceptHttpErrorase:print(e)if__name__=='__main__':parser=argparse.ArgumentParser(description='Creates a bidder-level filter set with the specified options')# Required fields.parser.add_argument('-b','--bidder_resource_id',default=DEFAULT_BIDDER_RESOURCE_ID,help=('The resource ID of the bidders resource for which the filter ''sets were created. This will be used to construct the ownerName ''used as a path parameter for filter set requests. For additional ''information on how to configure the ownerName path parameter, ''see: https://developers.google.com/authorized-buyers/apis/''reference/rest/v2beta1/bidders.filterSets/list''#body.PATH_PARAMETERS.owner_name'))args=parser.parse_args()try:service=samples_util.GetService('v2beta1')exceptIOErrorasex:print(f'Unable to create adexchangebuyer service -{ex}')print('Did you specify the key file in samples_util.py?')sys.exit(1)main(service,_OWNER_NAME_TEMPLATE.format(bidders_resource_id=args.bidder_resource_id))
PHP
<?php/*** Copyright 2017 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 Bidder-level Filter Sets.*/class ListBidderLevelFilterSets extends BaseExample {/*** @see BaseExample::getInputParameters()*/protected function getInputParameters() {return [['name' => 'bidderResourceId','display' => 'Bidder Resource ID','required' => true]];}/*** @see BaseExample::run()*/public function run() {$values = $this->formValues;$ownerName = sprintf('bidders/%s',$values['bidderResourceId']);$result = $this->service->bidders_filterSets->listBiddersFilterSets($ownerName);print sprintf('<h2>Listing Bidder-level Filter Sets for ownerName "%s"</h2>',$ownerName);if (empty($result['filterSets'])) {print '<p>No Bidder-level Filter Sets found.</p>';} else {foreach ($result['filterSets'] as $filterSets) {$this->printResult($filterSets);}}}/*** @see BaseExample::getClientType()*/public function getClientType() {return ClientType::AdExchangeBuyerII;}/*** @see BaseExample::getName()*/public function getName() {return 'RTB Troubleshooting: List Bidder-level Filter Sets';}}
.NET
/* Copyright 2017, 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.*/usingGoogle.Apis.AdExchangeBuyerII.v2beta1;usingGoogle.Apis.AdExchangeBuyerII.v2beta1.Data;usingGoogle.Apis.Services;usingSystem;usingSystem.Collections.Generic;namespaceGoogle.Apis.AdExchangeBuyer.Examples.v2_x{/// <summary>/// Retrieves the bidder-level filter sets for the given bidder resource ID./// </summary>publicclassListBidderLevelFilterSets:ExampleBase{/// <summary>/// Main method, to run this code example as a standalone application./// </summary>/// <param name="args">The command line arguments</param>publicstaticvoidMain(string[]args){AdExchangeBuyerIIServiceservice=Utilities.GetV2Service();ExampleBaseexample=newListBidderLevelFilterSets();Console.WriteLine(example.Description);example.Run(service);}/// <summary>/// Returns a description about the code example./// </summary>publicoverridestringDescription{get{return"This code example lists all bidder-level filter sets for the given "+"bidder resource ID.";}}/// <summary>/// Runs the code example./// </summary>/// <param name="service">An authenticated AdExchangeBuyerIIService</param>publicoverridevoidRun(BaseClientServiceservice){AdExchangeBuyerIIServiceadXService=(AdExchangeBuyerIIService)service;stringbidderResourceId="INSERT_BIDDER_RESOURCE_ID_HERE";stringownerName=String.Format("bidders/{0}",bidderResourceId);ListFilterSetsResponseresponse=adXService.Bidders.FilterSets.List(ownerName).Execute();Console.WriteLine("========================================\n");Console.WriteLine("Listing of filter sets associated with owner name \"{0}\"",ownerName);Console.WriteLine("========================================\n");if(response.FilterSets.Count==0){Console.WriteLine("No filter sets found.");}else{foreach(FilterSetfilterSetinresponse.FilterSets){Console.WriteLine("* Name: {0}",filterSet.Name);AbsoluteDateRangeabsDateRange=filterSet.AbsoluteDateRange;if(absDateRange!=null){Console.WriteLine("\tAbsoluteDateRange:");DatestartDate=absDateRange.StartDate;Console.WriteLine("\t\tStartDate:");Console.WriteLine("\t\t\tYear: {0}",startDate.Year);Console.WriteLine("\t\t\tMonth: {0}",startDate.Month);Console.WriteLine("\t\t\tDay: {0}",startDate.Day);DateendDate=absDateRange.EndDate;Console.WriteLine("\t\tEndDate:");Console.WriteLine("\t\t\tYear: {0}",endDate.Year);Console.WriteLine("\t\t\tMonth: {0}",endDate.Month);Console.WriteLine("\t\t\tDay: {0}",endDate.Day);}RelativeDateRangerelDateRange=filterSet.RelativeDateRange;if(relDateRange!=null){Console.WriteLine("\tRelativeDateRange:");Console.WriteLine("\t\tOffsetDays: {0}",relDateRange.OffsetDays);Console.WriteLine("\t\tDurationDays: {0}",relDateRange.DurationDays);}RealtimeTimeRangertTimeRange=filterSet.RealtimeTimeRange;if(rtTimeRange!=null){Console.WriteLine("\tRealtimeTimeRange:");Console.WriteLine("\t\tStartTimestamp: {0}",rtTimeRange.StartTimestamp);}StringtimeSeriesGranularity=filterSet.TimeSeriesGranularity;if(timeSeriesGranularity!=null){Console.WriteLine("\tTimeSeriesGranularity: {0}",timeSeriesGranularity);}IList<String>formats=filterSet.Formats;if(formats!=null){Console.WriteLine("\tFormats:");foreach(stringformatinformats){Console.WriteLine("\t\t{0}",format);}}Stringenvironment=filterSet.Environment;if(environment!=null){Console.WriteLine("\tEnvironment: {0}",environment);}IList<string>platforms=filterSet.Platforms;if(platforms!=null){Console.WriteLine("\tPlatforms:");foreach(stringplatforminplatforms){Console.WriteLine("\t\t{0}",platform);}}IList<int?>sellerNetworkIds=filterSet.SellerNetworkIds;if(sellerNetworkIds!=null){Console.WriteLine("\tSellerNetworkIds:");foreach(int?sellerNetworkIdinsellerNetworkIds){Console.WriteLine("\t\t{0}",sellerNetworkId);}}}}}publicoverrideClientTypegetClientType(){returnClientType.ADEXCHANGEBUYERII;}}}
Ruby
#!/usr/bin/env ruby# Encoding: utf-8## Copyright:: Copyright 2017, 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 filter sets for a given bidder.## Tags: Bidders.FilterSets.listrequire'optparse'require_relative'../samples_util'deflist_bidder_level_filter_sets(ad_exchange_buyer,owner_name,page_size)beginresponse=ad_exchange_buyer.list_bidder_filter_sets(owner_name,page_size:page_size)unlessresponse.filter_sets.nil?puts'Found the following filter sets for bidder %s:'%owner_nameresponse.filter_sets.eachdo|filter_set|puts'* Filter set name: %s'%filter_set.nameif!filter_set.absolute_date_range.nil?abs_date_range=filter_set.absolute_date_rangestart_date=abs_date_range.start_dateend_date=abs_date_range.end_dateputs"\tAbsolute date range:"puts"\t\tStart date: %s-%s-%s"%[start_date.year,start_date.month,start_date.day]puts"\t\tEnd date: %s-%s-%s"%[end_date.year,end_date.month,end_date.day]endunlessfilter_set.realtime_time_range.nil?realtime_time_range=filter_set.realtime_time_rangeputs"\tRealtime time range:"puts"\t\tStart timestamp: %s"%realtime_time_range.start_timestampendunlessfilter_set.relative_date_range.nil?relative_date_range=filter_set.relative_date_rangeputs"\tRelative date range:"puts"\t\tOffset days: %s"%relative_date_range.offset_daysputs"\t\tDuration days: %s"%relative_date_range.duration_daysendunlessfilter_set.time_series_granularity.nil?puts"\tTime series granularity: %s"%filter_set.time_series_granularityendunlessfilter_set.format.nil?puts"\tFormat: %s"%filter_set.formatendunlessfilter_set.environment.nil?puts"\tEnvironment: %s"%filter_set.environmentendunlessfilter_set.platforms.nil?puts"\tPlatforms: %s"%filter_set.platforms.inspectendunlessfilter_set.seller_network_ids.nil?puts"\tSeller network IDs: %s"%filter_set.seller_network_ids.inspectendendelseputs'No filter sets found for bidder %s.'%owner_nameendrescueGoogle::Apis::ServerError=>eraise"The following server error occured:\n%s"%e.messagerescueGoogle::Apis::ClientError=>eraise"Invalid client request:\n%s"%e.messagerescueGoogle::Apis::AuthorizationError=>eraise"Authorization error occured:\n%s"%e.messageendendif__FILE__==$0begin# Retrieve the service used to make API requests.service=get_service(ADEXCHANGEBUYER_V2BETA1)rescueArgumentError=>eraise'Unable to create service, with error message: %s'%e.messagerescueSignet::AuthorizationError=>eraise('Unable to create service, was the KEY_FILE in samples_util.rb '+'set? Error message: %s')%e.messageend# Set options and default values for fields used in this example.options=[Option.new('bidder_resource_id',('The resource ID of the bidders resource for which the filter '+'sets were created. This will be used to construct the ownerName '+'used as a path parameter for filter set requests. For additional '+'information on how to configure the ownerName path parameter, '+'see: https://developers.google.com/authorized-buyers/apis/reference/'+'rest/v2beta1/bidders.filterSets/list#body.PATH_PARAMETERS.owner_name'),:short_alias=>'b',: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)owner_name='bidders/%s'%opts['bidder_resource_id']list_bidder_level_filter_sets(service,owner_name,opts['max_page_size'])end
Next steps
Read thebackground guideto
lean more about the samples, and the available options for developing your
solution.
[[["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-28 UTC."],[[["\u003cp\u003eThe Authorized Buyers APIs provide programmatic access to manage deals, bidding, and account information within the Authorized Buyers platform, including the Marketplace and Real-time Bidding.\u003c/p\u003e\n"],["\u003cp\u003eAuthentication for the Real-time Bidding API involves creating a service account, generating a JSON key file, and granting the service account access in the Authorized Buyers UI, with specific scopes for each API.\u003c/p\u003e\n"],["\u003cp\u003eThe provided examples demonstrate how to use the Marketplace API to list clients and the Real-time Bidding API to list creatives for a buyer account, using various languages like Java, Python, PHP, C#, and Ruby.\u003c/p\u003e\n"],["\u003cp\u003eThe Ad Exchange Buyer API II is deprecated, and the examples provided use it to retrieve and display a list of filter sets associated with a specific bidder, showcasing various properties.\u003c/p\u003e\n"],["\u003cp\u003eA wide range of resources are provided, such as background guides, client library setup, documentation, performance tips and community forum, to help developpers use and get the best out of the API.\u003c/p\u003e\n"]]],[],null,[]]