google adwords api php примеры
Пример использования Google AdWords API
Многие рекламодатели знают о преимуществах использования API в контекстной рекламе. Допустим, вам нужно запустить рекламную кампанию с большим количеством однотипных объявлений, но для разных товаров. В этом случае и приходит на помощь API-интерфейс. Вы легко и быстро переносите данные из базы MySQL в рекламную кампанию. И все! Дело сделано. Можно немного подредактировать и запускать. Именно такой схемой мы неоднократно пользовались для рекламы нашего книжного магазина в Яндекс.Директе.
А вот с Google Adwords все оказалось далеко не так просто. Мы долго пытались использовать эту схему в Adwords, переворошили кучу информации в Интернете, пока не узнали следующее от службы поддержки Google:
На данный момент AdWords API не доступен для рекламодателей РФ. Приносим извинения за неудобства.
На данный момент мы не имеем точных сроков запуска. Как только это будет сделано, мы обязательно сообщим рекламодателям РФ о данной функции.
Очень-очень жаль. Но мы не теряем надежды, что рано или поздно Google откроет возможность использовать API-интерфейс и у нас в России. Именно для такого случая мы решили рассказать подробно о нашем примере использования API в Adwords. Наш пример на ура работал на тестовом сервере Google, но не заработал на рабочем сервере по вышеуказанным причинам.
Схема эта довольно нетривиальна, поэтому в будущем (когда API для Adwods в России будет открыт) многим облегчит жизнь.
Шаг 1. Создание PHP кода
Сначала создаем PHP код для переноса данных из базы MySQL сайта в AdWords. Последнюю версию PHP библиотеки можно скачать с этой страницы. Так же, по этой ссылке можно найти много полезной информации, которая необходима в процессе написания кода.
Код в example.php имеет комментарии, которые должны помочь при разработке своей версии экспортера. Далее описаны основные шаги, которые выполняются в примере.
1.1 Инициализация начальных параметров
1.3 Остальные блоки кода
Шаг 2. Тестирование кода
Для работы с тестовым сервером необходимо поставить
DEFAULT_SERVER = «https://adwords-sandbox.google.com»
Для работы с рабочим сервером необходимо поставить
DEFAULT_SERVER = «https://adwords.google.com»
; Uncomment to make requests against a client account.
Пример содержания файла для рабочего сервера:
Google adwords api php примеры
Google Ads API PHP Client Library
This project hosts the PHP client library for the various SOAP-based Ads APIs (AdWords and Ad Manager) at Google.
Requirements and Preparation
Downloading this library
There are three ways of downloading this library as described below.
Method | Target Users |
---|---|
Using composer require | Those who want to use this library as a third-party library for their projects and thus example files are not needed. |
Using git clone | Those who want to alter or contribute to this library (e.g., submitting a pull request) or want to run example files. |
Downloading a compressed tarball | Those who only want to run example files. |
Using composer require
The steps below download this library as a third-party library for your projects. The library will be downloaded by Composer and stored under the vendor/ directory. Examples are NOT downloaded by this download method.
Install the latest version using Composer.
Follow Getting started if you haven’t done so.
Follow Setting up your OAuth2 credentials if you haven’t set up the credentials yet.
You can now use the library.
This method is suitable for those who want to alter or contribute to this library (e.g., submitting pull requests) or wish to try our examples. All files in this repository will be downloaded.
Run git clone https://github.com/googleads/googleads-php-lib.git at the command prompt.
Run composer install at the command prompt. This will install all dependencies needed for using the library and running examples.
Follow Getting started if you haven’t done so.
Follow Setting up your OAuth2 credentials if you haven’t set up the credentials yet.
You can now use the library and run any examples you want. Try GetCampaigns.php by executing the following command:
Downloading a compressed tarball
This is suitable for those who only want to try out the AdWords API with this client library. The extracted directory of the tarball will contain only the examples/ directory.
On the releases page, select a version you want to try. Then, under Download, select the tarball of your choice. The name of the tarball indicates which product it belongs to, for example, adwords-examples-vX.Y.Z.tar.gz.
Extract your downloaded file to any location on your computer.
Navigate to the extracted directory (for example, adwords-examples-vX.Y.Z).
Run composer install at the command prompt. This will install all dependencies needed for using the library and running examples.
Follow Getting started if you haven’t done so.
Follow Setting up your OAuth2 credentials if you haven’t set up the credentials yet.
You can now run any examples you want. Try GetCampaigns.php by executing the following command:
Setting up your OAuth2 credentials
The AdWords and Ad Manager APIs use OAuth2 as the authentication mechanism. Follow the appropriate guide below based on your use case.
If you’re accessing an API using your own credentials.
If you’re accessing an API on behalf of clients.
The best way to learn how to use this library is to review the examples for your product.
All our examples are meant to be run via the command line and not through a webpage.
If you’re using 32-bit PHP, you’ll need to change all instances of intval() to floatval() before running an example. This is due to some IDs exceeding the 32-bit PHP_INT_MAX that intval() changes your value to. In addition, when writing your own code, do not apply intval() on any attributes that are explicitly an integer.
The following snippet of code from the BasicOperations/GetCampaigns.php example for AdWords gives you an idea of how to use this library. The usage pattern is similar for Ad Manager.
The builder’s fromFile() method looks for an adsapi_php.ini file in your home directory by default. If you want to store this file in another directory, pass the path of the file as an argument. For example:
It is highly recommended that you use an adsapi_php.ini file. However, if you don’t want to or can’t use one, you can use the OAuth2 token and ads session builders instead to set the same information. See the builders for details:
WSDL objects with names that are reserved PHP keywords
Note that some WSDL object types have names that are reserved PHP keywords and need to be augmented when used as PHP class names. The following is a list of these occurences.
This library conforms to PSR-3 for logging and provides the following loggers:
In general, each logger logs a summary and debug message for events (e.g., a SOAP API call). The level at which messages are logged depends on whether the event succeeded.
Log message \ Event status | Success | Failure |
---|---|---|
One-line summary | INFO | WARNING |
Debug message (e.g., SOAP payload) | DEBUG | NOTICE |
By default, each of the library loggers logs to STDERR on a separate channel using a Monolog StreamHandler.
You can configure some options for these default loggers in the adsapi_php.ini file:
If you need to further customize logging, you can specify your own logger entirely by providing a logger that implements LoggerInterface in either the AdWords or Ad Manager session builders:
We provide some utilities in this client library for helping you use features in the AdWords and Ad Manager API more conveniently. Check out the following wikis for details:
When downloading reports, you can set additional stream context options using the stream_context key to suit your needs (e.g., increasing the timeout as shown below). See also Guzzle FAQ for details.
If this library can’t find a CA bundle on your system, you’ll get an error message similar to this:
CA file issues can also cause an error like this:
PHPDoc for this library can be found in the gh-pages branch of this repository and can be viewed at:
General AdWords and Ad Manager API documentation can be found on our Google Developers site:
We use PSR-2 as a coding style standard. Assuming that you’re at the root directory of your project, to check for coding style violations, run
To automatically fix (fixable) coding style violations, run
For client library specific bug reports, feature requests, and patches, create an issue on the issue tracker.
For general AdWords and Ad Manager API questions, bug reports, or feature requests, post to our forums:
Announcements and updates
For general ads API and client library updates and news, follow:
API deprecation schedules can be found at:
About
Google Ads API Client Library for PHP (AdWords and Ad Manager)
Google adwords api php примеры
Google Ads API Client Library for PHP
This project hosts the PHP client library for the Google Ads API.
Clone this project in the directory of your choice via:
Change into the google-ads-php directory.
You’ll see some files and subdirectories:
Run composer install at the command prompt. This will install all dependencies needed for using the library and running examples.
Set up your OAuth2 credentials.
The Google Ads API uses OAuth2 as the authentication mechanism. Choose the appropriate option below based on your use case, and read and follow the instructions that the example prints to the console.
If you already have credentials for the AdWords API.
If you’re accessing the Google Ads API using your own credentials.
Follow the instructions at https://developers.google.com/google-ads/api/docs/oauth/cloud-project to create an OAuth2 client ID and secret for the installed application OAuth2 flow.
Run the AuthenticateInDesktopApplication example, which will prompt you for your OAuth2 client ID and secret.
Copy the output from the last step of the example into the google_ads_php.ini file in your home directory. Don’t forget to fill in your developer token too.
Run the GetCampaigns example to test if your credentials are valid. You also need to pass your Google Ads account’s customer ID without dashes as a command-line parameter:
NOTE: Code examples are meant to be run from command prompt, not via the web browsers.
Explore other examples.
Note: You will find comments with the formats [START. ] and [END. ] in the source code of these examples. These are only used for technical purposes, you can completely disregard them.
Instantiate a client
To issue requests via the Google Ads API, you first need to create a GoogleAdsClient.
For more information on how to configure a client when instantiating it, see the configuration guide.
Get a service client
There are different types of transport that can be used. See the Transport guide for more information.
Protobuf is used regardless of the transport used to request the Google Ads API.
See the Protobuf guide for more information.
Автоматизируем рекламу. Adwords API. Часть 1
Oct 23, 2017 · 5 min read
Всем привет! Это первая статья в цикле. Для начала представлюсь. Меня зовут Леонид, я работаю в Chocofamily, занимаюсь маркетингом в проекте Chocofood.
Хочу сразу оправдать себя, я в первую очередь маркетолог, и программировать не умею, но учусь и стараюсь. Поэтому эти статьи не претендуют на истину в последней инстанции, а качество написанного говнокода оставляет желать лучшего. Основная цель всего этого — показать маркетолагам, что учить питон и другие штуки это классно, и сильно поможет в работе.
Итак, начинаем. Мы будем использовать для автоматизации Python 2.7 и официальную библиотеку для работы с Adwords от Google. Ссылка для скачивания, изучения примеров и т.д.: https://github.com/googleads/googleads-python-lib
Устанавливаем Python, если у вас его нет. В интернете миллиард гайдов, как это сделать.
Далее устанавливаем библиотеку для работы с Adwords, под названием GoogleAds. В консоли пишем:
$ pip install googleads
Результат должен быть таким:
3. Другие библиотеки, которые необходимы для корректной работы GoogleAds (при установке через pip устанавливаются автоматически):
4. Теперь самое интересное: авторизация.
Для того чтоб работать с API, вам нужен токен разработчика, client id, client secret, refresh token и номер клиента.
Для того, чтобы получит токен разработчика, мы регистрируем Центр клиентов (MCC), заходим в “Настройки” > “Центр Adwords API”, и там заполняем форму для получения токена:
После этого мы получим токен, у которого есть доступ только к тестовым центрам клиентов (о том, как получить базовый доступ, я расскажу в следующих статьях).
Ну и, как вы понимаете, вам теперь необходим тестовый центр клиентов (тестовый MCC аккаунт), для этого нужно зарегистрировать новый gmail аккаунт и перейти по ссылке: https://adwords.google.com/um/StartNewMccAccount?testAccount=true
В результате вы должны получить такой MCC акк с красной плашкой, предупреждающей о том, что это тестовый аккаунт (в нем лучше сразу завести тестового клиента, с тестовой кампанией):
Переходим к получению client_id, client_secret (они нужны и для тестового аккаунта, и для боевого):
Идем по адресу: console.cloud.google.com. Авторизуемся с почты, на которой зарегистрирован тестовый MCC.
Регистрируем новый проект:
Для этого жмем на “Выберите проект” и жмем на +
После этого заходим в раздел «Credentials» или «Учетные данные» в боковом меню, и в открывшемся разделе жмем «Create credentials» (создать учетные данные) > oAuth Client ID. В “Application type” выбираем “Other”. Если все успешно, выскочит окошко с client id и client secret.
from oauth2client import client
# Your OAuth2 Client ID and Secret. If you do not have an ID and Secret yet,
DEFAULT_CLIENT_ID = ‘ВСТАВЬТЕ ВАШ CLIENT ID’
DEFAULT_CLIENT_SECRET = ‘ВСТАВЬТЕ ВАШ CLIENT SECRET’
# The AdWords API OAuth2 scope.
parser = argparse.ArgumentParser(description=’Generates a refresh token with ‘
‘the provided credentials.’)
parser.add_argument(‘ — client_id’, default=DEFAULT_CLIENT_ID,
help=’Client Id retrieved from the Developer\’s Console.’)
parser.add_argument(‘ — client_secret’, default=DEFAULT_CLIENT_SECRET,
help=’Client Secret retrieved from the Developer\’s ‘
parser.add_argument(‘ — additional_scopes’, default=None,
help=’Additional scopes to apply when generating the ‘
‘refresh token. Each scope should be separated by a comma.’)
def main(client_id, client_secret, scopes):
“””Retrieve and display the access and refresh token.”””
user_agent=’Ads Python Client Library’,
print (‘Log into the Google Account you use to access your AdWords account’
‘and go to the following URL: \n%s\n’ % (authorize_url))
print ‘After approving the token enter the verification code (if specified).’
code = raw_input(‘Code: ‘).strip()
except client.FlowExchangeError, e:
print ‘Authentication has failed: %s’ % e
print (‘OAuth2 authorization successful!\n\n’
‘Your access token is:\n %s\n\nYour refresh token is:\n %s’
if __name__ == ‘__main__’:
if not (any([args.client_id, DEFAULT_CLIENT_ID]) and
raise AttributeError(‘No client_id or client_secret specified.’)
main(args.client_id, args.client_secret, configured_scopes)
Запустим его через консоль, предварительно вставив client_id&client_secret в нужные поля, в результате вы получите ссылку:
Перейдя по ней, нужно выбрать аккаунт, на который зарегистрирован тестовый MCC.
После выбора вы получите код:
Его нужно вставить в консоль, в результате вы получите ваш refresh token:
В будущем, когда вы получите базовый доступ для вашего токена разработчика, все эти манипуляции нужно будет повторить для основного MCC аккаунта.
Потненько, но мы почти у цели. У нас есть все, чтобы сделать первый запрос, а именно: получить список компаний в моем аккаунте.
Как это сделать, я расскажу во второй статье.
Code Structure
Previously, we got you set up to make your first API call, and we reviewed the configuration ingredients required for making calls to the API.
In this guide, we’ll take a look at the structure of a typical AdWords API code sample.
Then we’ll examine a few common use cases that illustrate how the code samples can be used to integrate practically any API functionality into your app.
Anatomy of an API code sample
The code samples provided with the client libraries cover the most common API functions. They handle most back-end tasks automatically and greatly simplify AdWords API apps development.
Let’s take a look at the typical structure of an AdWords API code example. Click the tab below for the language of your choice:
In your IDE, open the sample file we used in the previous guide: GetCampaigns.java.
In GetCampaigns.java, you’ll notice some boilerplate code in main that does the following:
You’ll become familiar with these as you explore the code samples in the client library.
There’s one other line in the GetCampaigns sample you might need: Recall that in the previous guide, we set the client customer ID in the ads.properties file.
But what if you have many client customer accounts under your manager account? In that case, you can remove the client customer ID from the ads.properties file, and programmatically set it via the session object. After the object is built, call setClientCustomerID to dynamically set it.
In your IDE, open the sample file we used in the previous guide: GetCampaigns.cs.
You’ll see some boilerplate code in main that references AdWordsUser :
The most important classes in the C# library are the AdsUser classes. AdsUser classes typically encapsulate a single Ads account, in this case a Google Ads account.
The AdWordsUser class allows you to create a pre-configured service class that can be used for making API calls, using the settings specified in your application’s app.config file.
But what if you have many client customer accounts under your manager account? In that case, you can set it programmatically using the Config property of the AdsUser object to configure that user at runtime:
Another option is to use the constructor that accepts an AdWordsAppConfig instance, for example:
Python
In your IDE, open the sample file we used in the previous guide: get_campaigns.py.
In the sample, the comments indicate that the LoadFromStorage method is pulling credentials and properties from the googleads.yaml file. Recall that in the previous guide, we set the client customer ID in googleads.yaml. The LoadFromStorage method defaults to looking for a file with this name in your home directory, though you could pass in a path to any file with the correct yaml contents:
To pass in the location of the file:
But what if you have many client customer accounts under your manager account? In that case, you can programmatically set the client customer ID at runtime with the following code:
In your IDE, open the sample file GetCampaigns.php.
The example first generates an OAuth token:
It then uses the token to construct an API session wherein the runExample() function is executed:
runExample() is the primary function in this example; it retrieves campaign IDs and names through the use of a selector from CampaignService.
In your IDE, open the sample file we used in the previous guide: get_campaigns.pl.
In the sample, you’ll notice some code that gets credential info from your configuration file, adwords.properties:
Recall that in the previous guide, we set the client customer ID in the adwords.properties file.
Open the sample file we used in the previous guide: get_campaigns.rb.
In the sample, you’ll notice some boilerplate code in main that handles pulling credential info from the adwords_api.yml configuration file.
There’s one other line in the sample you might need: Recall that in the previous guide, we set the client customer ID in the adwords_api.yml configuration file.
But what if you have many client customer accounts under your manager account? In that case, you can remove the client customer ID from the adwords_api.yml file, and programmatically set it via the AdWords session object. After the object is built, call adwords.config.set to dynamically set it.
Accessing the code samples
You can browse all the AdWords API code samples on our client library and samples pages. The samples cover all the main areas of API functionality, including:
Now that you understand the structure of a typical AdWords API code sample, we’ll look at some use cases that demonstrate how the code samples can be used for almost any API function.
The two main buckets of the API’s functionality are reporting and automation. Let’s start with reporting.
Using code samples for reporting
We’ll begin with a code sample that downloads a criteria performance report:
You’ll see the same boilerplate code in main that we looked at earlier:
But it’s the RunExample method that has the interesting code in this class. Here we create an object hierarchy defining the report we want:
We then pass it to an instance of ReportDownloader :
The IDE console will print the location of the downloaded file.
You’ll notice the sample code specifies a report type, in this case a criteria performance report.
The sample also specifies some fields to retrieve for the report.
You’ll see the same boilerplate code we saw in the previous example, that handles authentication by pulling values from the app.config file:
But the interesting code in this sample is where we create an object hierarchy defining the report we want:
Go ahead and run DownloadCriteriaReport.cs.
The console will print the location of the downloaded file.
You’ll notice the sample code specifies a report type, in this case a criteria performance report.
The sample also specifies some fields to retrieve for the report.
Python
You’ll see the same boilerplate code we saw in the previous example, that handles authentication by pulling values from the googleads.yaml config file:
But the interesting code in this sample is the object hierarchy defining the report we want:
We then pass it to an instance of ReportDownloader :
Your console will print the location of the downloaded file.
You’ll notice the sample code specifies a report type, in this case a criteria performance report.
The sample also specifies some fields to retrieve for the report in the ‘selector’ section, for example, ‘CampaignId’, ‘AdGroupId’, etc.
The example has the standard code for authentication and building an AdWords API session. It’s in the primary function runExample() where a selector is constructed and the report defined:
Note that the example specifies a CRITERIA_PERFORMANCE_REPORT for the report type and also the fields to retrieve for the report.
The report definition is then passed to a report downloader:
Run DownloadCriteriaReportWithSelector.php and the console will print the location of the downloaded file.
You’ll see the same boilerplate code that we saw in the previous example, that handles authentication by pulling values from the adwords.properties configuration file:
But the interesting code in this sample is where we create a selector and report definition, defining the report we want:
We then pass it to an instance of ReportDownloader :
The console will print the location of the downloaded file.
You’ll notice the sample code specifies a report type, in this case a criteria performance report.
The sample also specifies some fields to retrieve for the report.
You’ll see the same boilerplate code that we looked in the previous example, that handles authentication by pulling values from the adwords_api.yml configuration file:
But the interesting code in this sample is where we create an object hierarchy defining the report we want:
We then pass it to the report_utils.download_report_as_file method:
You’ll notice the sample code specifies a report type, in this case a criteria performance report.
The sample also specifies some fields to retrieve for the report.
See the Report Types page for the complete list of report types and the fields they contain.
You can use this code sample, along with the information on the Report Types page, to define, create, and download any kind of reports you need.
AdWords Query Language (AWQL)
In addition to defining reports with an object hierarchy, you could also use the AdWords Query Language (AWQL). This is a SQL-like language that allows you to build reports in a less verbose way than through objects.
Compare the sample code we just ran with DownloadCriteriaReportWithAWQL.java: They retrieve the same report, but the AWQL is more concise. The report types and fields are the same for either approach.
Compare the sample code we just ran with DownloadCriteriaReportWithAWQL.cs: They retrieve the same report, but the AWQL is more concise. The report types and fields are the same for either approach.
Python
Compare the sample code we just ran with download_criteria_report_with_awql.py: They retrieve the same report, but the AWQL is more concise. The report types and fields are the same for either approach.
Compare the selector report download example with DownloadCriteriaReportWithAwql.php. Both define the same report types and fields and retrieve the same report, but the AWQL approach is more concise:
Compare the sample code we just ran with download_criteria_report_with_awql.pl: They retrieve the same report, but the AWQL is more concise. The report types and fields are the same for either approach.
In this case, the date range for the report is defined in the code directly preceding the AWQL:
Compare the sample code we just ran with download_criteria_report_with_awql.rb: They retrieve the same report, but the AWQL is more concise. The report types and fields are the same for either approach.
In this case, the date range is defined in the code directly preceding the AWQL:
Now that you understand the fundamentals of reporting, you have the tools needed to start building your own custom reporting platform.
Using code samples for automation
Here we’ll examine how you can use the code samples to make updates to your Google Ads accounts, and a few other popular use cases, and see how these examples serve as the basis for almost any kind of automation.
Pause and resume ad groups
One of the most common API use cases is to pause and resume ad groups. For example, you could pause an ad when inventory for an item is depleted, resulting in better use of your advertising budget.
This use case highlights the power of integrating your own systems, such as inventory tracking, with the AdWords API.
We’ll use the code samples to pause and resume an ad group:
Start your IDE and open the UpdateAdGroup.java sample.
We see again the typical boilerplate code in main that we saw before. This time main has a placeholder string near the bottom for the ID of the ad group.
Where would you get that ID? You could get it programmatically, through the get() method of the AdGroupService interface. A shortcut for getting the ID is to grab it from the URL of the Google Ads UI when viewing that ad group.
Once again the runExample method has the interesting code. Let’s see what it’s doing, step by step:
First it gets a reference to the AdGroupService interface because it will be updating an ad group. To update other entities you would use their corresponding service. A full list of services is available in Objects, Methods, and Services.
Then, it creates a new ad group object and sets the ID of the new object to the ID of the ad group it wants to update.
It then creates an AdGroupOperation using the newly created ad group object as the operand, and SET as the operator.
Last, it calls the mutate() method of the AdGroupService interface, passing in the ad group operation object.
Go ahead and replace the placeholder with an adgroup ID from your test client account and try running the code. After it runs, log in to the test account in the Google Ads UI, and confirm the status has been changed.
In your IDE, and open the UpdateAdGroup.cs sample.
We see again the typical boilerplate code in main that we saw in the earlier sections. This time main has a placeholder string near the bottom for the ID of the ad group.
Where would you get that ID? You could get it programmatically, through the get() method of the AdGroupService interface. A shortcut for getting the ID is to grab it from the URL of the Google Ads UI when viewing that ad group.
Once again the runExample method has the interesting code. Let’s see what it’s doing, step by step:
First it gets a reference to the AdGroupService interface because it will be updating an ad group. To update other entities you would use their corresponding service. A full list of services is available in the Objects, Methods, and Services guide.
Then, it creates a new AdGroup object and sets the ID of the new object to the ID of the ad group it wants to update.
It then creates an AdGroupOperation using the newly created adGroup object as the operand, and SET as the operator.
Last, it calls the mutate() method of the AdGroupService interface, passing in the AdGroupOperation object.
Go ahead and replace the placeholder with an ad group ID from your test client account and try running the code. After it runs, log in to the test account in the Google Ads UI, and confirm the status has been changed.
Python
In your IDE, open the update_ad_group.py sample.
We see again the typical boilerplate code where the LoadFromStorage method is pulling credentials and properties from the googleads.yaml config file. This time a placeholder string is added for the ID of the ad group.
Where would you get that ID? You could get it programmatically, through the get() method of the AdGroupService interface. A shortcut for getting the ID is to grab it from the URL of the Google Ads UI when viewing that ad group.
The interesting code comes after. Let’s see what it’s doing, step by step:
First it gets a reference to the AdGroupService interface because it will be updating an ad group. To update other entities you would use their corresponding service. A full list of services is available in the Objects, Methods, and Services guide.
Last, it calls the mutate() method of the ad group service interface, passing in the ad group operation object.
Go ahead and replace the placeholder with an adgroup ID from your test client account and try running the code. After it runs, log in to the test account in the Google Ads UI, and confirm the status has been changed.
The particular ad is identified through the ad group and ad IDs:
The ad group ID can be retrieved through the get() method from AdGroupService, or from the URL of the Google Ads UI when viewing the ad group.
Let’s now go through runExample() step-by-step:
Replace the placeholders with appropriate IDs from your test client account and run the code. After it completes, log in to the test account from the Google Ads UI and verify that the status was changed.
In your IDE, open the update_ad_group.pl sample.
We see again at the bottom the typical boilerplate code we saw before, that pulls credentials from the adwords.properties configuration file.
In this sample, a placeholder string is added for the ID of the ad group and ad you want to pause.
Where would you get that ID? You could get it programmatically, through the get() method of the AdGroupService interface. A shortcut for getting the ID is to grab it from the URL of the Google Ads UI when viewing that ad group.
The interesting code in this sample comes when the example is run. Let’s see what it’s doing, step by step:
It then creates an ad group operation using the newly created ad group object as the operand, and SET as the operator.
Last, it calls the mutate() method of the AdGroupService interface, passing in the ad group operation object.
Go ahead and replace the placeholder with an adgroup ID from your test client account and try running the code. After it runs, log in to the test account in the Google Ads UI, and confirm the status has been changed.
We see again the typical boilerplate code in that we saw before, that pulls credentials from the adwords_api.yml configuration file. We see a little further down a placeholder string for the ID of the ad group.
Where would you get that ID? You could get it programmatically, through the get() method of the AdGroupService interface. A shortcut for getting the ID is to grab it from the URL of the Google Ads UI when viewing that ad group.
Once again the interesting code is where the sample is run. Let’s see what it’s doing, step by step:
First it gets a reference to the AdGroup service interface because it will be updating an ad group. To update other entities you would use their corresponding service. A full list of services is available in the Objects, Methods, and Services guide.
Last, it calls the mutate() method of the AdGroupService interface, passing in the ad group operation object.
Go ahead and replace the placeholder with an adgroup ID from your test client account and try running the code. After it runs, log in to the test account in the Google Ads UI, and confirm the status has been changed.
Reviewing the pattern
The same process and pattern we used to pause and resume the ad group above is used for most updates through the API, so it’s worth reviewing the steps:
This was an update, so we used the SET operator. Adds or removals would use the ADD or REMOVE operators.
If this seems confusing, take a look at other code samples and you’ll quickly see the pattern.
Now that you know the pattern, you can easily make many other updates, for example modifying the bid for an ad group.
Modify bids for an ad group
Another popular use case is programmatically modifying a bid. The canonical example is raising the bid for an umbrella ad when its raining. Your app could consume a weather web service, and then use the AdWords API to increase the bid for this ad group.
You could modify the same UpdateAdGroup sample we looked at above to make this update: Instead of setting AdGroupStatus you would set the bidding strategy. See the Bidding guide for more information.
Create new campaigns
We don’t need to set the IDs here because these are new entities that don’t have IDs yet.
We don’t need to set the IDs here because these are new entities that don’t have IDs yet.
Python
We don’t need to set the IDs here because these are new entities that don’t have IDs yet.
We don’t need to set the IDs here because these are new entities that don’t have IDs yet.
We don’t need to set the IDs here because these are new entities that don’t have IDs yet.
Next steps
Now that you’ve got the basics, you’ll want to see Objects, Methods, and Services and related guides to learn more about the API’s architecture, services, and features.
You’ll then be ready to start building your own app, taking full advantage of the increased efficiency through automation, and greater visibility through custom reporting, that the AdWords API offers.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.