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 all the most common API functions. They handle most back-end tasks automatically, and make developing AdWords API apps a lot easier.

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:

Java

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:

  • Credential generation
  • AdWords session creation
  • AdWords services instantiation

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 AdWords session object. After the object is built, call setClientCustomerID to dynamically set it.

// Construct an AdWordsSession.
AdWordsSession session = new AdWordsSession.Builder()
    .fromFile()
    .withOAuth2Credential(oAuth2Credential)
    .build();

session.setClientCustomerID("123-456-7890");

AdWordsServices adWordsServices = new AdWordsServices();

runExample(adWordsServices, session);

C#

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:
public static void Main(string[] args) {
    GetCampaigns codeExample = new GetCampaigns();
    Console.WriteLine(codeExample.Description);
    try {
      codeExample.Run(new AdWordsUser());
    }
}

The most important classes in the C# library are the AdsUser classes. AdsUser classes typically encapsulate a single Ads account, in this case an AdWords account.

The AdsWordsUser 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.

// Create a new AdWordsUser with the App.config settings.
AdWordsUser user = new AdWordsUser();

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:

// Create a default AdWordsUser instance. If any configuration
// is available in App.config, those will be used.
AdWordsUser user = new AdWordsUser();

// Override a specific setting at runtime.
AdWordsAppConfig config = (AdWordsAppConfig) user.Config;
user.Config.clientCustomerId = "123-456-7890";

Another option is to use the constructor that accepts an AdWordsAppConfig instance, for example:

// Create a config object with the values in App.config.
AdWordsAppConfig config = new AdWordsAppConfig();

// Override any specific setting you wish to change.
user.Config.clientCustomerId = "123-456-7890";

AdWordsUser user = new AdWordsUser(config);

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 use the default location - your home directory:

adwords_client = adwords.AdWordsClient.LoadFromStorage()

To pass in the location of the file:

adwords_client = adwords.AdWordsClient.LoadFromStorage('C:\My\Directory\googleads.yaml')

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:

adwords_client = AdWordsClient.LoadFromStorage()
adwords_client.SetClientCustomerId('123-456-7890')

PHP

In your IDE, open the sample file GetCampaigns.php.

The example first generates an OAuth token:

// Generate a refreshable OAuth2 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())
    ->fromFile()
    ->build();

It then uses the token to construct an API session wherein the runExample() function is executed:

// Construct an API session configured from a properties file and the OAuth2
// credentials above.
$session = (new AdWordsSessionBuilder())
    ->fromFile()
    ->withOAuth2Credential($oAuth2Credential)
    ->build();
self::runExample(new AdWordsServices(), $session);

runExample() is the primary function in this example; it retrieves campaign IDs and names through the use of a selector from CampaignService.

Perl

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:

# Get AdWords Client, credentials will be read from ~/adwords.properties.
my $client = Google::Ads::AdWords::Client->new({version => "v201710"});

Recall that in the previous guide, we set the client customer ID in the adwords.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 adwords.properties, and programmatically set it by calling set_client_id:

# Get AdWords Client, credentials will be read from ~/adwords.properties.
my $client = Google::Ads::AdWords::Client->new({version => "v201710"});
$client->set_client_id("123-456-7890");

Ruby

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.

  # AdwordsApi::Api will read a config file from ENV['HOME']/adwords_api.yml
  # when called without parameters.
  adwords = AdwordsApi::Api.new

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.

# Set a new CID value
adwords.config.set("authentication.client_customer_id", "123-456-7890")

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:

  • Account management
  • Campaign management
  • Error handling
  • Optimization
  • Reporting
  • Targeting

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:

Java

Go to your IDE and open DownloadCriteriaReport.java.

You'll see the same boilerplate code in main that we looked at earlier:

