Bidders, Buyers, and Endpoints

Overview

Bidders and buyers

bidders and buyers are root-level resources representing accounts in the context of two different use cases:

  • A bidder represents the entity that manages a real-time bidding integration in order to place bids for ad inventory on behalf of one or more buyers in Real-time Bidding.

  • A buyer is the entity that intends to place ads and is ultimately billed for ad placements.

The bidders resource and its sub-resources are generally used for the purpose of managing a real-time bidding integration, or acting upon one or more resources for associated buyers.

The buyers resource and its sub-resources are generally focused on the specifics of an individual buyer—such as managing creatives that can be bid with on their behalf.

Many operations in the Real-time Bidding API are performed in the context of a specific bidder or buyer, so most API resources are directly under one of these two resources.

Endpoints

The bidders.endpoints resource is intended to provide information to bidders about the endpoints hosting their real-time bidding integration that are registered with Google. At least one endpoint must be registered with Google to participate in real-time bidding, where the bid requests received by any individual endpoint are dependent on its tradingLocation and your pretargeting configuration.

Once configured, the endpoint's url will generally receive a number of bid requests per second that is near the value specified for maximumQps, which will be in the specified bidProtocol. There are many reasons why the number of bid requests received might be lower however—such as overly restrictive pretargeting, or a high error rate resulting in throttling. To learn more about this topic, read the Callout Quota System guide.

Using the Bidders resource

Retrieve an individual bidder

The following code demonstrates how an authorized user can retrieve an individual bidder with bidders.get.

REST

Request

GET https://realtimebidding.googleapis.com/v1/bidders/12345678?alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json

Response

{
  "cookieMatchingNetworkId": "devrel_test_account",
  "cookieMatchingUrl": "https://google.com/cm",
  "dealsBillingId": "10293847",
  "name": "bidders/12345678"
}

C#

/* 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.
 */

using Google.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Bidders
{
    /// <summary>
    /// Gets a single bidder for the specified bidder name.
    ///
    /// The bidder specified must be associated with the authorized service account specified in
    /// Utilities.cs.
    /// </summary>
    public class GetBidders : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public GetBidders()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "Get a bidder for the given account ID.";
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            string[] requiredOptions = new string[] {"account_id"};
            bool showHelp = false;

            string accountId = null;

            OptionSet options = new OptionSet {
                "Get a bidder for the given bidder account ID.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the bidders resource that is being " +
                     "retrieved. This will be used to construct the name used as a path " +
                     "parameter for the bidders.get request."),
                    a => accountId = a
                },
            };

            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;
            // 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 name = $"bidders/{accountId}";

            BiddersResource.GetRequest request = rtbService.Bidders.Get(name);
            Bidder response = null;

            Console.WriteLine("Getting bidder with name: {0}", name);

            try
            {
                response = request.Execute();
            }
            catch (System.Exception exception)
            {
                throw new ApplicationException(
                    $"Real-time Bidding API returned error response:\n{exception.Message}");
            }

            Utilities.PrintBidder(response);
        }
    }
}

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.
 */

package com.google.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.Bidder;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

import java.io.IOException;
import java.security.GeneralSecurityException;

/**
 * This sample illustrates how to get a single bidder for the specified bidder name.
 *
 * The bidder specified must be associated with the authorized service account specified in Utils.java.
 */
public class GetBidders {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) {
    Integer accountId = parsedArgs.getInt("account_id");
    String name = String.format("bidders/%s", accountId);

    Bidder bidder = null;

    try {
      bidder = client.bidders().get(name).execute();
    } catch(IOException ex) {
      System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
      System.exit(1);
    }

    System.out.printf("Get bidder with ID '%s'.\n", accountId);
    Utils.printBidder(bidder);
  }

  public static void main(String[] args) {
    ArgumentParser parser = ArgumentParsers.newFor("GetBidders").build()
        .defaultHelp(true)
        .description(("Get a bidder for the given account ID."));
    parser.addArgument("-a", "--account_id")
        .help("The resource ID of the bidders resource that is being retrieved. This will be " +
            "used to construct the name used as a path parameter for the bidders.get request.")
        .required(true)
        .type(Integer.class);

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding 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);
  }
}

PHP

<?php

/**
 * 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.
 */

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Bidders;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;

/**
 * This example illustrates how to get a single bidder for the specified bidder name.
 *
 * The bidder specified must be associated with the authorized service account.
 */
class GetBidders extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Account ID',
                'required' => true,
                'description' =>
                    'The resource ID of the bidders resource that is being retrieved. This will ' .
                    'be used to construct the name used as a path parameter for the bidders.get ' .
                    'request.'
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;

        $name = "bidders/$values[account_id]";

        try {
            $bidder = $this->service->bidders->get($name);
            print '<h2>Found bidder.</h2>';
            $this->printResult($bidder);
        } catch (Google_Service_Exception $ex) {
            if ($ex->getCode() === 404 || $ex->getCode() === 403) {
                print '<h1>Bidder not found or can\'t access bidder account.</h1>';
            } else {
                throw $ex;
            }
        }
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Get Bidder';
    }
}

