始める

Google Ad Manager API を使用して、広告枠の管理、オーダーの作成、レポートの作成などを行うアプリを作成できます。

Ad Manager API では SOAP が使用されます。簡単に始められるように、Java、.NET、Python、PHP、Ruby 用のクライアント ライブラリが提供されています。

最初の API リクエストを実行する手順は次のとおりです。

アド マネージャー ネットワークにアクセスする

アド マネージャー アカウントをまだお持ちでない場合は、アカウントを作成します。別の環境で API をテストする場合は、テスト ネットワークを作成することもできます。テスト目的で AdSense アカウントは必要ありません。

ネットワーク コードをメモします。この番号は、ネットワークにログインしたときに URL で確認できます。たとえば、URL https://admanager.google.com/1234#home では、1234 がネットワーク コードです。

認証情報を作成する

アド マネージャー API のリクエストはすべて、OAuth 2.0 を使用して認証する必要があります。ご自分のアド マネージャー データにアクセスする場合の手順は、次のとおりです。詳細とその他のオプションについては、認証をご覧ください。

  1. Google API Console の [認証情報] ページを開きます。

  2. プロジェクト メニューから [プロジェクトを作成] を選択し、プロジェクトの名前を入力して、必要に応じてプロジェクト ID を編集します。[作成] をクリックします。

  3. [認証情報] ページで、[認証情報を作成] を選択し、[サービス アカウント キー] を選択します。

  4. [新しいサービス アカウント] を選択し、キーのタイプとして JSON を選択します。

  5. [作成] をクリックして、秘密鍵を含むファイルをダウンロードします。

アド マネージャー ネットワークを設定する

  1. Google アド マネージャーにログインします。

  2. サイドバーで、[管理] > [全般設定] をクリックします。

  3. [全般設定] > [API アクセス] で、スライダーをクリックして [有効] にします。

  4. ページ下部にある [SAVE] ボタンをクリックします。

クライアントを設定する

アド マネージャーのクライアント ライブラリの 1 つをダウンロードします。このライブラリには、アプリの開発を迅速かつ容易にするラッパー関数と機能が用意されています。

以下のタブでは、クライアント ライブラリがある各言語のコーディングのクイックスタートを示します。

Java

Java クライアント ライブラリの使用方法を示す基本的な例を以下に紹介します。使用方法の詳細については、クライアント ライブラリ ディストリビューションの README ファイルをご覧ください。

  1. 認証情報を設定する

    シェルで次のコマンドを実行します。

    curl https://raw.githubusercontent.com/googleads/googleads-java-lib/main/examples/admanager_axis/src/main/resources/ads.properties -o ~/ads.properties
    ~/ads.properties ファイルを開き、次のフィールドに入力します。
    [...]
    api.admanager.applicationName=INSERT_APPLICATION_NAME_HERE
    api.admanager.jsonKeyFilePath=INSERT_PATH_TO_JSON_KEY_FILE_HERE
    api.admanager.networkCode=INSERT_NETWORK_CODE_HERE
    [...]
  2. 依存関係を指定する

    pom.xml ファイルを編集して、次のコードを dependencies タグに追加します。最新のバージョン番号は GitHub で入手できます。

    <dependency>
      <groupId>com.google.api-ads</groupId>
      <artifactId>ads-lib</artifactId>
      <version>RELEASE</version>
    </dependency>
    <dependency>
      <groupId>com.google.api-ads</groupId>
      <artifactId>dfp-axis</artifactId>
      <version>RELEASE</version>
    </dependency>

  3. コードを記述してリクエストを行ってください。

    import com.google.api.ads.common.lib.auth.OfflineCredentials;
    import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
    import com.google.api.ads.admanager.axis.factory.AdManagerServices;
    import com.google.api.ads.admanager.axis.v202402.Network;
    import com.google.api.ads.admanager.axis.v202402.NetworkServiceInterface;
    import com.google.api.ads.admanager.lib.client.AdManagerSession;
    import com.google.api.client.auth.oauth2.Credential;
    
    public class App {
      public static void main(String[] args) throws Exception {
        Credential oAuth2Credential = new OfflineCredentials.Builder()
            .forApi(Api.AD_MANAGER)
            .fromFile()
            .build()
            .generateCredential();
    
        // Construct an AdManagerSession.
        AdManagerSession session = new AdManagerSession.Builder()
            .fromFile()
            .withOAuth2Credential(oAuth2Credential)
            .build();
    
        // Construct a Google Ad Manager service factory, which can only be used once per
        // thread, but should be reused as much as possible.
        AdManagerServices adManagerServices = new AdManagerServices();
    
        // Retrieve the appropriate service
        NetworkServiceInterface networkService = adManagerServices.get(session,
            NetworkServiceInterface.class);
    
        // Make a request
        Network network = networkService.getCurrentNetwork();
    
        System.out.printf("Current network has network code '%s' and display" +
            " name '%s'.%n", network.getNetworkCode(), network.getDisplayName());
      }
    }
    