public static void main(String[] args) throws Exception {
    // Generate a refreshable OAuth2 credential.
    Credential oAuth2Credential = new OfflineCredentials.Builder()
        .forApi(Api.ADWORDS)
        .fromFile()
        .build()
        .generateCredential();

    // Construct an AdWordsSession.
    AdWordsSession session = new AdWordsSession.Builder()
        .fromFile()
        .withOAuth2Credential(oAuth2Credential)
        .build();

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:

// Create report definition.
    ReportDefinition reportDefinition = new ReportDefinition();
    reportDefinition.setReportName("Criteria performance report #" + System.currentTimeMillis());
    reportDefinition.setDateRangeType(ReportDefinitionDateRangeType.YESTERDAY);
    reportDefinition.setReportType(ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT);
    reportDefinition.setDownloadFormat(DownloadFormat.CSV);

We then pass it to an instance of ReportDownloader:

 ReportDownloadResponse response =
          new ReportDownloader(session).downloadReport(reportDefinition);
      response.saveToFile(reportFile);

Go ahead and run DownloadCriteriaReport.java.

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.

reportDefinition.setReportType(ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT);

The sample also specifies some fields to retrieve for the report.

Selector selector = new Selector();
    selector.getFields().addAll(Lists.newArrayList("CampaignId",
        "AdGroupId",
        "Id",
        "CriteriaType",
        "Criteria",
        "FinalUrls",
        "Impressions",
        "Clicks",
        "Cost"));

C#

Go to your IDE and open DownloadCriteriaReport.cs.

You'll see the same boilerplate code we saw in the previous example, that handles authentication by pulling values from the app.config file:

public static void Main(string[] args) {
  GetCampaigns codeExample = new GetCampaigns();
  Console.WriteLine(codeExample.Description);
  try {
    codeExample.Run(new AdWordsUser());
  }
}

But the interesting code in this sample is where we create an object hierarchy defining the report we want:

public void Run(AdWordsUser user, string fileName) {
  ReportDefinition definition = new ReportDefinition() {
    reportName = "Last 7 days CRITERIA_PERFORMANCE_REPORT",
        reportType = ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT,
        downloadFormat = DownloadFormat.GZIPPED_CSV,
        dateRangeType = ReportDefinitionDateRangeType.LAST_7_DAYS,
  }
}

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.

reportType = ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT,

The sample also specifies some fields to retrieve for the report.

selector = new Selector() {
  fields = new string[] {"CampaignId", "AdGroupId", "Id", "CriteriaType", "Criteria",
      "FinalUrls", "Clicks", "Impressions", "Cost"},
      predicates = new Predicate[] {
        Predicate.In("Status", new string[] {"ENABLED", "PAUSED"})
      }
}

Python

Go to your IDE and open download_criteria_report_with_selector.py.

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:

adwords_client = adwords.AdWordsClient.LoadFromStorage()
  main(adwords_client)

But the interesting code in this sample is the object hierarchy defining the report we want:

# Create report definition.
report = {
    'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT',
    'dateRangeType': 'LAST_7_DAYS',
    'reportType': 'CRITERIA_PERFORMANCE_REPORT',
    'downloadFormat': 'CSV',
    'selector': {
        'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType',
                   'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost']
    }
}

We then pass it to an instance of ReportDownloader:

report_downloader.DownloadReport(
    report, sys.stdout, skip_report_header=False, skip_column_header=False,
    skip_report_summary=False)

Go ahead and run download_criteria_report_with_selector.py.

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.

PHP

Go to your IDE and open DownloadCriteriaReportWithSelector.php.

The example has the standard code for authentication and building an AdWords session. It's in the primary function runExample() where a selector is constructed and the report defined:

// Create selector.
$selector = new Selector();
$selector->setFields(['CampaignId', 'AdGroupId', 'Id', 'Criteria',
    'CriteriaType', 'Impressions', 'Clicks', 'Cost']);

// Create report definition.
$reportDefinition = new ReportDefinition();
$reportDefinition->setSelector($selector);
$reportDefinition->setReportName(
    'Criteria performance report #' . uniqid());
$reportDefinition->setDateRangeType(
    ReportDefinitionDateRangeType::LAST_7_DAYS);
$reportDefinition->setReportType(
    ReportDefinitionReportType::CRITERIA_PERFORMANCE_REPORT);
$reportDefinition->setDownloadFormat(DownloadFormat::CSV);

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:

// Download report.
$reportDownloader = new ReportDownloader($session);
$reportDownloadResult =
    $reportDownloader->downloadReport($reportDefinition);
$reportDownloadResult->saveToFile($filePath);
printf("Report with name '%s' was downloaded to '%s'.\n",
    $reportDefinition->getReportName(), $filePath);

Run DownloadCriteriaReportWithSelector.php and the console will print the location of the downloaded file.

Perl

Go to your IDE and open download_criteria_report_with_selector.pl.

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:

# Get AdWords Client, credentials will be read from ~/adwords.properties.
my $client = Google::Ads::AdWords::Client->new({version => "v201710"});

But the interesting code in this sample is where we create a selector and report definition, defining the report we want:

my $report_definition = Google::Ads::AdWords::Reports::ReportDefinition->new({
      reportName     => "Last 7 days CRITERIA_PERFORMANCE_REPORT #" . $today,
      dateRangeType  => "LAST_7_DAYS",
      reportType     => "CRITERIA_PERFORMANCE_REPORT",
      downloadFormat => "CSV",
      selector       => $selector
});