Python

#!/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 bidder for the specified bidder name.

The bidder specified must be associated with the authorized service account.
"""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../..'))

from googleapiclient.errors import HttpError

import util


_BIDDERS_NAME_TEMPLATE = 'bidders/%s'

DEFAULT_BIDDER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE'


def main(realtimebidding, account_id):
  print(f'Get Bidder with ID "{account_id}":')
  try:
    # Construct and execute the request.
    response = realtimebidding.bidders().get(
        name=_BIDDERS_NAME_TEMPLATE % account_id).execute()
  except HttpError as e:
    print(e)
    sys.exit(1)

  pprint.pprint(response)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print(f'Unable to create realtimebidding service - {ex}')
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Get a bidder for the given account ID.'))
  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BIDDER_RESOURCE_ID,
      help=('The resource ID of the bidders resource that is being retrieved. '
            'This will be used to construct the name used as a path parameter '
            'for the bidders.get request.'))

  args = parser.parse_args()

  main(service, args.account_id)


Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2021 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.
#
# Gets a single bidder for the specified bidder name.
#
# The bidder specified must be associated with the service account specified in util.rb.

require 'optparse'

require_relative '../../util'


def get_bidders(realtimebidding, options)
  name = "bidders/#{options[:account_id]}"

  puts "Get bidder with name '#{name}'"

  bidder = realtimebidding.get_bidder(name)
  print_bidder(bidder)
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the bidders resource that is being retrieved. This will be used to '\
      'construct the name used as a path parameter for the bidders.get request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    get_bidders(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

Retrieve a list of bidders

The following code demonstrates how an authorized user can retrieve a list of all bidders associated with their Google or Service account with bidders.list.

REST

Request

GET https://realtimebidding.googleapis.com/v1/bidders?pageSize=50&alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json

Response

{
  "bidders": [
    {
      "cookieMatchingNetworkId": "devrel_test_account",
      "cookieMatchingUrl": "https://google.com/cm",
      "dealsBillingId": "10293847",
      "name": "bidders/12345678"
    }
  ]
}

C#

/* 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.
 */

using Google.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Bidders
{
    /// <summary>
    /// Lists bidders associated with the authorized service account.
    /// </summary>
    public class ListBidders : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public ListBidders()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "This code example lists all bidders associated with the service account " +
                   "specified for the OAuth 2.0 flow in Utilities.cs.";
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            string[] requiredOptions = new string[] {};
            bool showHelp = false;
            int? pageSize = null;

            OptionSet options = new OptionSet {
                "List bidders associated with the authorized service account.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "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["page_size"] = 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 pageToken = null;

            Console.WriteLine("Listing bidders for the authorized service account:");
            do
            {
                BiddersResource.ListRequest request = rtbService.Bidders.List();
                request.PageSize = (int) parsedArgs["page_size"];
                request.PageToken = pageToken;

                ListBiddersResponse page = null;

                try
                {
                    page = request.Execute();
                }
                catch (System.Exception exception)
                {
                    throw new ApplicationException(
                        $"Real-time Bidding API returned error response:\n{exception.Message}");
                }

                var bidders = page.Bidders;
                pageToken = page.NextPageToken;

                if(bidders == null)
                {
                    Console.WriteLine("No bidders found.");
                }
                else
                {
                    foreach (Bidder bidder in bidders)
                        {
                            Utilities.PrintBidder(bidder);
                        }
                }
            }
            while(pageToken != null);
        }
    }
}

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.
 */

package com.google.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.Bidder;
import com.google.api.services.realtimebidding.v1.model.ListBiddersResponse;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;

/**
 * This sample illustrates how to list bidders associated with the authorized service account.
 */
public class ListBidders {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) {
    Integer pageSize = parsedArgs.getInt("page_size");
    String pageToken = null;

    System.out.println("Listing bidders associated with OAuth 2.0 credentials.");

    do {
      List<Bidder> bidders = null;

      try {
        ListBiddersResponse response = client.bidders().list()
            .setPageSize(pageSize)
            .setPageToken(pageToken)
            .execute();

        bidders = response.getBidders();
        pageToken = response.getNextPageToken();
      } catch(IOException ex) {
        System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
        System.exit(1);
      }
      if (bidders == null) {
        System.out.println("No bidders found.");
      } else {
        for(Bidder bidder: bidders) {
          Utils.printBidder(bidder);
        }
      }
    } while (pageToken != null);
  }

  public static void main(String[] args) {
    ArgumentParser parser = ArgumentParsers.newFor("ListBidders").build()
        .defaultHelp(true)
        .description("Lists bidders associated with the service account specified for the " +
            "OAuth 2.0 flow in Utils.java");
    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);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding 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);
  }
}

PHP

<?php

/**
 * 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.
 */

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Bidders;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;

/**
 * This example illustrates how to list bidders associated with the authorized service account.
 */
class ListBidders extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'page_size',
                'display' => 'Page size',
                'required' => false,
                'description' =>
                    'The number of rows to return per page. The server may return fewer rows ' .
                    'than specified.',
                'default' => 10
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;

        $queryParams = [
            'pageSize' => $values['page_size']
        ];

        $result = $this->service->bidders->listBidders($queryParams);

        print "<h2>Listing bidders associated with OAuth 2.0 credentials:</h2>";
        if (empty($result['bidders'])) {
            print '<p>No Bidders found</p>';
        } else {
            foreach ($result['bidders'] as $bidder) {
                $this->printResult($bidder);
            }
        }
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'List Bidders';
    }
}

Python

#!/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.

"""Lists bidders associated with the authorized service account."""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../..'))

from googleapiclient.errors import HttpError

import util


def main(realtimebidding, args):
  page_size = args.page_size

  page_token = None
  more_pages = True

  print(f'Listing bidders associated with OAuth 2.0 credentials.')
  while more_pages:
    try:
      # Construct and execute the request.
      response = realtimebidding.bidders().list(
          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.GetService(version='v1')
  except IOError as ex:
    print(f'Unable to create realtimebidding service - {ex}')
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Lists bidders associated with the service account '
                   'specified for the OAuth 2.0 flow in util.py.'))

  # 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.'))

  args = parser.parse_args()

  main(service, args)


Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2021 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.
#
# Lists bidders associated with the service account specified in util.rb.

require 'optparse'

require_relative '../../util'


def list_bidders(realtimebidding, options)
  page_size = options[:page_size]

  page_token = nil

  puts "Listing bidders associated with OAuth 2.0 credentials."
  begin
    response = realtimebidding.list_bidders(
        page_size: page_size, page_token: page_token
    )

    page_token = response.next_page_token

    unless response.bidders.nil?
      response.bidders.each do |bidder|
        print_bidder(bidder)
      end
    else
      puts 'No bidders found.'
    end
  end until page_token == nil
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'page_size', 'The number of rows to return per page. The server may return fewer rows than specified.',
      type: Array, short_alias: 'u', required: false, default_value: MAX_PAGE_SIZE
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    list_bidders(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

Using the Buyers resource

Retrieve an individual buyer

The following code demonstrates how an authorized user can retrieve an individual buyer with buyers.get.

REST

Request

GET https://realtimebidding.googleapis.com/v1/buyers/87654321?alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json

Response

{
  "bidder": "bidders/12345678",
  "billingIds": [
    "1352467980"
  ],
  "displayName": "DevRel Test Account Child Seat",
  "maximumActiveCreativeCount": "20000",
  "name": "buyers/87654321"
}

C#

/* 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.
 */

using Google.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Buyers
{
    /// <summary>
    /// Gets a single buyer for the specified buyer name.
    ///
    /// The buyer specified must be associated with the authorized service account specified in
    /// Utilities.cs.
    /// </summary>
    public class GetBuyers : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public GetBuyers()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "Get a buyer for the given account ID.";
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            string[] requiredOptions = new string[] {"account_id"};
            bool showHelp = false;

            string accountId = null;

            OptionSet options = new OptionSet {
                "Get a buyer for the given buyer account ID.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the buyers resource that is being " +
                     "retrieved. This will be used to construct the name used as a path " +
                     "parameter for the buyers.get request."),
                    a => accountId = a
                },
            };

            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;
            // 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 name = $"buyers/{accountId}";

            BuyersResource.GetRequest request = rtbService.Buyers.Get(name);
            Buyer response = null;

            Console.WriteLine("Getting buyer with name: {0}", name);

            try
            {
                response = request.Execute();
            }
            catch (System.Exception exception)
            {
                throw new ApplicationException(
                    $"Real-time Bidding API returned error response:\n{exception.Message}");
            }

            Utilities.PrintBuyer(response);
        }
    }
}

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.
 */

package com.google.api.services.samples.authorizedbuyers.realtimebidding.v1.buyers;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.Buyer;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

import java.io.IOException;
import java.security.GeneralSecurityException;

/**
 * This sample illustrates how to get a single buyer for the specified name.
 *
 * The buyer specified must be associated with the authorized service account.
 */
public class GetBuyers {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) {
    Integer accountId = parsedArgs.getInt("account_id");
    String name = String.format("buyers/%s", accountId);

    Buyer buyer = null;

    try {
      buyer = client.buyers().get(name).execute();
    } catch(IOException ex) {
      System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
      System.exit(1);
    }

    System.out.printf("Get buyer with ID '%d':\n", accountId);
    Utils.printBuyer(buyer);
  }

  public static void main(String[] args) {
    ArgumentParser parser = ArgumentParsers.newFor("GetCreatives").build()
        .defaultHelp(true)
        .description(("Get a buyer for the given account ID."));
    parser.addArgument("-a", "--account_id")
        .help("The resource ID of the buyers resource that is being retrieved. This will be " +
            "used to construct the name used as a path parameter for the buyers.get request.")
        .required(true)
        .type(Integer.class);

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding 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);
  }
}

PHP

<?php

/**
 * 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.
 */

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Buyers;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;

/**
 * This example illustrates how to get a single buyer for the specified buyer name.
 *
 * The buyer specified must be associated with the authorized service account.
 */
class GetBuyers extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Account ID',
                'required' => true,
                'description' =>
                    'The resource ID of the buyers resource that is being retrieved. This will ' .
                    'be used to construct the name used as a path parameter for the buyers.get ' .
                    'request.'
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;

        $name = "buyers/$values[account_id]";

        try {
            $buyer = $this->service->buyers->get($name);
            print '<h2>Found buyer.</h2>';
            $this->printResult($buyer);
        } catch (Google_Service_Exception $ex) {
            if ($ex->getCode() === 404 || $ex->getCode() === 403) {
                print '<h1>Buyer not found or can\'t access buyer account.</h1>';
            } else {
                throw $ex;
            }
        }
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Get Buyer';
    }
}

Python

#!/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 buyer for the specified buyer name.

The buyer specified must be associated with the authorized service account.
"""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../..'))