Python

Python クライアント ライブラリの使用方法を示す簡単な例を以下に紹介します。Python クライアント ライブラリは、Python v3.6 以降をサポートしています。使用方法の詳細については、クライアント ライブラリ ディストリビューションの README ファイルをご覧ください。

  1. ライブラリをインストールして認証情報を設定します。

    シェルで次のコマンドを実行します。

    pip install googleads
    curl https://raw.githubusercontent.com/googleads/googleads-python-lib/main/googleads.yaml \
         -o ~/googleads.yaml
    
  2. ~/googleads.yaml ファイルを設定します。

    次のフィールドに値を入力します。

    ad_manager:
      application_name: INSERT_APPLICATION_NAME_HERE
      network_code: INSERT_NETWORK_CODE_HERE
      path_to_private_key_file: INSERT_PATH_TO_FILE_HERE
    
  3. コードを実行してリクエストします。
    # Import the library.
    from googleads import ad_manager
    
    # Initialize a client object, by default uses the credentials in ~/googleads.yaml.
    client = ad_manager.AdManagerClient.LoadFromStorage()
    
    # Initialize a service.
    network_service = client.GetService('NetworkService', version='v202402')
    
    # Make a request.
    current_network = network_service.getCurrentNetwork()
    
    print("Current network has network code '%s' and display name '%s'." %
            (current_network['networkCode'], current_network['displayName']))
    

PHP

PHP クライアント ライブラリの使用方法を示す基本的な例を次に示します。

  1. ライブラリをインストールして認証情報を設定します。

    シェルで次のコマンドを実行してクライアント ライブラリをインストールし、adsapi_php.ini ファイルをホーム ディレクトリにダウンロードします。

    composer require googleads/googleads-php-lib
    curl https://raw.githubusercontent.com/googleads/googleads-php-lib/main/examples/AdManager/adsapi_php.ini -o ~/adsapi_php.ini
  2. ~/adsapi_php.ini ファイルを設定します。

    次のフィールドに値を入力します。

    [AD_MANAGER]
    networkCode = "INSERT_NETWORK_CODE_HERE"
    applicationName = "INSERT_APPLICATION_NAME_HERE"
    
    [OAUTH2]
    jsonKeyFilePath = "INSERT_ABSOLUTE_PATH_TO_OAUTH2_JSON_KEY_FILE_HERE"
    scopes = "https://www.googleapis.com/auth/dfp"
    
  3. コードを実行してリクエストする
    <?php
    require 'vendor/autoload.php';
    use Google\AdsApi\AdManager\AdManagerSession;
    use Google\AdsApi\AdManager\AdManagerSessionBuilder;
    use Google\AdsApi\AdManager\v202402\ApiException;
    use Google\AdsApi\AdManager\v202402\ServiceFactory;
    use Google\AdsApi\Common\OAuth2TokenBuilder;
    
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();
    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new AdManagerSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();
    
    // Get a service.
    $serviceFactory = new ServiceFactory();
    $networkService = $serviceFactory->createNetworkService($session);
    
    // Make a request
    $network = $networkService->getCurrentNetwork();
    printf(
        "Network with code %d and display name '%s' was found.\n",
        $network->getNetworkCode(),
        $network->getDisplayName()
    );
    

.NET

