このクイックスタート ガイドでは、Google Ads API に対して最初の API 呼び出しを行う方法について説明します。
主なコンセプト
- 開発者トークン: 開発者トークンは、Google Ads API サーバーに対してアプリを識別する 22 文字の英数字の 文字列です。API 呼び出しを行うには、開発者トークンが必要です。
- API アクセスレベル: 開発者トークンの API アクセスレベルによって、1 日に実行できる API 呼び出しの数と API 呼び出しを実行できる環境が制御されます。
- Google 広告クライアント センター(MCC)アカウント: Google 広告 MCC アカウントは、他の Google 広告アカウントを管理するために使用されます。Google 広告 MCC アカウントを使用して、Google 広告クライアント アカウントや他の Google 広告 MCC アカウントを管理できます。開発者トークンを取得するには、Google 広告 MCC アカウントが必要です。
- Google 広告クライアント アカウント: API 呼び出しを行う Google 広告アカウント。
- クライアントのお客様 ID: Google 広告クライアント アカウントを識別する 10 桁の数字。この ID を Google 広告 UI からコピーした場合は、ハイフンを削除してください。
- OAuth 2.0: OAuth 2.0 は、すべての Google API で使用される、業界標準の 承認プロトコルです。API 呼び出しを行うための OAuth 2.0 認証情報を生成するには、サービス アカウントとキーが必要です。
- Google Cloud プロジェクト: Google Cloud プロジェクトは、API と OAuth 2.0 API 認証情報の管理など、すべての Google サービスの作成、有効化、使用の基礎となります。これは Google Cloud コンソールから作成できます。
- サービス アカウント: 個々のユーザーではなくアプリケーションに属する特殊なタイプの Google アカウント。これは、Google Ads API に対してアプリケーションを認証するために使用されます。サービス アカウントを取得するには、Google Cloud プロジェクトが必要です。
- サービス アカウント キー: サービス アカウントの秘密鍵を含む JSON アプリ認証情報ファイル。これは、Google Ads API API 呼び出しを行うときにサービス アカウントを認証するための OAuth 2.0 認証情報を生成するために使用されます。サービス アカウント キーを取得するには、サービス アカウントが必要です。
前提条件
Google Ads API 呼び出しを行うには、次の手順を完了する必要があります。
開発者トークンを取得する
過去に開発者トークンに申し込んだことがある場合は、Google 広告 MCC アカウントにログインして API センターにアクセスすると確認できます。
開発者トークンをお持ちでない場合は、API センターで申し込むことができます。
開発者トークンに申し込む方法
- ウェブブラウザで API センター に 移動します。メッセージが表示されたら、Google 広告 MCC アカウントにログインします。 Google 広告 MCC アカウントをお持ちでない場合は、作成します。
- [API アクセスフォーム] に記入し、
[利用規約] に同意します。
- 情報が正しく、会社のウェブサイト の URL が機能していることを確認してください。ウェブサイトが公開されていない場合、Google は申請を処理できず、申請が拒否される可能性があります。
- 指定した API の連絡先メールアドレスが、定期的に モニタリングされている受信トレイに届くことを確認してください。審査プロセス中に、Google の API コンプライアンス チームからこのメール アドレスに連絡して、不明な点を確認する場合があります。連絡が取れない場合、 Google は申請を続行できない可能性があります。
- [API センター] で [API の連絡先メールアドレス] を編集できます。 申請手続き後もこの情報を最新の状態に保つことで、 Google から重要なサービスに関するお知らせを受け取ることができます。
申請手続きが完了すると、開発者トークンが [API センター] に [承認待ち] ステータスで表示されます。開発者トークンのアクセスレベルは [**テスト アカウントへのアクセス**] になります。
Google API Console プロジェクトを構成する
Google API Console プロジェクトは、Google API と OAuth 2.0 API 認証情報の管理に使用されます。既存の Google API Console プロジェクトを確認したり、Google API Console にアクセスしてプロジェクトを作成したりできます。
まず、プロジェクトで Google Ads API を有効にします。
次に、API 呼び出しを行うには、サービス アカウントとサービス アカウント キーが必要です。すでに別の Google API を使用していて、OAuth 2.0 サービス アカウントとキーを作成している場合は、この手順をスキップして既存の認証情報を再利用できます。
サービス アカウントとキーを作成する方法
- Google Cloud コンソールで、メニュー > [**IAM と管理**] > [**サービス アカウント**] に移動します。
- サービス アカウントを選択します。
- [Keys] > [Add key] > [Create new key] をクリックします。
- [JSON] を選択し、[作成] をクリックします。
新しい公開鍵と秘密鍵のペアが生成され、新しいファイルとしてパソコンにダウンロードされます。ダウンロードした JSON ファイルを、作業ディレクトリに
credentials.jsonとして保存します。このファイルは このキーの唯一のコピーです。 - [閉じる] をクリックします。
Google 広告クライアント アカウントを構成する
まず、API 呼び出しを行う Google 広告アカウントを特定します。API 呼び出しを行うことができるアカウントの タイプは、開発者トークンの API アクセスレベルによって異なります。API アクセスレベルを確認するには、API センターをご覧ください。
Explorer、Basic、Standard のアクセスレベル
Google 広告の本番環境アカウントを呼び出すことができます。必要に応じて、[テスト アカウントへのアクセス] タブの手順に沿って Google 広告テスト アカウントを作成できます。
テスト アカウントへのアクセスレベル
開発者トークンを使用して、Google 広告の本番環境アカウントに対して API 呼び出しを行うことはできません 。Google 広告テスト アカウントに対してのみ API 呼び出しを行うことができます。
Google 広告テスト アカウントを作成する方法
次の手順では、Google 広告テスト MCC アカウントと、その下に Google 広告テストの Google 広告広告主アカウントを作成します。
青いボタンをクリックして、Google 広告テスト MCC アカウントを作成します。 メッセージが表示されたら、Google 広告の本番環境 MCC アカウントにリンクされていない Google アカウントでログインします。お持ちでない場合は、そのページの [アカウントを作成] ボタンを使用して新しい Google アカウントを作成します。
- Google 広告テスト MCC アカウントで、Google 広告テスト お客様アカウントを作成します。[アカウント] > > [新しいアカウントを作成] をクリックして、フォームに記入します。Google 広告テスト MCC アカウントから作成した Google 広告アカウントは、すべて自動的に Google 広告テスト アカウントになります。
- 必要に応じて、Google 広告ページから Google 広告テスト クライアント アカウントの下にキャンペーンをいくつか作成します。
Google 広告のお客様に対して API 呼び出しを行うには、Google 広告のお客様アカウントに対するアクセス権と適切な権限をサービス アカウントに付与する必要があります。これを行うには、お客様アカウントに対する管理者権限が必要です。
Google 広告 アカウントへのサービス アカウントのアクセス権を付与する方法
- まず、管理者として Google 広告アカウントにログインします。
- [管理者] > [アクセスとセキュリティ] に移動します。
- [add_circle] ボタンを [**ユーザー**] タブの下でクリックします。
- [メール] 入力ボックスにサービス アカウントのメールアドレスを入力します。
適切なアカウントのアクセスレベルを選択し、
[アカウントを追加] ボタンをクリックします。サービス アカウントでは、メールのアクセスレベルはサポートされていません。
- サービス アカウントにアクセス権が付与されます。
- [省略可]デフォルトでは、サービス アカウントに管理者権限を付与することはできません。API 呼び出しに管理者権限が必要な場合は、次のようにアクセス権をアップグレードできます。
- [**アクセスレベル**] 列で、サービス アカウントのアクセスレベルの横にあるプルダウン矢印をクリックします。
- プルダウン リストから [管理者] を選択します。
ツールとクライアント ライブラリをダウンロードする
API 呼び出しを行う方法に応じて、クライアント ライブラリまたは HTTP クライアントをダウンロードできます。
クライアント ライブラリを使用する
任意のクライアント ライブラリをダウンロードしてインストールします。
HTTP クライアント(REST)を使用する
curl
URL を介してデータを転送するためのコマンドライン ツールである curl をダウンロードしてインストールします。
Google Cloud CLI
このガイドの残りの手順は、gcloud ツールの次のバージョンで動作することが確認されています。アプリケーションの動作やコマンドライン オプションが異なるため、以前のバージョンでは動作しない可能性があります。
:~$ gcloud version
Google Cloud SDK 492.0.0
alpha 2024.09.06
beta 2024.09.06
bq 2.1.8
bundled-python3-unix 3.11.9
core 2024.09.06
enterprise-certificate-proxy 0.3.2
gcloud-crc32c 1.0.0
gsutil 5.30API 呼び出しを行う
API 呼び出しを行う方法の手順については、使用するクライアントを選択してください。
Java
クライアント ライブラリ アーティファクトは Maven central リポジトリ に公開されています。クライアント ライブラリを依存関係としてプロジェクトに追加します。
Maven の依存関係は次のとおりです。
<dependency>
<groupId>com.google.api-ads</groupId>
<artifactId>google-ads</artifactId>
<version>43.0.0</version>
</dependency>
Gradle の依存関係は次のとおりです。
implementation 'com.google.api-ads:google-ads:43.0.0'
また、Google Ads API の部品構成表 (BOM)を使用して依存関係のバージョンを管理することをおすすめします。手順については、BOM ガイドをご覧ください。
次の内容のファイル ~/ads.properties を作成します。
api.googleads.serviceAccountSecretsPath=JSON_KEY_FILE_PATH
api.googleads.developerToken=INSERT_DEVELOPER_TOKEN_HERE
api.googleads.loginCustomerId=INSERT_LOGIN_CUSTOMER_ID_HERE
次のように GoogleAdsClient オブジェクトを作成します。
GoogleAdsClient googleAdsClient = null;
try {
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
System.err.printf(
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n",
fnfe);
System.exit(1);
} catch (IOException ioe) {
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
System.exit(1);
}
次に、GoogleAdsService.SearchStream メソッドを使用してキャンペーン レポートを実行し、
アカウント内のキャンペーンを取得します。
private void runExample(GoogleAdsClient googleAdsClient, long customerId) {
try (GoogleAdsServiceClient googleAdsServiceClient =
googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
String query = "SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id";
// Constructs the SearchGoogleAdsStreamRequest.
SearchGoogleAdsStreamRequest request =
SearchGoogleAdsStreamRequest.newBuilder()
.setCustomerId(Long.toString(customerId))
.setQuery(query)
.build();
// Creates and issues a search Google Ads stream request that will retrieve all campaigns.
ServerStream<SearchGoogleAdsStreamResponse> stream =
googleAdsServiceClient.searchStreamCallable().call(request);
// Iterates through and prints all of the results in the stream response.
for (SearchGoogleAdsStreamResponse response : stream) {
for (GoogleAdsRow googleAdsRow : response.getResultsList()) {
System.out.printf(
"Campaign with ID %d and name '%s' was found.%n",
googleAdsRow.getCampaign().getId(), googleAdsRow.getCampaign().getName());
}
}
}
}
C#
クライアント ライブラリ パッケージは Nuget.org
リポジトリ に公開されています。まず、Google.Ads.GoogleAds パッケージに nuget 参照を追加します。
dotnet add package Google.Ads.GoogleAds --version 25.1.0関連する設定で GoogleAdsConfig オブジェクトを作成し、それを使用して GoogleAdsClient オブジェクトを作成します。
GoogleAdsConfig config = new GoogleAdsConfig()
{
DeveloperToken = "******",
OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
OAuth2SecretsJsonPath = "PATH_TO_CREDENTIALS_JSON",
LoginCustomerId = ******
};
GoogleAdsClient client = new GoogleAdsClient(config);
次に、GoogleAdsService.SearchStream メソッドを使用してキャンペーン レポートを実行し、
アカウント内のキャンペーンを取得します。このガイドでは、
レポートの詳細については説明しません。
public void Run(GoogleAdsClient client, long customerId)
{
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService = client.GetService(
Services.V24.GoogleAdsService);
// Create a query that will retrieve all campaigns.
string query = @"SELECT
campaign.id,
campaign.name,
campaign.network_settings.target_content_network
FROM campaign
ORDER BY campaign.id";
try
{
// Issue a search request.
googleAdsService.SearchStream(customerId.ToString(), query,
delegate (SearchGoogleAdsStreamResponse resp)
{
foreach (GoogleAdsRow googleAdsRow in resp.Results)
{
Console.WriteLine("Campaign with ID {0} and name '{1}' was found.",
googleAdsRow.Campaign.Id, googleAdsRow.Campaign.Name);
}
}
);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
PHP
クライアント ライブラリ パッケージは Packagist
リポジトリ に公開されています。プロジェクトのルート ディレクトリに移動し、次のコマンドを実行して、ライブラリとそのすべての依存関係をプロジェクトのルート ディレクトリの vendor/ ディレクトリにインストールします。
composer require googleads/google-ads-php:32.2.0GitHub リポジトリから
google_ads_php.ini
ファイルのコピーを作成し、認証情報を含めるように変更します。
[GOOGLE_ADS]
developerToken = "INSERT_DEVELOPER_TOKEN_HERE"
loginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"
[OAUTH2]
jsonKeyFilePath = "INSERT_ABSOLUTE_PATH_TO_OAUTH2_JSON_KEY_FILE_HERE"
scopes = "https://www.googleapis.com/auth/adwords"
GoogleAdsClient オブジェクトのインスタンスを作成します。
$oAuth2Credential = (new OAuth2TokenBuilder())
->fromFile('/path/to/google_ads_php.ini')
->build();
$googleAdsClient = (new GoogleAdsClientBuilder())
->fromFile('/path/to/google_ads_php.ini')
->withOAuth2Credential($oAuth2Credential)
->build();
次に、GoogleAdsService.SearchStream メソッドを使用してキャンペーン レポートを実行し、
アカウント内のキャンペーンを取得します。
public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
{
$googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
// Creates a query that retrieves all campaigns.
$query = 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id';
// Issues a search stream request.
/** @var GoogleAdsServerStreamDecorator $stream */
$stream = $googleAdsServiceClient->searchStream(
SearchGoogleAdsStreamRequest::build($customerId, $query)
);
// Iterates over all rows in all messages and prints the requested field values for
// the campaign in each row.
foreach ($stream->iterateAllElements() as $googleAdsRow) {
/** @var GoogleAdsRow $googleAdsRow */
printf(
"Campaign with ID %d and name '%s' was found.%s",
$googleAdsRow->getCampaign()->getId(),
$googleAdsRow->getCampaign()->getName(),
PHP_EOL
);
}
}
Python
クライアント ライブラリは PyPI
で配布されており、pip
コマンドを使用して次のようにインストールできます。
python -m pip install google-ads==29.2.0GitHub リポジトリから
google-ads.yaml ファイルのコピーを作成し、認証情報を含めるように変更します。
developer_token: INSERT_DEVELOPER_TOKEN_HERE
login_customer_id: INSERT_LOGIN_CUSTOMER_ID_HERE
json_key_file_path: JSON_KEY_FILE_PATH_HERE
GoogleAdsClient インスタンスを、
GoogleAdsClient.load_from_storage メソッドを呼び出して作成します。呼び出すときに、google-ads.yaml へのパスを文字列としてメソッドに渡します。
from google.ads.googleads.client import GoogleAdsClient
client = GoogleAdsClient.load_from_storage("path/to/google-ads.yaml")
ログの出力先をライブラリのロガーに伝えるハンドラを追加します。
次のコマンドを実行すると、ライブラリのロガーがコンソール(stdout)に出力されます。
import logging
import sys
logger = logging.getLogger('google.ads.googleads.client')
logger.addHandler(logging.StreamHandler(sys.stdout))
次に、GoogleAdsService.SearchStream メソッドを使用してキャンペーン レポートを実行し、
アカウント内のキャンペーンを取得します。
def main(client: GoogleAdsClient, customer_id: str) -> None:
ga_service: GoogleAdsServiceClient = client.get_service("GoogleAdsService")
query: str = """
SELECT
campaign.id,
campaign.name
FROM campaign
ORDER BY campaign.id"""
# Issues a search request using streaming.
stream: Iterator[SearchGoogleAdsStreamResponse] = ga_service.search_stream(
customer_id=customer_id, query=query
)
for batch in stream:
rows: List[GoogleAdsRow] = batch.results
for row in rows:
print(
f"Campaign with ID {row.campaign.id} and name "
f'"{row.campaign.name}" was found.'
)
Ruby
クライアント ライブラリの Ruby gem は、Rubygems gem ホスティング サイトに公開されています。インストール方法としては、bundler を使用することをおすすめします。Gemfile に次の行を追加します。
gem 'google-ads-googleads', '~> 38.0.0'
次のコマンドを実行します。
bundle installGitHub リポジトリから
google_ads_config.rb
ファイルのコピーを作成し、認証情報を含めるように変更します。
Google::Ads::GoogleAds::Config.new do |c|
c.developer_token = 'INSERT_DEVELOPER_TOKEN_HERE'
c.login_customer_id = 'INSERT_LOGIN_CUSTOMER_ID_HERE'
c.keyfile = 'JSON_KEY_FILE_PATH'
end
このファイルを保存するパスを渡して、GoogleAdsClient インスタンスを作成します。
client = Google::Ads::GoogleAds::GoogleAdsClient.new('path/to/google_ads_config.rb')
次に、GoogleAdsService.SearchStream メソッドを使用してキャンペーン レポートを実行し、
アカウント内のキャンペーンを取得します。
def get_campaigns(customer_id)
# GoogleAdsClient will read a config file from
# ENV['HOME']/google_ads_config.rb when called without parameters
client = Google::Ads::GoogleAds::GoogleAdsClient.new
responses = client.service.google_ads.search_stream(
customer_id: customer_id,
query: 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id',
)
responses.each do |response|
response.results.each do |row|
puts "Campaign with ID #{row.campaign.id} and name '#{row.campaign.name}' was found."
end
end
end
Perl
このライブラリは
CPANで配布されています。まず、任意のディレクトリに google-ads-perl リポジトリのクローンを作成します。
git clone https://github.com/googleads/google-ads-perl.gitgoogle-ads-perl ディレクトリに移動し、コマンド プロンプトで次のコマンドを実行して、ライブラリの使用に必要なすべての依存関係をインストールします。
cd google-ads-perlcpan install Module::Buildperl Build.PLperl Build installdeps
GitHub リポジトリから
googleads.properties
ファイルのコピーを作成し、認証情報を含めるように変更します。
jsonKeyFilePath=JSON_KEY_FILE_PATH
developerToken=INSERT_DEVELOPER_TOKEN_HERE
loginCustomerId=INSERT_LOGIN_CUSTOMER_ID_HERE
このファイルを保存するパスを渡して、Client インスタンスを作成します。
my $properties_file = "/path/to/googleads.properties";
my $api_client = Google::Ads::GoogleAds::Client->new({
properties_file => $properties_file
});
次に、GoogleAdsService.SearchStream メソッドを使用してキャンペーン レポートを実行し、
アカウント内のキャンペーンを取得します。
sub get_campaigns {
my ($api_client, $customer_id) = @_;
# Create a search Google Ads stream request that will retrieve all campaigns.
my $search_stream_request =
Google::Ads::GoogleAds::V24::Services::GoogleAdsService::SearchGoogleAdsStreamRequest
->new({
customerId => $customer_id,
query =>
"SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id"
});
# Get the GoogleAdsService.
my $google_ads_service = $api_client->GoogleAdsService();
my $search_stream_handler =
Google::Ads::GoogleAds::Utils::SearchStreamHandler->new({
service => $google_ads_service,
request => $search_stream_request
});
# Issue a search request and process the stream response to print the requested
# field values for the campaign in each row.
$search_stream_handler->process_contents(
sub {
my $google_ads_row = shift;
printf "Campaign with ID %d and name '%s' was found.\n",
$google_ads_row->{campaign}{id}, $google_ads_row->{campaign}{name};
});
return 1;
}
curl
まず、gcloud CLI でサービス アカウントをアクティブな認証情報として設定します。
gcloud auth login --cred-file=PATH_TO_CREDENTIALS_JSON次に、Google Ads API の OAuth 2.0 アクセス トークンを取得します。
gcloud auth \
print-access-token \
--scopes='https://www.googleapis.com/auth/adwords'次に、GoogleAdsService.SearchStream メソッドを使用してキャンペーン レポートを実行し、
アカウント内のキャンペーンを取得します。
curl -i -X POST https://googleads.googleapis.com/v24/customers/CUSTOMER_ID/googleAds:searchStream \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ACCESS_TOKEN" \
-H "developer-token: DEVELOPER_TOKEN" \
-H "login-customer-id: LOGIN_CUSTOMER_ID" \
--data-binary "@query.json"query.json の内容は次のとおりです。
{
"query": "SELECT campaign.id, campaign.name, campaign.network_settings.target_content_network FROM campaign ORDER BY campaign.id"
}
最初の呼び出しでエラーが発生した場合は、 API エラーの処理で トラブルシューティングの方法をご確認ください。