from googleapiclient.errors import HttpError

import util


_BUYERS_NAME_TEMPLATE = 'buyers/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'


def main(realtimebidding, account_id):
  print(f'Get Buyer with ID "{account_id}":')
  try:
    # Construct and execute the request.
    response = realtimebidding.buyers().get(
        name=_BUYERS_NAME_TEMPLATE % account_id).execute()
  except HttpError as e:
    print(e)
    sys.exit(1)

  pprint.pprint(response)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print(f'Unable to create realtimebidding service - {ex}')
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Get a buyer for the given account ID.'))
  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
      help=('The resource ID of the buyers resource that is being retrieved. '
            'This will be used to construct the name used as a path parameter '
            'for the buyers.get request.'))

  args = parser.parse_args()

  main(service, args.account_id)


Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2021 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.
#
# Gets a single buyer for the specified buyer name.
#
# The buyer specified must be associated with the service account specified in util.rb.

require 'optparse'

require_relative '../../util'


def get_buyers(realtimebidding, options)
  name = "buyers/#{options[:account_id]}"

  puts "Get buyer with name '#{name}'"

  buyer = realtimebidding.get_buyer(name)
  print_buyer(buyer)
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the buyers resource that is being retrieved. This will be used to '\
      'construct the name used as a path parameter for the buyers.get request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    get_buyers(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

Retrieve a list of buyers

The following code demonstrates how an authorized user can retrieve a list of all buyers associated with their Google or Service Account with buyers.list.

REST

Request

GET https://realtimebidding.googleapis.com/v1/buyers?pageSize=50&alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json

Response

{
  "buyers": [
    {
      "bidder": "bidders/12345678",
      "billingIds": [
        "112233445566",
        "110022993388",
        "229900114488",
        "993388221111"
      ],
      "displayName": "DevRel Test Account",
      "maximumActiveCreativeCount": "20000",
      "name": "buyers/12345678"
    },
    {
      "bidder": "bidders/12345678",
      "billingIds": [
        "1352467980"
      ],
      "displayName": "DevRel Test Account Child Seat",
      "maximumActiveCreativeCount": "20000",
      "name": "buyers/87654321"
    }
  ]
}

C#

/* 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.
 */

using Google.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Buyers
{
    /// <summary>
    /// Lists buyers associated with the authorized service account.
    /// </summary>
    public class ListBuyers : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public ListBuyers()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "This code example lists all buyers associated with the service account " +
                   "specified for the OAuth 2.0 flow in Utilities.cs.";
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            string[] requiredOptions = new string[] {};
            bool showHelp = false;
            int? pageSize = null;

            OptionSet options = new OptionSet {
                "List buyers associated with the authorized service account.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "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["page_size"] = 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 pageToken = null;

            Console.WriteLine("Listing buyers for the authorized service account:");
            do
            {
                BuyersResource.ListRequest request = rtbService.Buyers.List();
                request.PageSize = (int) parsedArgs["page_size"];
                request.PageToken = pageToken;

                ListBuyersResponse page = null;

                try
                {
                    page = request.Execute();
                }
                catch (System.Exception exception)
                {
                    throw new ApplicationException(
                        $"Real-time Bidding API returned error response:\n{exception.Message}");
                }

                var buyers = page.Buyers;
                pageToken = page.NextPageToken;

                if(buyers == null)
                {
                    Console.WriteLine("No buyers found.");
                }
                else
                {
                    foreach (Buyer buyer in buyers)
                        {
                            Utilities.PrintBuyer(buyer);
                        }
                }
            }
            while(pageToken != null);
        }
    }
}

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.
 */

