開始使用這個 API

本文說明如何開始編寫使用 Google Bid Manager API 的應用程式。使用這個 API 即可管理查詢及擷取報表中繼資料。

Bid Manager API v2 是目前建議使用的最新版本,

1. 事前準備

如果您不熟悉 Google Display & Video 360 概念,請參閱 Display & Video 360 說明中心,並試用 UI

2. 為驗證做好準備

如要開始使用 Bid Manager API,請先使用設定工具;這項工具會逐步引導您在 Google API 控制台中建立專案、啟用 API,並建立憑證。

如果您尚未建立 OAuth 2.0 憑證,請點選「Create credentials」(建立憑證) >「OAuth client ID」(OAuth 用戶端 ID) 以建立 OAuth 2.0 憑證。建立憑證後,即可在「Credentials」(憑證) 頁面查看用戶端 ID。按一下用戶端 ID 即可查看相關詳細資料,例如用戶端密鑰、重新導向 URI、JavaScript 來源地址和電子郵件地址。

詳情請參閱授權要求

3. 呼叫 Bid Manager API

下列分頁提供使用不同語言編寫程式的快速入門導覽課程。Bid Manager API 範例存放區也提供類似的程式碼範例。

Java

  1. 匯入必要的程式庫。

    import static java.nio.charset.StandardCharsets.UTF_8;
    import com.google.api.client.auth.oauth2.Credential;
    import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
    import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
    import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
    import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
    import com.google.api.client.googleapis.util.Utils;
    import com.google.api.services.doubleclickbidmanager.DoubleClickBidManager;
    import com.google.api.services.doubleclickbidmanager.model.ListQueriesResponse;
    import com.google.api.services.doubleclickbidmanager.model.Query;
    import java.io.Reader;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    
  2. 載入用戶端密鑰檔案並產生授權憑證。

    您第一次執行這個步驟時,系統會要求您在瀏覽器中接受授權提示。接受邀請之前,請確認您登入的是可存取 Display & Video 360 的 Google 帳戶。您的應用程式將有權代表目前登入的帳戶存取資料。

    // Read client secrets file.
    GoogleClientSecrets clientSecrets;
    try (Reader reader = Files.newBufferedReader(Paths.get(path-to-client-secrets-file), UTF_8)) {
      clientSecrets = GoogleClientSecrets.load(Utils.getDefaultJsonFactory(), reader);
    }
    
    // Generate authorization credentials.
    // Set up the authorization code flow.
    GoogleAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow.Builder(
            Utils.getDefaultTransport(),
            Utils.getDefaultJsonFactory(),
            clientSecrets,
            oauth-scopes)
        .build();
    
    Credential credential =
        new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    
  3. 建立授權的 API 用戶端。

    // Create authorized API client.
    DoubleClickBidManager service =
        new DoubleClickBidManager.Builder(credential.getTransport(), credential.getJsonFactory(), credential)
            .setApplicationName("bidmanager-java-installed-app-sample")
            .build();
    
  4. 執行作業。

    // Perform an operation.
    // Call the API, getting a list of 10 queries.
    ListQueriesResponse queriesResponse = service.queries().list().setPageSize(10).execute();
    
    // Print them out.
    System.out.println("Id\t\tName");
    if (queriesResponse.getQueries().size() > 0) {
      for (int i = 0; i < queriesResponse.getQueries().size(); i++) {
        Query currentQuery = queriesResponse.getQueries().get(i);
        System.out.printf(
            "%s\t%s%n",
            currentQuery.getQueryId(),
            currentQuery.getMetadata().getTitle());
      }
    } else {
      System.out.println("No queries exist.");
    }
    

如要進一步瞭解如何搭配 Java 使用 Bid Manager API,請參閱 Bid Manager API 範例中的 README 檔案。