We then pass it to an instance of ReportDownloader:

# Download the report using the appropriate method on ReportDownloadHandler.
my $result;
if ($output_file) {
  $result = $report_handler->save($output_file);
} else {
  $result = $report_handler->get_as_string();
}

Go ahead and run download_criteria_report_with_selector.pl.

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.

reportType => "CRITERIA_PERFORMANCE_REPORT",

The sample also specifies some fields to retrieve for the report.

# Create selector.
my $selector = Google::Ads::AdWords::Reports::Selector->new({
    fields => [
      "CampaignId", "AdGroupId", "Id",          "CriteriaType",
      "Criteria",   "FinalUrls", "Impressions", "Clicks",
      "Cost"
    ]
});

Ruby

Open download_criteria_report_with_selector.rb.

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:

def download_criteria_report_with_selector(file_name)
  # AdwordsApi::Api will read a config file from ENV['HOME']/adwords_api.yml
  # when called without parameters.
  adwords = AdwordsApi::Api.new

But the interesting code in this sample is where we create an object hierarchy defining the report we want:

# Define report definition. You can also pass your own XML text as a string.
report_definition = {
  :selector => {
    :fields => ['CampaignId', 'AdGroupId', 'Id', 'Criteria', 'CriteriaType',
        'FinalUrls', 'Impressions', 'Clicks', 'Cost'],
  },
...

  :report_name => 'Last 7 days CRITERIA_PERFORMANCE_REPORT',
  :report_type => 'CRITERIA_PERFORMANCE_REPORT',
  :download_format => 'CSV',
  :date_range_type => 'LAST_7_DAYS',
}

We then pass it to the report_utils.download_report_as_file method:

# Download report, using "download_report_as_file" utility method.
# To retrieve the report as return value, use "download_report" method.
report_utils.download_report_as_file(report_definition, file_name)
puts "Report was downloaded to '%s'." % file_name
end

Go ahead and run download_criteria_report_with_selector.rb. The location of the downloaded file with be printed out on the console.

You'll notice the sample code specifies a report type, in this case a criteria performance report.

:report_type => 'CRITERIA_PERFORMANCE_REPORT',

The sample also specifies some fields to retrieve for the report.

:fields => ['CampaignId', 'AdGroupId', 'Id', 'Criteria', 'CriteriaType',
          'FinalUrls', 'Impressions', 'Clicks', 'Cost'],

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.

Java

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.

String query = "SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, "
    + "Impressions, Clicks, Cost FROM CRITERIA_PERFORMANCE_REPORT "
    + "WHERE Status IN [ENABLED, PAUSED] "
    + "DURING YESTERDAY";

C#

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.

string query = "SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, Impressions, " +
    "Clicks, Cost FROM CRITERIA_PERFORMANCE_REPORT WHERE Status IN [ENABLED, PAUSED] " +
    "DURING LAST_7_DAYS";

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.

report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, '
                'FinalUrls, Impressions, Clicks, Cost '
                'FROM CRITERIA_PERFORMANCE_REPORT '
                'WHERE Status IN [ENABLED, PAUSED] '
                'DURING LAST_7_DAYS')

PHP

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:

// Create report query to get the data for last 7 days.
$reportQuery = 'SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, '
    . 'Impressions, Clicks, Cost FROM CRITERIA_PERFORMANCE_REPORT '
    . 'WHERE Status IN [ENABLED, PAUSED] DURING LAST_7_DAYS';

Perl

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.

my $report_query =
  "SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, " .
  "Impressions, Clicks, Cost FROM CRITERIA_PERFORMANCE_REPORT " .
  "WHERE Status IN [ENABLED, PAUSED] " . "DURING $last_4_days, $yesterday";

In this case, the date range for the report is defined in the code directly preceding the AWQL:

# Create report query.
my (undef, undef, undef, $mday, $mon, $year) = localtime(time - 60 * 60 * 24);
my $yesterday = sprintf("%d%02d%02d", ($year + 1900), ($mon + 1), $mday);
(undef, undef, undef, $mday, $mon, $year) =
  localtime(time - 60 * 60 * 24 * 4);
my $last_4_days = sprintf("%d%02d%02d", ($year + 1900), ($mon + 1), $mday);

Ruby

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.

report_query = 'SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' +
    'Impressions, Clicks, Cost FROM CRITERIA_PERFORMANCE_REPORT ' +
    'WHERE Status IN [ENABLED, PAUSED] ' +
    'DURING %s' % date_range