package com.google.api.services.samples.authorizedbuyers.realtimebidding.v1.buyers;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.Buyer;
import com.google.api.services.realtimebidding.v1.model.ListBuyersResponse;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;

/**
 * This sample illustrates how to list buyers associated with the authorized service account.
 */
public class ListBuyers {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) {
    Integer pageSize = parsedArgs.getInt("page_size");
    String pageToken = null;

    System.out.println("Listing buyers associated with OAuth 2.0 credentials.");

    do {
      List<Buyer> buyers = null;

      try {
        ListBuyersResponse response = client.buyers().list()
            .setPageSize(pageSize)
            .setPageToken(pageToken)
            .execute();

        buyers = response.getBuyers();
        pageToken = response.getNextPageToken();
      } catch(IOException ex) {
        System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
        System.exit(1);
      }
      if (buyers == null) {
        System.out.println("No buyers found.");
      } else {
        for(Buyer buyer: buyers) {
          Utils.printBuyer(buyer);
        }
      }
    } while (pageToken != null);
  }

  public static void main(String[] args) {
    ArgumentParser parser = ArgumentParsers.newFor("ListCreatives").build()
        .defaultHelp(true)
        .description(("Lists buyers associated with the service account specified for the OAuth " +
            "2.0 flow in Utils.java."));
    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);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding 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);
  }
}

