Existem duas APIs do Authorized Buyers:
- API Real-time Bidding (mais recente)
- API Ad Exchange Buyer II
Essas APIs permitem que seus apps interajam com o Authorized Buyers para:
- Acesse informações de contas de lances em tempo real
- Enviar e gerenciar criativos em revisão
- Recuperar métricas de solução de problemas de lances em tempo real
- Gerenciar listas de usuários
- Gerenciar configurações de pré-segmentação
- Configurar o acesso do cliente ao Marketplace
- Descobrir e gerenciar propostas para as transações no Marketplace
Caso você não conheça os conceitos do Authorized Buyers, acesse a Central de Ajuda do Authorized Buyers e teste a IU.
Preparar para autorização
Conclua as etapas a seguir para se preparar para a autenticação usando o OAuth 2.0. A API é compatível com muitos tipos de credenciais. Para este exemplo, usaremos uma conta de serviço.
Acesse a página APIs ativadas pelo Console de APIs do Google.
Na lista suspensa do projeto, selecione um projeto ou crie um novo.
Na lista de APIs ativadas, confira se a API Buyer do Ad Exchange está listada. Se ela não estiver na lista, clique na guia APIs do Google, pesquise e selecione a API Buyer do Ad Exchange e clique em Ativar API.
Em seguida, na barra lateral à esquerda, selecione Credenciais.
Selecione o menu suspenso Criar credenciais e escolha Chave da conta de serviço.
No menu suspenso Conta de serviço, escolha Nova conta de serviço.
Insira um Nome para a conta de serviço. O ID da conta de serviço é gerado automaticamente a partir do nome e do projeto.
Anote o ID da conta de serviço: você precisará dele para conceder acesso à nova conta de serviço na IU do Authorized Buyers na etapa 11.
Escolha um Tipo de chave, o arquivo JSON recomendado, ou P12, se a compatibilidade com versões anteriores do código usando o formato P12 for necessária.
Clique em Criar. O arquivo JSON ou P12 com o par de chaves públicas/privadas da conta é salvo na sua pasta "Downloads". Mantenha o arquivo JSON ou P12 gerado em um local seguro.
Você precisa conceder acesso à conta de serviço na IU do Authorized Buyers para que ela funcione. Selecione Configurações > Configurações da conta, escolha Gerenciamento de usuários > Usuários da conta e clique em +Conta de serviço. Insira o ID da conta de serviço que você anotou na etapa 8. Isso cria um novo usuário com o papel da conta de serviço.
Escopos do OAuth
Ao percorrer o fluxo de autorização do OAuth 2.0, seu aplicativo pode especificar escopos para indicar que pretende acessar determinados recursos nas APIs do Google para uma determinada Conta do Google. Para acessar qualquer uma das APIs do Authorized Buyers em nome de uma conta do Authorized Buyers, especifique o escopo associado à API que você pretende usar.
API Marketplace
Veja a seguir os escopos usados para acessar a API Marketplace:
Escopo | Significado |
---|---|
https://www.googleapis.com/auth/authorized-buyers-marketplace |
Acesso de leitura e gravação. |
API Real-time Bidding
Veja a seguir os escopos usados para acessar a API Real-time Bidding:
Escopo | Significado |
---|---|
https://www.googleapis.com/auth/realtime-bidding |
Acesso de leitura e gravação. |
API Ad Exchange Buyer II
Veja abaixo os escopos usados para acessar a API Buyer 2 do Ad Exchange:
Escopo | Significado |
---|---|
https://www.googleapis.com/auth/adexchange.buyer |
Acesso de leitura e gravação. |
Fazer uma chamada de API
Veja algumas amostras que você pode usar para dar os primeiros passos nos nossos idiomas compatíveis:
API Marketplace
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.marketplace.v1; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplace; import com.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplaceScopes; import com.google.api.services.authorizedbuyersmarketplace.v1.model.Client; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; import java.io.FileInputStream; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Set; /** * A sample application that authenticates and runs a request against the Authorized Buyers * Marketplace API. */ public class FirstApiRequest { /** * Be sure to specify the name of your application. If the application name is {@code null} or * blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0". */ private static final String APPLICATION_NAME = "APPLICATION_NAME_HERE"; // Full path to JSON Key file - include file name. private static final java.io.File JSON_FILE = new java.io.File("INSERT_PATH_TO_JSON_FILE"); // Name of the buyer resource for which the API call is being made. private static final String BUYER_NAME = "INSERT_BUYER_RESOURCE_NAME"; // Global instance of the HTTP transport. private static HttpTransport httpTransport; // Global instance of the JSON factory. private static final JsonFactory jsonFactory = GsonFactory.getDefaultInstance(); public static void main(String[] args) throws Exception { // Create credentials using the JSON key file. GoogleCredentials credentials = null; try (FileInputStream serviceAccountStream = new FileInputStream((JSON_FILE))) { Set<String> scopes = new HashSet<>(AuthorizedBuyersMarketplaceScopes.all()); credentials = ServiceAccountCredentials.fromStream(serviceAccountStream).createScoped(scopes); } catch (IOException ex) { System.out.println("Can't complete authorization step. Did you specify a JSON key file?"); System.out.println(ex); System.exit(1); } HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // Use the credentials to create a client for the API service. AuthorizedBuyersMarketplace marketplaceClient = new AuthorizedBuyersMarketplace.Builder(httpTransport, jsonFactory, requestInitializer) .setApplicationName(APPLICATION_NAME) .build(); // Call the buyers.clients.list method to get a list of clients for the given buyer. List<Client> clients = marketplaceClient.buyers().clients().list(BUYER_NAME).execute().getClients(); if (clients != null && clients.size() > 0) { System.out.printf("Listing of clients associated with buyer \"%s\"%n", BUYER_NAME); for (Client client : clients) { System.out.printf("* Client name: %s\n", client.getName()); } } else { System.out.printf( "No clients were found that were associated with buyer \"%s\"%n.", BUYER_NAME); } } }
Python
#!/usr/bin/python # # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Sample application that authenticates and makes an API request.""" import pprint from googleapiclient.discovery import build from google.oauth2 import service_account # A Service Account key file can be generated via the Google Developers # Console. KEY_FILE = 'PATH_TO_JSON_KEY_FILE' # Path to Service Account JSON key file. # Authorized Buyers Marketplace API authorization scope. SCOPE = 'https://www.googleapis.com/auth/authorized-buyers-marketplace' VERSION = 'v1' # Version of Authorized Buyers Marketplace API to use. # Name of the buyer resource for which the API call is being made. BUYER_NAME = 'BUYER_RESOURCE_NAME' def main(): # Create credentials using the Service Account JSON key file. credentials = service_account.Credentials.from_service_account_file( KEY_FILE, scopes=[SCOPE]) # Build a client for the authorizedbuyersmarketplace API service. marketplace = build('authorizedbuyersmarketplace', VERSION, credentials=credentials) # Call the buyers.clients.list method to get a list of clients for the # given buyer. request = marketplace.buyers().clients().list(parent=BUYER_NAME) pprint.pprint(request.execute()) if __name__ == '__main__': main()
.NET
/* Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied * See the License for the specific language governing permissions and * limitations under the License. */ using Google.Apis.AuthorizedBuyersMarketplace.v1; using Google.Apis.AuthorizedBuyersMarketplace.v1.Data; using Google.Apis.Auth.OAuth2; using Google.Apis.Json; using Google.Apis.Services; using System; using System.Collections.Generic; namespace Google.Apis.AuthorizedBuyersMarketplace.Examples.v1 { /// <summary> /// Self contained sample to return a list of clients for a given buyer account. /// Primarily used by the Getting Started guide: /// https://developers.google.com/authorized-buyers/apis/getting_started /// /// Note: To run this sample, you will need to configure it as the StartupObject in /// Google.Apis.AuthorizedBuyersMarketplace.Examples.csproj. /// </summary> internal class FirstApiRequest { private static void Main(string[] args) { // See the README.md for details of these fields. // Retrieved from https://console.developers.google.com var ServiceKeyFilePath = "PATH TO JSON KEY FILE HERE"; // Name of the buyer resource for which the API call is being made. var buyerName = "INSERT_BUYER_RESOURCE_NAME_HERE"; // Retrieve credential parameters from the key JSON file. var credentialParameters = NewtonsoftJsonSerializer.Instance .Deserialize<JsonCredentialParameters>( System.IO.File.ReadAllText(ServiceKeyFilePath)); // Create the credentials. var credentialInitializer = new ServiceAccountCredential.Initializer( credentialParameters.ClientEmail) { Scopes = new[] { AuthorizedBuyersMarketplaceService.Scope.AuthorizedBuyersMarketplace } }.FromPrivateKey(credentialParameters.PrivateKey); var oAuth2Credentials = new ServiceAccountCredential(credentialInitializer); // Use the credentials to create a client for the API service. var serviceInitializer = new BaseClientService.Initializer { HttpClientInitializer = oAuth2Credentials, ApplicationName = "FirstAPICall" }; var mkService = new AuthorizedBuyersMarketplaceService(serviceInitializer); // Call the buyers.clients.list method to list clients for the given buyer. BuyersResource.ClientsResource.ListRequest request = mkService.Buyers.Clients.List(buyerName); IList<Client> clients = request.Execute().Clients; foreach (Client client in clients) { Console.WriteLine("* Client name: {0}", client.Name); } Console.ReadLine(); } } }
PHP
<?php /** * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Sample application that authenticates and makes an API request. */ namespace Google\Ads\AuthorizedBuyers\Marketplace\Examples\V1; /** * Provide path to client library. See README.md for details. */ require_once __DIR__ . '/../../vendor/autoload.php'; use Google_Client; use Google_Service_AuthorizedBuyersMarketplace; session_start(); /** * You can retrieve this file from the Google Developers Console. * * See README.md for details. */ $keyFileLocation = "INSERT_PATH_TO_JSON_KEYFILE"; /** * Name of the buyer resource for which the API call is being made. */ $buyerName = "INSERT_BUYER_RESOURCE_NAME"; if ($keyFileLocation === 'INSERT_PATH_TO_JSON_KEYFILE') { print "WARNING: Authorization details not provided!\n"; exit(1); } $client = new Google_Client(); $client->setApplicationName('Authorized Buyers Marketplace API PHP Samples'); $service = new Google_Service_AuthorizedBuyersMarketplace($client); $client->setAuthConfig($keyFileLocation); $client->addScope('https://www.googleapis.com/auth/authorized-buyers-marketplace'); if ($client->isAccessTokenExpired()) { $client->refreshTokenWithAssertion(); } if ($client->getAccessToken()) { // Call the buyers.clients.list method to get a list of clients for the given buyer. $result = $service->buyers_clients->listBuyersClients($buyerName); print "Clients associated with buyer account\n"; if (empty($result['clients'])) { print "No clients found\n"; return; } else { foreach ($result['clients'] as $client) { print_r($client); } } }
Ruby
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright:: Copyright 2022 Google LLC # # License:: Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # Sample application that authenticates and makes an API request. require 'google/apis/authorizedbuyersmarketplace_v1' require 'googleauth/service_account' # You can download the JSON keyfile used for authentication from the Google # Developers Console. KEY_FILE = 'path_to_key' # Path to JSON file containing your private key. # Name of the buyer resource for which the API call is being made. BUYER_NAME = 'insert_buyer_resource_name' def first_api_request() # Create credentials using the JSON key file. auth_options = { :json_key_io => File.open(KEY_FILE, "r"), :scope => 'https://www.googleapis.com/auth/authorized-buyers-marketplace' } oauth_credentials = Google::Auth::ServiceAccountCredentials.make_creds( options=auth_options ) # Create the service and set credentials marketplace = ( Google::Apis::AuthorizedbuyersmarketplaceV1::AuthorizedBuyersMarketplaceService.new ) marketplace.authorization = oauth_credentials marketplace.authorization.fetch_access_token! begin # Call the buyers.clients.list method to get list of clients for given buyer. clients_list = marketplace.list_buyer_clients(BUYER_NAME) if clients_list.clients.any? puts "Found the following clients for buyer '%s':" % BUYER_NAME clients_list.clients.each do |client| puts "* Client name: #{client.name}" end else puts "No clients were found that were associated with buyer '%s'" % BUYER_NAME end rescue Google::Apis::ServerError => e raise "The following server error occured:\n%s" % e.message rescue Google::Apis::ClientError => e raise "Invalid client request:\n%s" % e.message rescue Google::Apis::AuthorizationError => e raise "Authorization error occured:\n%s" % e.message end end if __FILE__ == $0 begin first_api_request() end end
API Real-time Bidding
Java
Veja um exemplo básico que mostra como usar a API Real-time Bidding com Java.
- Criar um projeto do Maven
Abra o arquivo pom.xml e adicione estas dependências:
<dependencies> <dependency> <groupId>com.google.api-client</groupId> <artifactId>google-api-client</artifactId> <version>1.32.2</version> </dependency> <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-pubsub</artifactId> <version>v1-rev452-1.25.0</version> </dependency> <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-realtimebidding</artifactId> <version>v1-rev20220503-1.32.1</version> </dependency> <dependency> <groupId>com.google.auth</groupId> <artifactId>google-auth-library-oauth2-http</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.9</version> </dependency> <dependency> <groupId>com.google.http-client</groupId> <artifactId>google-http-client-jackson2</artifactId> <version>1.40.1</version> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.10.13</version> </dependency> <dependency> <groupId>net.sourceforge.argparse4j</groupId> <artifactId>argparse4j</artifactId> <version>0.9.0</version> </dependency> </dependencies>
- Configurar suas credenciais
Todas as chamadas para a API exigem autenticação. Crie um
Credential
usando o arquivo de chave JSON da conta de serviço discutido acima.GoogleCredentials credentials = null; try (FileInputStream serviceAccountStream = new FileInputStream((JSON_FILE))) { Set<String> scopes = new HashSet<>(RealTimeBiddingScopes.all()); credentials = ServiceAccountCredentials.fromStream(serviceAccountStream).createScoped(scopes); } catch (IOException ex) { System.out.println("Can't complete authorization step. Did you specify a JSON key file?"); System.out.println(ex); System.exit(1); }
- Criar um cliente para a API Real-time Bidding
É possível criar o cliente da API Real-time Bidding usando o padrão Builder:
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // Use the credentials to create a client for the API service. RealTimeBidding realtimeBidding = new RealTimeBidding.Builder(httpTransport, jsonFactory, requestInitializer) .setApplicationName(APPLICATION_NAME) .build();
. - Realizar uma operação
Depois de instanciar um cliente para se conectar à API, é possível executar uma operação. O código a seguir retorna todos os criativos de um determinado comprador.
List<Creative> creatives = realtimeBidding .buyers() .creatives() .list(BUYER_NAME) .setView("FULL") .execute() .getCreatives(); if (creatives != null && creatives.size() > 0) { System.out.printf("Listing of creatives associated with buyer '%s'%n", BUYER_NAME); for (Creative creative : creatives) { System.out.printf("* Creative name: %s\n", creative.getName()); } } else { System.out.printf( "No creatives were found that were associated with buyer '%s'%n.", BUYER_NAME); }
Para informações mais detalhadas sobre como usar a API Real-time Bidding com Java, consulte o arquivo README nos exemplos da API Real-time Bidding.
Python
Veja um exemplo básico que mostra como usar a API de lances em tempo real com Python.
- Faça o download e instale o cliente Python da API do Google
Exemplo de uso do pip:
$ pip install --upgrade google-api-python-client
- Configurar suas credenciais
Todas as chamadas para a API exigem autenticação. Instancie uma instância
service_account.Credentials
usando o arquivo de chave JSON da conta de serviço discutido acima.credentials = service_account.Credentials.from_service_account_file( KEY_FILE, scopes=[SCOPE])
- Criar um cliente para a API Real-time Bidding
Em seguida, crie o cliente da API Real-time Bidding usando a instância
service_account.Credentials
autorizada:realtimebidding = build('realtimebidding', VERSION, credentials=credentials)
- Realizar uma operação
Depois de instanciar um cliente para se conectar à API, é possível executar uma operação. O código a seguir retorna todos os criativos de um determinado comprador.
request = realtimebidding.buyers().creatives().list(parent=BUYER_NAME) pprint.pprint(request.execute())
Para informações mais detalhadas sobre como usar a API Buyer do Ad Exchange com Python, consulte o arquivo README nos exemplos da API de lance em tempo real.
PHP
Veja um exemplo básico que mostra como usar a API Real-time Bidding com o PHP.
- Configurar dependências
Se você ainda não o instalou, faça o download e instale o Composer. Em seguida, crie um composer.json com um conteúdo como este:
{ "description": "Authorized Buyers Real-Time Bidding API PHP Samples", "require": { "php": ">=7.2", "google/apiclient": "^2.0" }, "require-dev": { "squizlabs/php_codesniffer": "3.*" }, "type": "project", "homepage": "https://github.com/googleads/authorized-buyers-rtb-api-samples/tree/master/php", "license": "Apache-2.0", "authors": [ { "name": "Google", "homepage": "https://github.com/googleads/authorized-buyers-rtb-api-samples/graphs/contributors" } ] }
Por fim, execute o seguinte para instalar bibliotecas de dependência:
composer install
- Configurar um cliente
Crie uma
Google_Client
e use-a para instanciarGoogle_Service_RealTimeBidding
.$client = new Google_Client(); $client->setApplicationName('Authorized Buyers Real-time Bidding API PHP Samples'); $service = new Google_Service_RealTimeBidding($client);
- Configurar suas credenciais
Todas as chamadas para a API exigem um token de acesso válido. Configure o cliente para seguir o fluxo do OAuth 2.0.
$client->setAuthConfig($keyFileLocation); $client->addScope('https://www.googleapis.com/auth/realtime-bidding'); if ($client->isAccessTokenExpired()) { $client->refreshTokenWithAssertion(); }
- Realizar uma operação
Depois de instanciar um cliente para se conectar à API e configurar o OAuth 2.0, é possível usá-lo para fazer uma chamada da API. O código a seguir retorna todos os criativos de um determinado comprador:
$result = $service->buyers_creatives->listBuyersCreatives($buyerName, $queryParams); print "Creatives associated with buyer account\n"; if (empty($result['creatives'])) { print "No creatives found\n"; return; } else { foreach ($result['creatives'] as $creative) { print_r($creative); } }
Para informações mais detalhadas sobre como usar a API de comprador do Ad Exchange com PHP, consulte o arquivo README nos exemplos da API de lance em tempo real.
.NET
Veja um exemplo básico que mostra como usar a API Real-time Bidding com C#.
- Criar um novo projeto
Abra o código do Visual Studio e crie um novo projeto.
- Adicionar referências de biblioteca necessárias ao seu projeto
No arquivo *.csproj do seu projeto, adicione uma entrada
PackageReference
paraGoogle.Apis
,Google.Apis.Auth
,Google.Apis.Core
,Google.Apis.Oauth2.v2
eGoogle.Apis.RealTimeBidding.v1
. Veja um exemplo:<ItemGroup> <PackageReference Include="Google.Apis" Version="1.57.0" /> <PackageReference Include="Google.Apis.Auth" Version="1.57.0" /> <PackageReference Include="Google.Apis.Core" Version="1.57.0" /> <PackageReference Include="Google.Apis.Oauth2.v2" Version="1.57.0.1869" /> <PackageReference Include="Google.Apis.Pubsub.v1" Version="1.57.0.2667" /> <PackageReference Condition="!Exists('./Google.Apis.RealTimeBidding.v1.csproj')" Include="Google.Apis.RealTimeBidding.v1" Version="1.57.0.2680" /> <PackageReference Include="log4net" Version="2.0.13" /> <PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.4" /> <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference> <PackageReference Include="Mono.Options" Version="6.12.0.148" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> </ItemGroup>
Veja mais informações sobre essas dependências em: https://www.nuget.org/packages/ (link em inglês).
- Configurar suas credenciais
Todas as chamadas para a API exigem autenticação. Crie um
Credential
usando o e-mail da conta de serviço e o arquivo JSON discutido acima.var credentialParameters = NewtonsoftJsonSerializer.Instance .Deserialize<JsonCredentialParameters>( System.IO.File.ReadAllText(ServiceKeyFilePath)); // Create the credentials. var credentialInitializer = new ServiceAccountCredential.Initializer( credentialParameters.ClientEmail) { Scopes = new[] { RealTimeBiddingService.Scope.RealtimeBidding } }.FromPrivateKey(credentialParameters.PrivateKey); var oAuth2Credentials = new ServiceAccountCredential(credentialInitializer);
- Criar um cliente para a API Real-time Bidding
Em seguida, crie seu
RealTimeBiddingService
:var serviceInitializer = new BaseClientService.Initializer { HttpClientInitializer = oAuth2Credentials, ApplicationName = "FirstAPICall" }; var realtimebidding = new RealTimeBiddingService(serviceInitializer);
- Realizar uma operação
Depois de instanciar um cliente para se conectar à API, é possível executar uma operação. O código a seguir lista criativos para uma conta de comprador especificada do Authorized Buyers associada às suas credenciais.
BuyersResource.CreativesResource.ListRequest request = realtimebidding.Buyers.Creatives.List(buyerName); request.View = BuyersResource.CreativesResource.ListRequest.ViewEnum.FULL; IList<Creative> creatives = request.Execute().Creatives; foreach (Creative creative in creatives) { Console.WriteLine("* Creative name: {0}", creative.Name); }
Para informações mais detalhadas sobre o uso da API Real-time Bidding com C#, consulte o arquivo README nos exemplos da API Real-time Bidding.
Ruby
Veja um exemplo básico que mostra como usar a API Real-time Bidding com Ruby.
- Fazer o download e instalar o cliente Ruby da API do Google
Se você ainda não o instalou, faça o download e instale o Bundler. Em seguida, crie um Gemfile com conteúdo como este:
source "https://rubygems.org" ruby "2.6.0" gem 'google-apis-pubsub_v1', '0.10.0' gem 'google-apis-realtimebidding_v1', '~> 0.14.0'
Por fim, execute o seguinte para instalar bibliotecas de dependência:
bundle
- Configurar suas credenciais
Todas as chamadas para a API exigem autenticação. Crie credenciais usando o e-mail da conta de serviço e o arquivo JSON discutido acima.
# Create credentials using the JSON key file. auth_options = { :json_key_io => File.open(KEY_FILE, "r"), :scope => 'https://www.googleapis.com/auth/realtime-bidding' } oauth_credentials = Google::Auth::ServiceAccountCredentials.make_creds( options=auth_options )
- Criar um cliente para o RHELBuyer
Em seguida, crie o cliente autorizado do comprador do RHEL usando as credenciais:
# Create the service and set credentials realtimebidding = ( Google::Apis::RealtimebiddingV1::RealtimeBiddingService.new ) realtimebidding.authorization = oauth_credentials realtimebidding.authorization.fetch_access_token!
- Realizar uma operação
Depois de instanciar um cliente para se conectar à API, é possível executar uma operação. O código a seguir retorna todos os criativos de um determinado comprador.
# Call the buyers.creatives.list method to get list of creatives for given buyer. creatives_list = realtimebidding.list_buyer_creatives( BUYER_NAME, view: 'FULL') if creatives_list.creatives.any? puts "Found the following creatives for buyer '%s':" % BUYER_NAME creatives_list.creatives.each do |creative| puts "* Creative name: #{creative.name}" end else puts "No creatives were found that were associated with buyer '%s'" % BUYER_NAME end
Para informações mais detalhadas sobre como usar a API Real-time Bidding com Ruby, consulte o arquivo README nos exemplos da API Real-time Bidding.
API Ad Exchange Buyer II
Java
/* * Copyright (c) 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.services.samples.adexchangebuyer.cmdline.v2_x; import com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient; import com.google.api.services.adexchangebuyer2.v2beta1.AdExchangeBuyerII; import com.google.api.services.adexchangebuyer2.v2beta1.model.Client; import com.google.api.services.samples.adexchangebuyer.cmdline.BaseSample; import java.io.IOException; import java.util.List; /** * This sample illustrates how to retrieve all client buyers associated with a given account. * * See the <a href="Client Access Guide">https://developers.google.com/authorized-buyers/apis/guides/v2/client-access#clients</a> * for more details on the usage of this resource. */ public class GetAllClientBuyers extends BaseSample { @Override public ClientType getClientType() { return BaseSample.ClientType.ADEXCHANGEBUYERII; } @Override public String getName() { return "Get All Client Buyers"; } @Override public String getDescription() { return "Lists Client Buyers associated with the given Account."; } @Override public void execute(AbstractGoogleJsonClient client) throws IOException { AdExchangeBuyerII adXClient = (AdExchangeBuyerII) client; long accountId = getIntInput("AccountId", "Enter the Account ID"); List<Client> allClients = adXClient.accounts().clients().list(accountId).execute().getClients(); if (allClients != null && allClients.size() > 0) { System.out.println("========================================"); System.out.printf("Listing of Client Buyers associated with AdX Account \"%s\"%n", accountId); System.out.println("========================================"); for (Client clientBuyer : allClients) { System.out.printf("Client Account ID: %s%n", clientBuyer.getClientAccountId()); System.out.printf("\tClient Name: %s%n", clientBuyer.getClientName()); System.out.printf("\tEntity ID: %s%n", clientBuyer.getEntityId()); System.out.printf("\tEntity Name: %s%n", clientBuyer.getEntityName()); System.out.printf("\tEntity Type: %s%n", clientBuyer.getEntityType()); System.out.printf("\tRole: %s%n", clientBuyer.getRole()); System.out.printf("\tStatus: %s%n", clientBuyer.getStatus()); } } else { System.out.println("No Client Buyers were found associated to this Account."); } } }
Python
#!/usr/bin/python # # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example lists the client buyers for a given account.""" import argparse import pprint import os import sys sys.path.insert(0, os.path.abspath('..')) from googleapiclient.errors import HttpError import samples_util DEFAULT_ACCOUNT_ID = 'ENTER_ACCOUNT_ID_HERE' def main(ad_exchange_buyer, account_id): try: # Construct and execute the request. clients = ad_exchange_buyer.accounts().clients().list( accountId=account_id).execute() print(f'Client buyers for account ID: "{account_id}"') pprint.pprint(clients) except HttpError as e: print(e) if __name__ == '__main__': parser = argparse.ArgumentParser( description='Lists client buyers for a given Authorized Buyers account.') parser.add_argument( '-a', '--account_id', default=DEFAULT_ACCOUNT_ID, type=int, help='The integer id of the Authorized Buyers account.') args = parser.parse_args() try: service = samples_util.GetService('v2beta1') except IOError as ex: print(f'Unable to create adexchangebuyer service - {ex}') print('Did you specify the key file in samples_util.py?') sys.exit(1) main(service, args.account_id)
PHP
<?php /** * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ require_once __DIR__ . '/../../BaseExample.php'; /** * This example illustrates how to retrieve all buyer clients associated * with a given account. */ class ListClientBuyers extends BaseExample { /** * @see BaseExample::getInputParameters() */ protected function getInputParameters() { return [ [ 'name' => 'accountId', 'display' => 'Account ID', 'required' => true ] ]; } /** * @see BaseExample::run() */ public function run() { $values = $this->formValues; $result = $this->service->accounts_clients->listAccountsClients( $values['accountId']); print '<h2>Listing buyer clients</h2>'; if (empty($result['clients'])) { print '<p>No buyer clients found</p>'; return; } else { foreach ($result['clients'] as $clients) { $this->printResult($clients); } } } /** * @see BaseExample::getClientType() */ public function getClientType() { return ClientType::AdExchangeBuyerII; } /** * @see BaseExample::getName() */ public function getName() { return 'Client Access: List Client Buyers'; } }
.NET
/* Copyright 2016, Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied * See the License for the specific language governing permissions and * limitations under the License. */ using Google.Apis.AdExchangeBuyerII.v2beta1; using Google.Apis.AdExchangeBuyerII.v2beta1.Data; using Google.Apis.Services; using System; namespace Google.Apis.AdExchangeBuyer.Examples.v2_x { /// <summary> /// Retrieves the authenticated user's list of client buyers for the given account ID. /// </summary> public class ListClientBuyers : ExampleBase { /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments</param> public static void Main(string[] args) { AdExchangeBuyerIIService service = Utilities.GetV2Service(); ExampleBase example = new ListClientBuyers(); Console.WriteLine(example.Description); example.Run(service); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example lists all client buyers for a given account ID."; } } /// <summary> /// Runs the code example. /// </summary> /// <param name="service">An authenticated AdExchangeBuyerIIService</param> public override void Run(BaseClientService service) { AdExchangeBuyerIIService adXService = (AdExchangeBuyerIIService)service; long accountId = long.Parse("INSERT ACCOUNT ID HERE"); ListClientsResponse response = adXService.Accounts.Clients.List(accountId).Execute(); Console.WriteLine("========================================\n"); Console.WriteLine("Listing of client buyers associated with Authorized Buyers " + "Account \"{0}\"", accountId); Console.WriteLine("========================================\n"); if (response.Clients.Count == 0) { Console.WriteLine("No client buyers found."); } else { foreach (Client clientBuyer in response.Clients) { Console.WriteLine("Client Account ID: {0}", clientBuyer.ClientAccountId); Console.WriteLine("\tClient Name: {0}", clientBuyer.ClientName); Console.WriteLine("\tEntity ID: {0}", clientBuyer.EntityId); Console.WriteLine("\tEntity Name: {0}", clientBuyer.EntityName); Console.WriteLine("\tEntity Type: {0}", clientBuyer.EntityType); Console.WriteLine("\tRole: {0}", clientBuyer.Role); Console.WriteLine("\tStatus: {0}", clientBuyer.Status); } } } public override ClientType getClientType() { return ClientType.ADEXCHANGEBUYERII; } } }
Ruby
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright:: Copyright 2016, Google Inc. All Rights Reserved. # # License:: Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # Lists the client buyers for a given account. # # To get Account IDs, run list_accounts.rb. # # Tags: Accounts.Clients.list require 'optparse' require_relative '../samples_util' def list_client_buyers(ad_exchange_buyer, account_id, page_size) begin client_buyers = ad_exchange_buyer.list_account_clients( account_id, page_size: page_size ) if !client_buyers.clients.nil? puts 'Found the following client buyers for account ID %s:' % account_id client_buyers.clients.each do |client_buyer| puts '* Client account ID: %s' % client_buyer.client_account_id puts "\tClient name: %s" % client_buyer.client_name puts "\tEntity ID: %s" % client_buyer.entity_id puts "\tEntity name: %s" % client_buyer.entity_name puts "\tEntity Type: %s" % client_buyer.entity_type puts "\tRole: %s" % client_buyer.role puts "\tStatus: %s" % client_buyer.status puts "\tVisible to seller: %s" % client_buyer.visible_to_seller end else puts 'No client buyers found for account ID %s.' % account_id end rescue Google::Apis::ServerError => e raise "The following server error occured:\n%s" % e.message rescue Google::Apis::ClientError => e raise "Invalid client request:\n%s" % e.message rescue Google::Apis::AuthorizationError => e raise "Authorization error occured:\n%s" % e.message end end if __FILE__ == $0 begin # Retrieve the service used to make API requests. service = get_service(ADEXCHANGEBUYER_V2BETA1) rescue ArgumentError => e raise 'Unable to create service, with error message: %s' % e.message rescue Signet::AuthorizationError => e raise ('Unable to create service, was the KEY_FILE in samples_util.rb ' + 'set? Error message: %s') % e.message end # Set options and default values for fields used in this example. options = [ Option.new( 'account_id', 'The integer ID of the Authorized Buyers account.', :type => Integer, :short_alias => 'a', :required => true, :default_value => nil # Insert default value here. ), Option.new( 'max_page_size', 'The maximum number of entries returned on one result page.', :type => Integer, :short_alias => 'm', :required => true, :default_value => MAX_PAGE_SIZE ) ] # Parse options. parser = Parser.new(options) opts = parser.parse(ARGV) list_client_buyers(service, opts['account_id'], opts['page_size']) end
Próximas etapas
Leia o guia em segundo plano para entender melhor o que está acontecendo nas amostras e as opções disponíveis para desenvolver sua solução.
Depois de instalar uma biblioteca de cliente, tente estender os exemplos de código para atender às suas necessidades.
Acesse a documentação de referência da versão com que você está trabalhando para saber mais sobre a API.
Se precisar de ajuda, acesse o fórum.
Caso seu aplicativo precise realizar lances em tempo real, leia a documentação do protocolo de RTB.
Veja as dicas de desempenho.
Responda a uma pesquisa
Ajude-nos a melhorar esta documentação. Diga o que funcionou e o que deixamos de participar preenchendo uma pesquisa rápida.