In this case, the date range is defined in the code directly preceding the AWQL:

# Prepare a date range for the last week. Instead you can use 'LAST_7_DAYS'.
date_range = '%s,%s' % [
    DateTime.parse((Date.today - 7).to_s).strftime('%Y%m%d'),
    DateTime.parse((Date.today - 1).to_s).strftime('%Y%m%d')
]

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 AdWords 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:

Java

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.

public static void main(String[] args) throws Exception {
    // Generate a refreshable OAuth2 credential.
    Credential oAuth2Credential = new OfflineCredentials.Builder()
        .forApi(Api.ADWORDS)
        .fromFile()
        .build()
        .generateCredential();

    // Construct an AdWordsSession.
    AdWordsSession session = new AdWordsSession.Builder()
        .fromFile()
        .withOAuth2Credential(oAuth2Credential)
        .build();

    Long adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE");
}

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 AdWords web interface 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.

// Get the AdGroupService.
AdGroupServiceInterface adGroupService =
    adWordsServices.get(session, AdGroupServiceInterface.class);

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.

// Create ad group with updated status.
AdGroup adGroup = new AdGroup();
adGroup.setId(adGroupId);

Then it sets the status to PAUSED.

adGroup.setStatus(AdGroupStatus.PAUSED);

It then creates an AdGroupOperation using the newly created ad group object as the operand, and SET as the operator.

// Create operations.
AdGroupOperation operation = new AdGroupOperation();
operation.setOperand(adGroup);
operation.setOperator(Operator.SET);

Last, it calls the mutate() method of the AdGroupService interface, passing in the ad group operation object.

// Update ad group.
AdGroupReturnValue result = adGroupService.mutate(operations);

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 AdWords web interface, and confirm the status has been changed.

C#

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.

public static void Main(string[] args) {
    UpdateAdGroup codeExample = new UpdateAdGroup();
    Console.WriteLine(codeExample.Description);
    try {
      long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
      codeExample.Run(new AdWordsUser(), adGroupId);
    }
}

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 AdWords web interface 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.

public void Run(AdWordsUser user, long adGroupId) {
    // Get the AdGroupService.
    AdGroupService adGroupService =
        (AdGroupService) user.GetService(AdWordsService.v201710.AdGroupService);
}

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.

// Create the ad group.
AdGroup adGroup = new AdGroup();
adGroup.status = AdGroupStatus.PAUSED;
adGroup.id = adGroupId;

It also sets the status to PAUSED.

adGroup.status = AdGroupStatus.PAUSED;

It then creates an AdGroupOperation using the newly created adGroup object as the operand, and SET as the operator.

// Create the operation.
AdGroupOperation operation = new AdGroupOperation();
operation.@operator = Operator.SET;
operation.operand = adGroup;

Last, it calls the mutate() method of the AdGroupService interface, passing in the AdGroupOperation object.

// Update the ad group.
AdGroupReturnValue retVal = adGroupService.mutate(new AdGroupOperation[] {operation});

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 AdWords web interface, 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.

AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'

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 AdWords web interface 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.

def main(client, ad_group_id):
  # Initialize appropriate service.
  ad_group_service = client.GetService('AdGroupService', version='v201710')

Then, it sets the ID to the ID of the ad group it wants to update, and sets the status to PAUSED.