PHP

<?php

/**
 * 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.
 */

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Buyers;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;

/**
 * This example illustrates how to list buyers associated with the authorized service account.
 */
class ListBuyers extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'page_size',
                'display' => 'Page size',
                'required' => false,
                'description' =>
                    'The number of rows to return per page. The server may return fewer rows ' .
                    'than specified.',
                'default' => 10
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;

        $queryParams = [
            'pageSize' => $values['page_size']
        ];

        $result = $this->service->buyers->listBuyers($queryParams);

        print "<h2>Listing buyers associated with OAuth 2.0 credentials:</h2>";
        if (empty($result['buyers'])) {
            print '<p>No Buyers found</p>';
        } else {
            foreach ($result['buyers'] as $buyer) {
                $this->printResult($buyer);
            }
        }
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'List Buyers';
    }
}

Python

#!/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.

"""Lists buyers associated with the authorized service account."""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../..'))

from googleapiclient.errors import HttpError

import util


def main(realtimebidding, args):
  page_size = args.page_size

  page_token = None
  more_pages = True

  print(f'Listing buyers associated with OAuth 2.0 credentials.')
  while more_pages:
    try:
      # Construct and execute the request.
      response = realtimebidding.buyers().list(
          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.GetService(version='v1')
  except IOError as ex:
    print(f'Unable to create realtimebidding service - {ex}')
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Lists buyers associated with the service account '
                   'specified for the OAuth 2.0 flow in util.py.'))

  # 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.'))

  args = parser.parse_args()

  main(service, args)


Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2021 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.
#
# Lists buyers associated with the service account specified in util.rb.

require 'optparse'

require_relative '../../util'