Python

  1. 匯入必要的程式庫。

    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient import discovery
    
  2. 載入用戶端密鑰檔案並產生授權憑證。

    您第一次執行這個步驟時,系統會要求您在瀏覽器中接受授權提示。接受邀請之前,請確認您登入的是可存取 Display & Video 360 的 Google 帳戶。您的應用程式將有權代表目前登入的帳戶存取資料。

    # Set up a flow object to create the credentials using the
    # client secrets file and OAuth scopes.
    credentials = InstalledAppFlow.from_client_secrets_file(
        path-to-client-secrets-file, oauth-scopes).run_local_server()
    
  3. 建立授權的 API 用戶端。

    # Build the discovery document URL.
    discovery_url = f'https://doubleclickbidmanager.googleapis.com/$discovery/rest?version=v2'
    
    # Build the API service.
    service = discovery.build(
        'doubleclickbidmanager',
        'v2',
        discoveryServiceUrl=discovery_url,
        credentials=credentials)
    
  4. 執行作業。

    # Build and execute queries.listqueries request.
    response = service.queries().list(pageSize='10').execute()
    
    # Print queries out.
    if 'queries' in response:
      print('Id\t\tName')
      for query in response['queries']:
        print('%s\t%s' % (query['queryId'], query['metadata']['title']))
    else:
      print('No queries exist.')
    

如要進一步瞭解如何搭配 Python 使用 Bid Manager API,請參閱 Bid Manager API 範例中的 README 檔案。

PHP

本範例假設您使用內建網路伺服器執行 PHP,且已將憑證設定為重新導向至相關網頁。舉例來說,在 index.php 檔案中的以下程式碼,可在驗證後使用設定為重新導向 http://localhost:8000 的指令和憑證執行:

php -S localhost:8000 -t ./

  1. 下載並安裝 Google API PHP 用戶端。

    建議使用的方法是使用 Composer

    composer require google/apiclient:^2.12.1
    

    安裝完成後,請務必加入自動載入器

    require_once '/path/to/your-project/vendor/autoload.php';
    

  2. 建立 Google_Client 物件。

    $client = new Google_Client();
    
  3. 設定用戶端、視需要重新導向至驗證網址,以及擷取存取權杖。

    您第一次執行這個步驟時,系統會要求您在瀏覽器中接受授權提示。接受邀請之前,請確認您登入的是可存取 Display & Video 360 的 Google 帳戶。您的應用程式將有權代表目前登入的帳戶存取資料。

    // Set up the client.
    $client->setApplicationName('DBM API PHP Samples');
    $client->addScope(oauth-scope);
    $client->setAccessType('offline');
    $client->setAuthConfigFile(path-to-client-secrets-file);
    
    // If the code is passed, authenticate. If not, redirect to authentication page.
    if (isset($_GET['code'])) {
      $client->authenticate($_GET['code']);
    } else {
      $authUrl = $client->createAuthUrl();
      header('Location: ' . $authUrl);
    }
    
    // Exchange authorization code for an access token.
    $accessToken = $client->getAccessToken();
    $client->setAccessToken($accessToken);
    
  4. 建立 Display & Video 360 API 服務的用戶端。

    $service = new Google_Service_DoubleClickBidManager($client);
    
  5. 執行作業。

    // Configure params for the Queries.listqueries request.
    $optParams = array('pageSize' => 10);
    
    // Execute the request.
    $result = $service->queries->listQueries($optParams);
    
    // Print the retrieved queries.
    if (!empty($result->getQueries())) {
      print('<pre><p>Id Name</p>');
      foreach ($result->getQueries() as $query) {
        printf('<p>%s %s</p>', $query->queryId, $query->metadata->title);
      }
      print('</pre>');
    } else {
      print '<p>No queries exist.</p>';
    }
    

如要進一步瞭解如何搭配 PHP 使用 Bid Manager API,請參閱 Bid Manager API 範例中的 README 檔案。

4. 後續步驟

現在您已成功設定並執行用戶端程式庫,請參閱參考說明文件,開始建構您的實作項目。

我們也提供其他指南,請參閱使用定期報表遵循報表最佳做法