이 빠른 시작 가이드에서는 Google Ads API에 대한 첫 번째 API 호출을 만드는 방법을 설명합니다.
주요 개념
- Google Cloud 프로젝트: Google Cloud 프로젝트는 API 및 OAuth 2.0 API 사용자 인증 정보 관리를 비롯한 모든 Google 서비스를 만들고 사용 설정하고 사용하기 위한 기반을 형성합니다. Google Cloud 콘솔에서 만들 수 있습니다.
- API 액세스 수준: Google Cloud 프로젝트의 API 액세스 수준은 하루에 수행할 수 있는 API 호출 수와 API 호출을 수행할 수 있는 환경을 제어합니다. 프로젝트의 API 액세스 수준은 프로젝트의 Google Ads API 개요 페이지에 표시됩니다.
- Google Ads 관리자 계정: Google Ads 관리자 계정은 다른 Google Ads 계정을 관리하는 데 사용되며, Google Ads 고객 계정 또는 다른 Google Ads 관리자 계정의 모음일 수 있습니다.
- Google Ads 고객 계정: API 호출로 타겟팅하려는 광고를 게재하는 데 사용되는 Google Ads 계정입니다.
- 클라이언트 고객 ID: Google Ads 클라이언트 계정을 식별하는 10자리 숫자입니다. Google Ads UI에서 이 ID를 복사한 경우 하이픈을 삭제해야 합니다.
- OAuth 2.0: OAuth 2.0은 모든 Google API에서 사용하는 승인용 산업 표준 프로토콜입니다. API 호출을 수행할 OAuth 2.0 사용자 인증 정보를 생성하려면 서비스 계정과 키가 필요합니다.
- 서비스 계정: 개별 사용자가 아닌 애플리케이션에 속하는 특별한 유형의 Google 계정입니다. Google Ads API에 애플리케이션을 인증하는 데 사용됩니다. 서비스 계정을 얻으려면 Google Cloud 프로젝트가 필요합니다.
- 서비스 계정 키: 서비스 계정의 비공개 키가 포함된 JSON 앱 사용자 인증 정보 파일입니다. Google Ads API API 호출 시 서비스 계정을 인증하는 OAuth 2.0 사용자 인증 정보를 생성하는 데 사용됩니다. 서비스 계정 키를 얻으려면 서비스 계정이 필요합니다.
기본 요건
Google Ads API 호출을 하려면 다음 단계를 완료해야 합니다.
Google Ads API 액세스를 위해 클라우드 프로젝트 구성
Google Cloud 프로젝트는 Google API 및 OAuth 2.0 API 사용자 인증 정보를 관리하는 데 사용됩니다. Google Cloud 콘솔을 방문하여 기존 Google Cloud 프로젝트를 찾거나 새 프로젝트를 만들 수 있습니다.
먼저 프로젝트에서 Google Ads API를 사용 설정합니다.
그런 다음 Google Ads API 개요 페이지를 방문합니다. 페이지에 현재 API 액세스 수준이 표시됩니다. 현재 API 액세스 수준이 테스트인 경우 액세스 수준 업그레이드 섹션을 펼칩니다. 안내에 따라 탐색기 액세스 수준을 신청합니다.
신청을 완료하면 Google에서 신청을 자동으로 검토하고 대부분의 경우 탐색기로 업그레이드합니다. 탐색기 액세스 권한이 부여되지 않은 경우에도 걱정하지 마세요. 이 가이드에서는 Google Ads 고객 계정을 구성할 때 적절한 안내를 제공합니다.
서비스 계정 만들기
API 호출을 수행하려면 서비스 계정과 서비스 계정 키가 필요합니다. 이미 다른 Google API를 사용 중이고 OAuth 2.0 서비스 계정 및 키를 만든 경우 이 단계를 건너뛰고 기존 사용자 인증 정보를 재사용할 수 있습니다.
서비스 계정 및 키를 만드는 방법
- Google Cloud 콘솔에서 메뉴 > IAM 및 관리자 > 서비스 계정으로 이동합니다.
- 서비스 계정을 선택합니다.
- 키 > 키 추가 > 새 키 만들기를 클릭합니다.
- JSON을 선택한 다음 만들기를 클릭합니다.
새로운 공개 키/비공개 키 쌍이 생성되어 기기에 새 파일로 다운로드됩니다. 다운로드한 JSON 파일을 작업 디렉터리에
credentials.json로 저장합니다. 이 파일은 이 키의 유일한 사본입니다.credentials.json를 버전 제어 (예:.gitignore파일에 추가)에 커밋하지 마세요. - 닫기를 클릭합니다.
Google Ads 고객 계정 구성
먼저 API 호출을 실행할 Google Ads 계정을 식별합니다. API 호출을 할 수 있는 계정 유형은 Google Cloud 프로젝트의 API 액세스 수준에 따라 달라집니다. Google Ads API 개요 페이지에서 API 액세스 수준을 확인하세요.
탐색기, 기본 및 일반 액세스 수준
Google Ads 프로덕션 계정에 전화를 걸 수 있습니다. 하지만 필요한 경우 테스트 액세스 탭의 안내에 따라 Google Ads 테스트 계정을 만들 수 있습니다.
액세스 테스트
Google Cloud 프로젝트는 Google Ads 프로덕션 계정에 대한 API 호출을 수행하는 데 사용할 수 없습니다. Google Ads 테스트 계정에 대해서만 API 호출을 할 수 있습니다.
Google Ads 테스트 계정을 만드는 방법
다음 안내에서는 Google Ads 테스트 관리자 계정과 그 아래에 Google Ads 테스트 광고주 계정을 만듭니다.
파란색 버튼을 클릭하여 Google Ads 테스트 관리자 계정을 만듭니다. 메시지가 표시되면 Google Ads 프로덕션 관리자 계정에 연결되지 않은 Google 계정으로 로그인합니다. 계정이 없는 경우 해당 페이지의 계정 만들기 버튼을 사용하여 새 Google 계정을 만드세요.
- Google Ads 테스트 관리자 계정에서 Google Ads 테스트 고객 계정을 만듭니다. 계정 > > 새 계정 만들기를 클릭하고 양식을 작성합니다. Google Ads 테스트 관리자 계정에서 만든 모든 Google Ads 계정은 자동으로 Google Ads 테스트 계정이 됩니다.
- 선택적으로 Google Ads 페이지에서 Google Ads 테스트 클라이언트 계정 아래에 몇 개의 캠페인을 만듭니다.
Google Ads 고객에게 API 호출을 하려면 서비스 계정에 Google Ads 고객 계정에 대한 액세스 권한과 적절한 권한을 부여해야 합니다. 이렇게 하려면 고객 계정에 대한 관리자 액세스 권한이 필요합니다.
서비스 계정에 Google Ads 계정 액세스 권한을 부여하는 방법
- 관리자로 Google Ads 계정에 로그인하여 시작합니다.
- 관리 > 액세스 및 보안으로 이동합니다.
- 사용자 탭에서 버튼을 클릭합니다.
- 이메일 입력 상자에 서비스 계정 이메일 주소를 입력합니다.
적절한 계정 액세스 수준을 선택하고 계정 추가 버튼을 클릭합니다. 서비스 계정에는 이메일 액세스 수준이 지원되지 않습니다.
- 서비스 계정에 액세스 권한이 부여됩니다.
- [선택사항] 초기 설정 중에 서비스 계정에 관리자 액세스 권한을 부여할 수 없습니다. API 호출에 관리자 액세스가 필요한 경우 다음과 같이 액세스를 업그레이드할 수 있습니다.
- 액세스 수준 열에서 서비스 계정의 액세스 수준 옆에 있는 드롭다운 화살표를 클릭합니다.
- 드롭다운 목록에서 관리자를 선택합니다.
도구 및 클라이언트 라이브러리 다운로드
API 호출 방식에 따라 클라이언트 라이브러리 또는 HTTP 클라이언트를 다운로드할 수 있습니다.
클라이언트 라이브러리 사용
원하는 클라이언트 라이브러리를 다운로드하여 설치합니다.
HTTP 클라이언트 사용 (REST)
curl
URL을 통해 데이터를 전송하는 명령줄 도구인 curl을 다운로드하여 설치합니다.
Google Cloud 명령줄 인터페이스
Google Cloud CLI 설치 가이드에 따라 gcloud 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 호출 방법에 관한 안내를 보려면 원하는 클라이언트를 선택하세요.
자바
클라이언트 라이브러리 아티팩트는 Maven Central 저장소에 게시됩니다.
종속 항목 버전을 관리하고 충돌을 방지하려면 Google Ads API 재료명세서 (BOM) 가이드를 참고하세요.
BOM을 사용하지 않는 경우 다음 빌드 도구 중 하나를 사용하여 프로젝트에 클라이언트 라이브러리를 직접 추가하세요.
Maven: pom.xml 파일에 다음 종속 항목을 추가합니다.
<dependency>
<groupId>com.google.api-ads</groupId>
<artifactId>google-ads</artifactId>
<version>46.1.0</version>
</dependency>
Gradle: build.gradle 파일에 다음 종속 항목을 추가합니다.
implementation 'com.google.api-ads:google-ads:46.1.0'
다음 콘텐츠로 홈 디렉터리 (Linux 및 macOS의 경우 ~/ads.properties, Windows의 경우 %USERPROFILE%\ads.properties)에 ads.properties 파일을 만듭니다.
api.googleads.serviceAccountSecretsPath=JSON_KEY_FILE_PATH
api.googleads.loginCustomerId=INSERT_LOGIN_CUSTOMER_ID_HERE
API 요청을 실행하기 전에 GoogleAdsClient 인스턴스를 만듭니다. 기본적으로 fromPropertiesFile()는 홈 디렉터리에 있는 ads.properties 파일에서 사용자 인증 정보를 로드합니다.
GoogleAdsClient googleAdsClient;
try {
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (IOException e) {
System.err.printf("Failed to create GoogleAdsClient: %s%n", e);
throw new RuntimeException("Initialization failed", e);
}
그런 다음 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 27.4.0API를 호출하려면 구성 설정 (예: appsettings.json, 환경 변수 또는 맞춤 설정)에서 GoogleAdsConfig 객체를 만들고 이를 전달하여 GoogleAdsClient 인스턴스를 초기화합니다.
GoogleAdsConfig config = new GoogleAdsConfig()
{
OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
OAuth2SecretsJsonPath = "JSON_KEY_FILE_PATH",
LoginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"
};
GoogleAdsClient client = new GoogleAdsClient(config);
그런 다음 GoogleAdsService.SearchStream 메서드를 사용하여 캠페인 보고서를 실행하여 계정의 캠페인을 가져옵니다. 이 가이드에서는 신고에 관한 세부정보를 다루지 않습니다.
public void Run(GoogleAdsClient client, long customerId)
{
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService = client.GetService(
Services.V25.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 저장소에 게시됩니다.
호환되는 PHP 버전과 Composer가 설치되어 있는지 확인한 다음 프로젝트의 루트 디렉터리로 변경하고 다음 명령어를 실행하여 프로젝트의 vendor/ 디렉터리에 라이브러리와 종속 항목을 설치합니다.
composer require googleads/google-ads-php:35.1.0GitHub 저장소에서 google_ads_php.ini 파일을 복사하여 홈 디렉터리 또는 프로젝트의 루트 디렉터리에 저장하고 사용자 인증 정보를 포함하도록 수정합니다.
[GOOGLE_ADS]
loginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"
[OAUTH2]
jsonKeyFilePath = "JSON_KEY_FILE_PATH"
scopes = "https://www.googleapis.com/auth/adwords"
google_ads_php.ini 구성 파일을 사용하여 GoogleAdsClient 인스턴스를 만듭니다.
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V25\GoogleAdsClientBuilder;
$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
Python용 Google Ads API 클라이언트 라이브러리는 PyPI에 배포됩니다. 지원되는 Python 버전이 설치되어 있는지 확인한 다음 pip를 사용하여 라이브러리를 설치합니다.
python -m pip install google-ads==33.0.0API 호출을 인증하려면 google-ads.yaml 파일을 구성하세요.
- GitHub 저장소에서 샘플
google-ads.yaml파일의 사본을 다운로드합니다. - 홈 디렉터리 (
~/google-ads.yaml) 또는 맞춤 경로에 파일을 저장합니다. google-ads.yaml을 열고 사용자 인증 정보를 포함하도록 업데이트합니다.login_customer_id: INSERT_LOGIN_CUSTOMER_ID_HERE json_key_file_path: JSON_KEY_FILE_PATH라이브러리가 초기화 또는 구성 경고를 캡처할 수 있도록 클라이언트를 초기화하기 전에 로깅을 구성합니다. 다음 예에서는 표준 출력(
stdout)에INFO로그를 출력하도록 라이브러리의 로거를 구성합니다.
import logging
import sys
logger = logging.getLogger("google.ads.googleads.client")
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler(sys.stdout))
GoogleAdsClient.load_from_storage 메서드를 호출하고 google-ads.yaml 파일의 경로를 전달하여 GoogleAdsClient 인스턴스를 만듭니다.
from google.ads.googleads.client import GoogleAdsClient
client = GoogleAdsClient.load_from_storage("path/to/google-ads.yaml")
경로 인수를 생략하면 load_from_storage()는 기본적으로 홈 디렉터리 (~/google-ads.yaml)에서 구성 파일을 검색합니다.
그런 다음 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에 게시됩니다. 지원되는 Ruby 버전이 설치되어 있는지 확인하고 Bundler를 사용하여 라이브러리를 설치합니다.
애플리케이션의
Gemfile에 gem을 추가합니다.gem 'google-ads-googleads', '~> 45.1.0'다음을 실행하여 gem을 설치합니다.
bundle install
사용자 인증 정보를 구성하려면 다음 단계를 따르세요.
- GitHub 저장소에서 샘플
google_ads_config.rb파일을 복사합니다. - 프로젝트의 루트 디렉터리 또는 홈 디렉터리(
~)에 파일을 저장합니다. google_ads_config.rb을 열고 자리표시자 값을 Google Ads API 사용자 인증 정보로 바꿉니다.Google::Ads::GoogleAds::Config.new do |c| c.login_customer_id = 'INSERT_LOGIN_CUSTOMER_ID_HERE' c.keyfile = 'JSON_KEY_FILE_PATH' end구성 파일 (
google_ads_config.rb)의 경로를 전달하여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
Perl 클라이언트 라이브러리는 CPAN에 배포되며 Perl 5.28 이상과 cpan 또는 cpanm 패키지 관리자가 필요합니다.
원하는 디렉터리에
google-ads-perl저장소를 클론합니다.git clone https://github.com/googleads/google-ads-perl.gitgoogle-ads-perl디렉터리로 변경하고 다음 명령어를 실행하여 필요한 종속 항목을 설치하고 라이브러리를 빌드합니다.cd google-ads-perl cpan install Module::Build perl Build.PL perl Build installdeps perl Build perl Build install
사용자 인증 정보를 구성하려면 다음 단계를 따르세요.
GitHub 저장소에서 홈 디렉터리(
~/googleads.properties)로 샘플googleads.properties구성 파일을 복사합니다.cp googleads.properties ~/googleads.properties사용자 인증 정보를 포함하도록
~/googleads.properties를 수정합니다.jsonKeyFilePath=JSON_KEY_FILE_PATH loginCustomerId=INSERT_LOGIN_CUSTOMER_ID_HERE구성된
googleads.properties파일 (예:~/googleads.properties)의 경로를 전달하여Client인스턴스를 만듭니다.
my $api_client = Google::Ads::GoogleAds::Client->new({
properties_file => "/path/to/googleads.properties"
});
그런 다음 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::V25::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;
}
실행되면 스크립트가 일치하는 행을 스트리밍하고 계정의 각 캠페인 ID와 이름을 출력합니다.
curl
먼저 gcloud CLI에서 서비스 계정을 활성 사용자 인증 정보로 설정합니다.
gcloud auth login --cred-file=JSON_KEY_FILE_PATH그런 다음 Google Ads API의 OAuth 2.0 액세스 토큰을 가져옵니다.
gcloud auth \
print-access-token \
--scopes='https://www.googleapis.com/auth/adwords'Google Ads 쿼리 언어(GAQL) 요청이 포함된 query.json이라는 파일을 만듭니다.
{
"query": "SELECT campaign.id, campaign.name, campaign.network_settings.target_content_network FROM campaign ORDER BY campaign.id"
}
GoogleAdsService.SearchStream 메서드를 사용하여 계정의 캠페인을 가져오는 캠페인 보고서를 실행합니다.
curl -i -X POST \
https://googleads.googleapis.com/v25/customers/CUSTOMER_ID/googleAds:searchStream \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ACCESS_TOKEN" \
-H "login-customer-id: LOGIN_CUSTOMER_ID" \
--data-binary "@query.json"첫 번째 호출 시 오류가 발생하면 API 오류 처리에서 문제 해결 안내를 참고하세요.