def list_buyers(realtimebidding, options)
  page_size = options[:page_size]

  page_token = nil

  puts "Listing buyers associated with OAuth 2.0 credentials."
  begin
    response = realtimebidding.list_buyers(
        page_size: page_size, page_token: page_token
    )

    page_token = response.next_page_token

    unless response.buyers.nil?
      response.buyers.each do |buyer|
        print_buyer(buyer)
      end
    else
      puts 'No buyers found.'
    end
  end until page_token == nil
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'page_size', 'The number of rows to return per page. The server may return fewer rows than specified.',
      type: Array, short_alias: 'u', required: false, default_value: MAX_PAGE_SIZE
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    list_buyers(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

Using the Endpoints resource

Retrieve an individual endpoint

The following code demonstrates how a bidder can retrieve an individual endpoint with bidders.endpoints.get.

REST

Request

GET https://realtimebidding.googleapis.com/v1/bidders/12345678/endpoints/16?alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json

Response

{
  "bidProtocol": "GOOGLE_RTB",
  "name": "bidders/12345678/endpoints/16",
  "tradingLocation": "US_EAST",
  "url": "https://test.testendpoint.com/testbidder"
}

C#

/* 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.
 */

using Google.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Bidders.Endpoints
{
    /// <summary>
    /// Gets a single endpoint for the specified bidder and endpoint IDs.
    /// </summary>
    public class GetEndpoints : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public GetEndpoints()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "Get an endpoint for the given bidder and endpoint IDs.";
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            string[] requiredOptions = new string[] {"account_id", "endpoint_id"};
            bool showHelp = false;

            string accountId = null;
            string endpointId = null;

            OptionSet options = new OptionSet {
                "Get an endpoint for the given bidder and endpoint IDs.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the bidders resource under which the " +
                     "endpoint exists. This will be used to construct the name used as a path " +
                     "parameter for the endpoints.get request."),
                    a => accountId = a
                },
                {
                    "e|endpoint_id=",
                    ("[Required] The resource ID of the endpoints resource that is being " +
                     "retrieved. This will be used to construct the name used as a path " +
                     "parameter for the endpoints.get request."),
                    e => endpointId = e
                },
            };

            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["endpoint_id"] = endpointId;
            // 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 endpointId = (string) parsedArgs["endpoint_id"];
            string name = $"bidders/{accountId}/endpoints/{endpointId}";

            BiddersResource.EndpointsResource.GetRequest request =
                rtbService.Bidders.Endpoints.Get(name);
            Endpoint response = null;

            Console.WriteLine("Getting endpoint with name: {0}", name);

            try
            {
                response = request.Execute();
            }
            catch (System.Exception exception)
            {
                throw new ApplicationException(
                    $"Real-time Bidding API returned error response:\n{exception.Message}");
            }

            Utilities.PrintEndpoint(response);
        }
    }
}

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.
 */

package com.google.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders.endpoints;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.Endpoint;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

import java.io.IOException;
import java.security.GeneralSecurityException;

/**
 * This sample illustrates how to get a single endpoint for the specified bidder and endpoint IDs.
 */
public class GetEndpoints {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) {
    Integer accountId = parsedArgs.getInt("account_id");
    Integer endpointId = parsedArgs.getInt("endpoint_id");
    String name = String.format("bidders/%s/endpoints/%s", accountId, endpointId);

    Endpoint endpoint = null;

    try {
      endpoint = client.bidders().endpoints().get(name).execute();
    } catch(IOException ex) {
      System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
      System.exit(1);
    }

    System.out.printf("Get endpoint with ID '%s' for bidder account with ID '%s'.\n",
        endpointId, accountId);
    Utils.printEndpoint(endpoint);
  }

  public static void main(String[] args) {
    ArgumentParser parser = ArgumentParsers.newFor("GetBidders").build()
        .defaultHelp(true)
        .description(("Get an endpoint for the given bidder and endpoint IDs."));
    parser.addArgument("-a", "--account_id")
        .help("The resource ID of the bidders resource under which the endpoint exists. This " +
            "will be used to construct the name used as a path parameter for the endpoints.get " +
            "request.")
        .required(true)
        .type(Integer.class);
    parser.addArgument("-e", "--endpoint_id")
        .help("The resource ID of the endpoints resource that is being retrieved. This will be " +
            "used to construct the name used as a path parameter for the endpoints.get request.")
        .required(true)
        .type(Integer.class);

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding 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);
  }
}

PHP

<?php

/**
 * 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.
 */

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Bidders_Endpoints;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;

/**
 * This example illustrates how to get a single endpoint for the specified bidder and endpoint IDs.
 */
class GetEndpoints extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Account ID',
                'required' => true,
                'description' =>
                    'The resource ID of the bidders resource under which the endpoint exists. ' .
                    'This will be used to construct the name used as a path parameter for the ' .
                    'endpoints.get request.'
            ],
            [
                'name' => 'endpoint_id',
                'display' => 'Endpoint ID',
                'required' => true,
                'description' =>
                    'The resource ID of the endpoints resource that is being retrieved. This ' .
                    'will be used to construct the name used as a path parameter for the ' .
                    'endpoints.get request.'
            ],
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;

        $name = "bidders/$values[account_id]/endpoints/$values[endpoint_id]";

        try {
            $endpoint = $this->service->bidders_endpoints->get($name);
            print '<h2>Found endpoint.</h2>';
            $this->printResult($endpoint);
        } catch (Google_Service_Exception $ex) {
            if ($ex->getCode() === 404 || $ex->getCode() === 403) {
                print '<h1>Endpoint not found or can\'t access endpoint.</h1>';
            } else {
                throw $ex;
            }
        }
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Get Endpoint';
    }
}

Python

#!/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 endpoint for the specified bidder and endpoint IDs."""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_ENDPOINTS_NAME_TEMPLATE = 'bidders/%s/endpoints/%s'