.NET クライアント ライブラリの使用方法を示す基本的な例を次に示します。

  1. 新しいプロジェクトを作成する

    Visual Studio を開き、新しいプロジェクト(コンソール アプリケーション)を作成します。

  2. 必要なライブラリ参照をプロジェクトに追加する

    Google.Dfp に nuget 依存関係を追加します。

  3. App.config を設定する

    src\App.config をプロジェクト ディレクトリにコピーして、プロジェクトに追加します。アプリケーションに独自の App.config がある場合は、次のノードを App.config にコピーできます。

    • 設定/アド マネージャー
    • configuration/configSections/section[name="AdManagerApi"]
    • configuration/system.net
  4. 認証情報を設定する

    App.config を開き、次のキーを編集します。

    <add key="ApplicationName" value="INSERT_YOUR_APPLICATION_NAME_HERE" />
    <add key="NetworkCode" value="INSERT_YOUR_NETWORK_CODE_HERE" />
    <add key="OAuth2Mode" value="SERVICE_ACCOUNT" />
    <add key="OAuth2SecretsJsonPath" value="INSERT_OAUTH2_SECRETS_JSON_FILE_PATH_HERE" />
    

  5. ライブラリを呼び出す

    次の C# コード スニペットに示すように、ライブラリを呼び出すことができます。

    AdManagerUser user = new AdManagerUser();
          using (InventoryService inventoryService = user.GetService<InventoryService>())
                {
                    // Create a statement to select ad units.
                    int pageSize = StatementBuilder.SUGGESTED_PAGE_LIMIT;
                    StatementBuilder statementBuilder =
                        new StatementBuilder().OrderBy("id ASC").Limit(pageSize);
    
                    // Retrieve a small amount of ad units at a time, paging through until all
                    // ad units have been retrieved.
                    int totalResultSetSize = 0;
                    do
                    {
                        AdUnitPage page =
                            inventoryService.getAdUnitsByStatement(statementBuilder.ToStatement());
    
                        // Print out some information for each ad unit.
                        if (page.results != null)
                        {
                            totalResultSetSize = page.totalResultSetSize;
                            int i = page.startIndex;
                            foreach (AdUnit adUnit in page.results)
                            {
                                Console.WriteLine(
                                    "{0}) Ad unit with ID \"{1}\" and name \"{2}\" was found.", i++,
                                    adUnit.id, adUnit.name);
                            }
                        }
    
                        statementBuilder.IncreaseOffsetBy(pageSize);
                    } while (statementBuilder.GetOffset() < totalResultSetSize);
    
                    Console.WriteLine("Number of results found: {0}", totalResultSetSize);
                }
            

App.config で認証情報を設定したくない場合は、別の使用方法について この Wiki 記事をご覧ください。.NET クライアント ライブラリの使用の詳細については、README をご覧ください。クライアント ライブラリを使用せずに .NET で開発を行う場合は、NoClientLibrary の Wiki 記事をご覧ください。

Ruby

Ruby クライアント ライブラリの使用方法を示す基本的な例を次に示します。Ruby クライアント ライブラリを使用するには、Ruby 2.1 以降が必要です。

  1. Ruby gem をインストールして、構成ファイルを取得します。

    シェルで次のコマンドを実行します。

    gem install google-dfp-api
    curl https://raw.githubusercontent.com/googleads/google-api-ads-ruby/main/ad_manager_api/ad_manager_api.yml -o ~/ad_manager_api.yml
    
  2. 認証情報を設定する

    ~/ad_manager_api.yml ファイルの必須フィールドを入力します。OAuth2 キーファイルがまだない場合は、OAuth2 認証情報を作成する必要があります。

    :authentication:
      :oauth2_keyfile: INSERT_PATH_TO_JSON_KEY_FILE_HERE
      :application_name: INSERT_APPLICATION_NAME_HERE
      :network_code: INSERT_NETWORK_CODE_HERE
    
  3. コードを記述してリクエストを行う
    # Import the library.
    require 'ad_manager_api'
    
    # Initialize an Ad Manager client instance (uses credentials in ~/ad_manager_api.yml by default).
    ad_manager = AdManagerApi::Api.new
    
    # Get a service instance.
    network_service = ad_manager.service(:NetworkService, :v202402)
    
    # Make a request.
    network = network_service.get_current_network()
    
    puts "The current network is %s (%d)." %
            [network[:display_name], network[:network_code]]
    

使用を開始する手順について詳しくは、Ruby クライアント ライブラリとともに配布されている README ファイルをご覧ください。また、Ruby のサンプル ライブラリ全体をご確認ください。

次のステップ

クライアント ライブラリを稼働したら、提供されたサンプルを変更して、ニーズに合わせて拡張します。

API の詳細については、リファレンス ドキュメントをご覧ください。

ご不明な点がございましたら、サポートページをご利用ください。