このガイドでは、前提条件となるいくつかの設定を 確認できます。次の場合は自己紹介から始める まだ行っていません。
このガイドでは更新トークンも使用します。これは、ユーザーが十分な Google 広告アカウントへのアクセス権を持つユーザーにより、1 回限りの設定でアプリを認可することで、 アカウントに対するオフライン API 呼び出しを、それ以上のユーザーの介入なしに行う。 更新トークンを使用して、cron ジョブなどのオフライン ワークフローの両方を構築できる インタラクティブなワークフロー(ウェブアプリやモバイルアプリなど)が含まれます。
更新トークンを取得する
Google Ads API では、認証メカニズムとして OAuth 2.0 を使用します。デフォルトでは、OAuth は 2.0 認証は、制限付きの有効期間が経過すると期限切れになるアクセス トークンを発行します。 あります。アクセス トークンを自動的に更新するには、refresh トークンを使用してください。
更新トークンを生成するには、 oauth2l ツール:
oauth2l fetch --credentials credentials.json --scope adwords \ --output_format refresh_token
credentials.json
ファイルは、以前のファイルです。 ステップをご覧ください。oauth2l
コマンドにより、新しいブラウザで Google アカウントのログイン ウィンドウが開きます OAuth 2.0 の認証手順が表示されます。アプリが未確認の場合は、警告画面が表示されることがあります。このような場合 [詳細設定を表示] をクリックして [PROJECT_NAME に移動(未確認)] オプション
スコープを確認したら、 [続行] ボタン。
ブラウザに次のテキストを含むプロンプトが表示されます。
Authorization code granted. Please close this tab.
oauth2l
コマンドは、次の JSON スニペットを出力します。{ "client_id": "******.apps.googleusercontent.com", "client_secret": "******", "token_uri": "https://oauth2.googleapis.com/token", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "refresh_token": "******", "type": "authorized_user" }
API 呼び出しを行う
ご利用のクライアントを選択して、API 呼び出しの方法をご確認ください。
Java
クライアント ライブラリのアーティファクトは、Maven セントラル リポジトリをご覧ください。追加 次のように、クライアント ライブラリをプロジェクトの依存関係として指定します。
Maven の依存関係は次のとおりです。
<dependency>
<groupId>com.google.api-ads</groupId>
<artifactId>google-ads</artifactId>
<version>33.0.0</version>
</dependency>
Gradle の依存関係は次のとおりです。
implementation 'com.google.api-ads:google-ads:33.0.0'
次の内容の ~/ads.properties
ファイルを作成します。
api.googleads.clientId=INSERT_CLIENT_ID_HERE
api.googleads.clientSecret=INSERT_CLIENT_SECRET_HERE
api.googleads.refreshToken=INSERT_REFRESH_TOKEN_HERE
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 18.1.0
関連する設定で GoogleAdsConfig
オブジェクトを作成し、これを使用して
GoogleAdsClient
オブジェクトを作成します。
GoogleAdsConfig config = new GoogleAdsConfig()
{
DeveloperToken = "******",
OAuth2Mode = "APPLICATION",
OAuth2ClientId = "******.apps.googleusercontent.com",
OAuth2ClientSecret = "******",
OAuth2RefreshToken = "******",
LoginCustomerId = ******
};
GoogleAdsClient client = new GoogleAdsClient(config);
次に、キャンペーン レポートを作成します。
GoogleAdsService.SearchStream
メソッドを使用して、アカウント内のキャンペーンを取得します。このガイドでは、
レポートの詳細をご覧ください。
public void Run(GoogleAdsClient client, long customerId)
{
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService = client.GetService(
Services.V17.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:22.0.0
コピーを作成し、
google_ads_php.ini
ファイルを GitHub リポジトリからコピーし、認証情報を含めるように修正します。
[GOOGLE_ADS]
developerToken = "INSERT_DEVELOPER_TOKEN_HERE"
loginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"
[OAUTH2]
clientId = "INSERT_OAUTH2_CLIENT_ID_HERE"
clientSecret = "INSERT_OAUTH2_CLIENT_SECRET_HERE"
refreshToken = "INSERT_OAUTH2_REFRESH_TOKEN_HERE"
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==21.3.0
google-ads.yaml
のコピーを作成します。
ファイルを GitHub リポジトリからコピーし、認証情報を含めるように修正します。
client_id: INSERT_OAUTH2_CLIENT_ID_HERE
client_secret: INSERT_OAUTH2_CLIENT_SECRET_HERE
refresh_token: INSERT_REFRESH_TOKEN_HERE
developer_token: INSERT_DEVELOPER_TOKEN_HERE
login_customer_id: INSERT_LOGIN_CUSTOMER_ID_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")
次に、キャンペーン レポートを作成します。
GoogleAdsService.SearchStream
メソッドを使用して、アカウント内のキャンペーンを取得します。このガイドでは、
レポートの詳細をご覧ください。
def main(client, customer_id):
ga_service = client.get_service("GoogleAdsService")
query = """
SELECT
campaign.id,
campaign.name
FROM campaign
ORDER BY campaign.id"""
# Issues a search request using streaming.
stream = ga_service.search_stream(customer_id=customer_id, query=query)
for batch in stream:
for row in batch.results:
print(
f"Campaign with ID {row.campaign.id} and name "
f'"{row.campaign.name}" was found.'
)
Ruby
クライアント ライブラリ用の Ruby gem は、Rubygems gem Hosting サイトをご覧ください。推奨される方法 Bundler を使用する方法です。Gemfile に行を追加します。
gem 'google-ads-googleads', '~> 30.0.0'
次のコマンドを実行します。
bundle install
コピーを作成し、
google_ads_config.rb
ファイルを GitHub リポジトリからコピーし、認証情報を含めるように修正します。
Google::Ads::GoogleAds::Config.new do |c|
c.client_id = 'INSERT_CLIENT_ID_HERE'
c.client_secret = 'INSERT_CLIENT_SECRET_HERE'
c.refresh_token = 'INSERT_REFRESH_TOKEN_HERE'
c.developer_token = 'INSERT_DEVELOPER_TOKEN_HERE'
c.login_customer_id = 'INSERT_LOGIN_CUSTOMER_ID_HERE'
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。まず、Cloud Shell の
任意のディレクトリの google-ads-perl
リポジトリ。
git clone https://github.com/googleads/google-ads-perl.git
google-ads-perl
ディレクトリに移動し、次のコマンドを実行します。
ライブラリを使用するために必要なすべての依存関係をインストールします。
cd google-ads-perl
cpan install Module::Build
perl Build.PL
perl Build installdeps
コピーを作成し、
googleads.properties
ファイルを GitHub リポジトリからコピーし、認証情報を含めるように修正します。
clientId=INSERT_OAUTH2_CLIENT_ID_HERE
clientSecret=INSERT_OAUTH2_CLIENT_SECRET_HERE
refreshToken=INSERT_OAUTH2_REFRESH_TOKEN_HERE
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::V17::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;
}
REST
まず、HTTP クライアントを使用して OAuth 2.0 アクセス トークンを取得します。このガイド
curl
コマンドを使用します。
curl \
--data "grant_type=refresh_token" \
--data "client_id=CLIENT_ID" \
--data "client_secret=CLIENT_SECRET" \
--data "refresh_token=REFRESH_TOKEN" \
https://www.googleapis.com/oauth2/v3/token
次に、キャンペーン レポートを作成します。
GoogleAdsService.SearchStream
メソッドを使用して、アカウント内のキャンペーンを取得します。このガイドでは、
レポートの詳細をご覧ください。
curl -i -X POST https://googleads.googleapis.com/v17/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"
}