DEFAULT_BIDDER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE'
DEFAULT_ENDPOINT_RESOURCE_ID = 'ENTER_ENDPOINT_RESOURCE_ID_HERE'


def main(realtimebidding, account_id, endpoint_id):
  print(f'Get endpoint with ID "{endpoint_id}" for bidder account with ID '
        f'"{account_id}":')
  try:
    # Construct and execute the request.
    response = realtimebidding.bidders().endpoints().get(
        name=_ENDPOINTS_NAME_TEMPLATE % (account_id, endpoint_id)).execute()
  except HttpError as e:
    print(e)
    sys.exit(1)

  pprint.pprint(response)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print(f'Unable to create realtimebidding service - {ex}')
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Get an endpoint for the given bidder and endpoint IDs.'))
  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BIDDER_RESOURCE_ID,
      help=('The resource ID of the bidders resource under which the endpoint '
            'exists. This will be used to construct the name used as a path '
            'parameter for the endpoints.get request.'))
  parser.add_argument(
      '-e', '--endpoint_id', default=DEFAULT_ENDPOINT_RESOURCE_ID,
      help=('The resource ID of the endpoints resource that is being '
            'retrieved. This will be used to construct the name used as a '
            'path parameter for the endpoints.get request.'))

  args = parser.parse_args()

  main(service, args.account_id, args.endpoint_id)


Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2021 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.
#
# Gets a single endpoint for the specified bidder and endpoint IDs.

require 'optparse'

require_relative '../../../util'


def get_endpoints(realtimebidding, options)
  name = "bidders/#{options[:account_id]}/endpoints/#{options[:endpoint_id]}"

  puts "Get endpoint with name '#{name}'"

  endpoint = realtimebidding.get_bidder_endpoint(name)
  print_endpoint(endpoint)
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the bidders resource under which the endpoint exists. This will be ' \
      'used to construct the name used as a path parameter for the endpoints.get request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'endpoint_id',
      'The resource ID of the endpoints resource that is being retrieved. This will be used to '\
      'construct the name used as a path parameter for the endpoints.get request.',
      type: Integer, short_alias: 'e', required: true, default_value: nil
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    get_endpoints(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

Retrieve a list of endpoints

The following code demonstrates how a bidder can retrieve a list of all their registered real-time bidding endpoints with bidders.endpoints.list.

REST

Request

GET https://realtimebidding.googleapis.com/v1/bidders/12345678/endpoints?pageSize=50&alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json

Response

{
  "endpoints": [
    {
      "bidProtocol": "GOOGLE_RTB",
      "name": "bidders/12345678/endpoints/16",
      "tradingLocation": "US_EAST",
      "url": "https://test.testendpoint.com/testbidder"
    }
  ]
}

C#

/* 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.
 */

using Google.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Bidders.Endpoints
{
    /// <summary>
    /// Lists endpoints for the given bidder's account ID.
    /// </summary>
    public class ListEndpoints : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public ListEndpoints()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "This code example lists all endpoints for the given bidder account.";
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            string[] requiredOptions = new string[] {"account_id"};
            bool showHelp = false;
            string accountId = null;
            int? pageSize = null;

            OptionSet options = new OptionSet {
                "List all endpoints for the given bidder account.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the bidders resource under which the " +
                     "endpoint exists. This will be used to construct the parent used as  path " +
                     "parameter for the endpoints.list request."),
                    a => accountId =  a
                },
                {
                    "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["page_size"] = 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 parent = $"bidders/{accountId}";
            string pageToken = null;

            Console.WriteLine(@"Listing endpoints for bidder account ""{0}""", accountId);
            do
            {
                BiddersResource.EndpointsResource.ListRequest request = rtbService.Bidders.Endpoints.List(parent);
                request.PageSize = (int) parsedArgs["page_size"];
                request.PageToken = pageToken;

                ListEndpointsResponse page = null;

                try
                {
                    page = request.Execute();
                }
                catch (System.Exception exception)
                {
                    throw new ApplicationException(
                        $"Real-time Bidding API returned error response:\n{exception.Message}");
                }

                var endpoints = page.Endpoints;
                pageToken = page.NextPageToken;

                if(endpoints == null)
                {
                    Console.WriteLine("No endpoints found.");
                }
                else
                {
                    foreach (Endpoint endpoint in endpoints)
                        {
                            Utilities.PrintEndpoint(endpoint);
                        }
                }
            }
            while(pageToken != null);
        }
    }
}

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.
 */

package com.google.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders.endpoints;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.Endpoint;
import com.google.api.services.realtimebidding.v1.model.ListEndpointsResponse;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;

/**
 * This sample illustrates how to list endpoints for the given bidder's account ID.
 */