# Construct operations and update an ad group.
  operations = [{
      'operator': 'SET',
      'operand': {
          'id': ad_group_id,
          'status': 'PAUSED'

It then creates an ad group operation using the newly created ad group object as the operand, and SET as the operator, and sets the status to PAUSED.

# Construct operations and update an ad group.
  operations = [{
      'operator': 'SET',
      'operand': {
          'id': ad_group_id,
          'status': 'PAUSED'

Last, it calls the mutate() method of the ad group service interface, passing in the ad group operation object.

ad_groups = ad_group_service.mutate(operations)

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 AdWords web interface, and confirm the status has been changed.

PHP

In your IDE, open PauseAd.php.

The particular ad is identified through the ad group and ad IDs:

const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';
const AD_ID = 'INSERT_AD_ID_HERE';

The ad group ID can be retrieved through the get() method from AdGroupService, or from the URL of the AdWords web interface when viewing the ad group.

Let's now go through runExample() step-by-step:

  1. Get a reference to AdGroupService since we're updating an ad group.
    $adGroupAdService =
        $adWordsServices->get($session, AdGroupAdService::class);
    
  2. Create an ad object.
    $ad = new Ad();
    $ad->setId($adId);
    
  3. Creates an ad group ad object and set its ad group ID and ad.
    $adGroupAd = new AdGroupAd();
    $adGroupAd->setAdGroupId($adGroupId);
    $adGroupAd->setAd($ad);
    
  4. Set the status of the ad group ad to PAUSED.
    $adGroupAd->setStatus(AdGroupAdStatus::PAUSED);
    
  5. Set up an operation and send it off to AdGroupAdService through the mutate() method.
    // Create ad group ad operation and add it to the list.
    $operation = new AdGroupAdOperation();
    $operation->setOperand($adGroupAd);
    $operation->setOperator(Operator::SET);
    $operations[] = $operation;
    
    // Pause the ad on the server.
    $result = $adGroupAdService->mutate($operations);
    

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 AdWords web interface and verify that the status was changed.

Perl

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.

# Replace with valid values of your account.
my $ad_group_id = "INSERT_AD_GROUP_ID_HERE";

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 AdWords web interface 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:

First it creates an ad group with updated status using the specified adGroupID. To update other entities you would use their corresponding service. A full list of services is available in the Objects, Methods, and Services guide. It then sets the status to PAUSED.

# Create ad group with updated status.
my $ad_group = Google::Ads::AdWords::v201710::AdGroup->new({
    id     => $ad_group_id,
    status => "PAUSED"
});

It then creates an ad group operation using the newly created ad group object as the operand, and SET as the operator.

# Create operation.
my $operation = Google::Ads::AdWords::v201710::AdGroupOperation->new({
    operand  => $ad_group,
    operator => "SET"
});

Last, it calls the mutate() method of the AdGroupService interface, passing in the ad group operation object.

# Update ad group.
my $result = $client->AdGroupService()->mutate({operations => [$operation]});

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 AdWords web interface, and confirm the status has been changed.

Ruby

Open the update_ad_group.rb sample.

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.

# ID of an ad group to update.
ad_group_id = 'INSERT_AD_GROUP_ID_HERE'.to_i

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 AdWords web interface 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.

ad_group_srv = adwords.service(:AdGroupService, API_VERSION)

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, and sets its status to PAUSED, using SET as the operator.

# Prepare for updating ad group.
operation = {
  :operator => 'SET',
  :operand => {
    :status => 'PAUSED',
    :id => ad_group_id
  }
}

Last, it calls the mutate() method of the AdGroupService interface, passing in the ad group operation object.

# Update ad group.
response = ad_group_srv.mutate([operation])

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 AdWords web interface, 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:

  1. Create a new object.
  2. Set its ID to be the ID of the entity you want to modify.
  3. Set the new value of the property on that new object.
  4. Create an operation object with SET as the operator and this new entity object as the operand.
  5. Pass the operation object into the mutate() method of the appropriate service.

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

Another use case:

Java

In your IDE look at AddCampaigns.java.

It's a lot of code but follows the same pattern as above. In this case, once the object hierarchy is created we use the ADD operator to add a new budget via the BudgetService, and new campaigns via the CampaignService.

We don't need to set the IDs here because these are new entities that don't have IDs yet.

C#

In your IDE, look at AddCampaigns.cs.

It's a lot of code but follows the same pattern as above. In this case, once the object hierarchy is created we use the ADD operator to add a new budget via the BudgetService, and new campaigns via the CampaignService.

We don't need to set the IDs here because these are new entities that don't have IDs yet.

Python

In your IDE, look at add_campaigns.py.

It's a lot of code but follows the same pattern as above. In this case, once the object hierarchy is created we use the ADD operator to add a new budget via the BudgetService, and new campaigns via the CampaignService.

We don't need to set the IDs here because these are new entities that don't have IDs yet.

PHP

In your IDE, open AddCampaigns.php.

As usual, the bulk of the logic is in runExample(). We set up a budget, campaign, bidding strategy, and optional settings such as network targeting and frequency cap. Finally, we wrap the campaign with an ADD operator and send off the operation to CampaignService via mutate().

Perl

In your IDE, look at add_campaigns.pl.

It's a lot of code but follows the same pattern as above. In this case, once the object hierarchy is created we use the ADD operator to add a new budget via the BudgetService, and new campaigns via the CampaignService.

We don't need to set the IDs here because these are new entities that don't have IDs yet.

Ruby

Take a look at add_campaigns.rb.

It's a lot of code but follows the same pattern as above. In this case, once the object hierarchy is created we use the ADD operator to add a new budget via the BudgetService, and new campaigns via the CampaignService.

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.

Enviar comentarios sobre…

¿Necesitas ayuda? Visita nuestra página de asistencia.