スタートガイド

デベロッパーは、Google アド マネージャー API を使用して、広告枠の管理、オーダーの作成、レポートの取得などを行うアプリケーションを作成できます。

Ad Manager API では SOAP を使用するため、Java、.NET、Python、PHP、Ruby 用のクライアント ライブラリをご利用いただけます。最初の API リクエストを行う手順は次のとおりです。

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

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

ネットワーク コードをメモします。これは、ネットワークにログインしたときに URL に表示されます。たとえば、URL https://admanager.google.com/1234#home の場合、1234 はネットワーク コードです。

認証情報を作成する

すべての Ad Manager API リクエストは、OAuth2 を使用して認証する必要があります。以下の手順では、独自のアド マネージャー データにアクセスする簡単なユースケースを説明しています。詳細とその他のオプションについては、認証をご覧ください。

  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.v202305.Network;
    import com.google.api.ads.admanager.axis.v202305.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='v202305')
    
    # 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\v202305\ApiException;
    use Google\AdsApi\AdManager\v202305\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/AdManagerApi
    • 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 記事で AdManagerUser クラスを使用する別の方法を確認してください。.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
    

    gem のインストール中に「cannot load such file -- mkmf (LoadError)」などのエラーが発生した場合、特定の環境用に ruby-dev、ruby-devel、xcode-select などの追加の Ruby 開発ライブラリをインストールする必要があります。
  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, :v202305)
    
    # 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 について詳しくは、リファレンス ドキュメントをご覧ください。

サポートが必要な場合は、サポートページをご覧ください。