開始使用這個 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 憑證,請依序點選「建立憑證」>「OAuth 用戶端 ID」。建立憑證後,您可以在「憑證」頁面中查看用戶端 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. 後續步驟

現在您已啟動並執行用戶端程式庫,可以開始瀏覽參考文件,並建構實作項目。

此外,您也可以參閱排定報表時間報表最佳做法的相關指南。