public class ListEndpoints {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) {
    Integer accountId = parsedArgs.getInt("account_id");
    String parent = String.format("bidders/%s", accountId);
    Integer pageSize = parsedArgs.getInt("page_size");
    String pageToken = null;

    System.out.printf("Listing endpoints for bidder account '%s':\n", accountId);

    do {
      List<Endpoint> endpoints = null;

      try {
        ListEndpointsResponse response = client.bidders().endpoints().list(parent)
            .setPageSize(pageSize)
            .setPageToken(pageToken)
            .execute();

        endpoints = response.getEndpoints();
        pageToken = response.getNextPageToken();
      } catch(IOException ex) {
        System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
        System.exit(1);
      }
      if (endpoints == null) {
        System.out.println("No endpoints found.");
      } else {
        for(Endpoint endpoint: endpoints) {
          Utils.printEndpoint(endpoint);
        }
      }
    } while (pageToken != null);
  }

  public static void main(String[] args) {
    ArgumentParser parser = ArgumentParsers.newFor("ListBidders").build()
        .defaultHelp(true)
        .description("Lists endpoints for the given bidder account.");
    parser.addArgument("-a", "--account_id")
        .help("The resource ID of the bidders resource under which the endpoint exists. This " +
            "will be used to construct the name used as a path parameter for the endpoints.list " +
            "request.")
        .required(true)
        .type(Integer.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);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding 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);
  }
}

PHP

<?php

/**
 * 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.
 */

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Bidders_Endpoints;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;

/**
 * This example illustrates how to list a bidder's endpoints.
 */
class ListEndpoints extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Account ID',
                'required' => true,
                'description' =>
                    'The resource ID of the bidders resource under which the endpoint exists. ' .
                    'This will be used to construct the name used as a path parameter for the ' .
                    'endpoints.list request.'
            ],
            [
                'name' => 'page_size',
                'display' => 'Page size',
                'required' => false,
                'description' =>
                    'The number of rows to return per page. The server may return fewer rows ' .
                    'than specified.',
                'default' => 10
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;

        $parentName = "bidders/$values[account_id]";

        $queryParams = [
            'pageSize' => $values['page_size']
        ];

        $result = $this->service->bidders_endpoints->listBiddersEndpoints($parentName, $queryParams);

        print "<h2>Endpoints found for '$parentName':</h2>";
        if (empty($result['endpoints'])) {
            print '<p>No Endpoints found</p>';
        } else {
            foreach ($result['endpoints'] as $endpoint) {
                $this->printResult($endpoint);
            }
        }
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'List Endpoints';
    }
}

Python

#!/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.

"""Lists endpoints for the given bidder's account ID."""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_BIDDER_NAME_TEMPLATE = 'bidders/%s'

DEFAULT_BIDDER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE'


def main(realtimebidding, args):
  account_id = args.account_id
  page_size = args.page_size

  page_token = None
  more_pages = True

  print(f'Listing endpoints for bidder account: "{account_id}".')

  while more_pages:
    try:
      # Construct and execute the request.
      response = realtimebidding.bidders().endpoints().list(
          parent=_BIDDER_NAME_TEMPLATE % account_id, pageToken=page_token,
          pageSize=page_size).execute()
    except HttpError as e:
      print(e)
      sys.exit(1)

    pprint.pprint(response if response else 'No endpoints found.')

    page_token = response.get('nextPageToken')
    more_pages = bool(page_token)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print(f'Unable to create realtimebidding service - {ex}')
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Lists endpoints for the given bidder account.'))

  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BIDDER_RESOURCE_ID,
      help=('The resource ID of the bidders resource under which the '
            'endpoint exists. This will be used to construct the parent used '
            'as a path parameter for the endpoints.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.'))

  args = parser.parse_args()

  main(service, args)


Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2021 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.
#
# Lists endpoints for the given bidder's account ID.

require 'optparse'

require_relative '../../../util'


def list_endpoints(realtimebidding, options)
  parent = "bidders/#{options[:account_id]}"
  page_size = options[:page_size]

  page_token = nil

  puts "Listing endpoints for bidder with name: '#{parent}'"
  begin
    response = realtimebidding.list_bidder_endpoints(
        parent, page_size: page_size, page_token: page_token
    )

    page_token = response.next_page_token

    unless response.endpoints.nil?
      response.endpoints.each do |endpoint|
        print_endpoint(endpoint)
      end
    else
      puts 'No endpoints found.'
    end
  end until page_token == nil
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the bidders resource under which the endpoints exist. This will be ' \
      'used to construct the parent used as a path parameter for the endpoints.list request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'page_size', 'The number of rows to return per page. The server may return fewer rows than specified.',
      type: Array, short_alias: 'u', required: false, default_value: MAX_PAGE_SIZE
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    list_endpoints(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end