Targeting Samples

The code samples below provide examples of common targeting functions using the AdWords API. Client Library.

Add targeting criteria to a campaign

#!/usr/bin/perl -w
#
# Copyright 2017, Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example adds various types of targeting criteria to a campaign. To get
# campaigns, run basic_operations/get_campaigns.pl.

use strict;
use lib "../../../lib";
use utf8;

use Google::Ads::AdWords::Client;
use Google::Ads::AdWords::Logging;
use Google::Ads::AdWords::v201708::CampaignCriterionOperation;
use Google::Ads::AdWords::v201708::ConstantOperand;
use Google::Ads::AdWords::v201708::Function;
use Google::Ads::AdWords::v201708::Language;
use Google::Ads::AdWords::v201708::Location;
use Google::Ads::AdWords::v201708::LocationExtensionOperand;
use Google::Ads::AdWords::v201708::LocationGroups;
use Google::Ads::AdWords::v201708::Platform;

use Cwd qw(abs_path);

# Replace with valid values of your account.
my $campaign_id = "INSERT_CAMPAIGN_ID_HERE";
# Replace the value below with the ID of a feed that has been configured for
# location targeting, meaning it has an ENABLED FeedMapping with criterionType
# of 77. Feeds linked to a GMB account automatically have this FeedMapping.
# If you don't have such a feed, do not set this value e.g.
# my $location_feed_id;
my $location_feed_id = "INSERT_LOCATION_FEED_ID_HERE";

# Example main subroutine.
sub add_campaign_targeting_criteria {
  my $client           = shift;
  my $campaign_id      = shift;
  my $location_feed_id = shift;

  my @criteria = ();

  # Create locations. The IDs can be found in the documentation or retrieved
  # with the LocationCriterionService.
  my $california = Google::Ads::AdWords::v201708::Location->new({id => 21137});
  push @criteria, $california;
  my $mexico = Google::Ads::AdWords::v201708::Location->new({
      id => 2484    # Mexico
  });
  push @criteria, $mexico;

  # Create languages. The IDs can be found in the documentation or retrieved
  # with the ConstantDataService.
  my $english = Google::Ads::AdWords::v201708::Language->new({id => 1000});
  push @criteria, $english;
  my $spanish = Google::Ads::AdWords::v201708::Language->new({id => 1003});
  push @criteria, $spanish;

  if ($location_feed_id) {
    # Distance targeting. Area of 10 miles around targets above.
    my $radius = Google::Ads::AdWords::v201708::ConstantOperand->new({
        type        => "DOUBLE",
        unit        => "MILES",
        doubleValue => 10.0
    });
    my $radiusLocationGroup =
      Google::Ads::AdWords::v201708::LocationGroups->new({
        matchingFunction => Google::Ads::AdWords::v201708::Function->new({
            operator => "IDENTITY",
            lhsOperand =>
              Google::Ads::AdWords::v201708::LocationExtensionOperand->new(
              {radius => $radius})}
        ),
        feedId => $location_feed_id
      });
    push @criteria, $radiusLocationGroup;
  }

  # Create operations.
  my @operations = ();
  foreach my $criterion (@criteria) {
    my $operation =
      Google::Ads::AdWords::v201708::CampaignCriterionOperation->new({
        operator => "ADD",
        operand  => Google::Ads::AdWords::v201708::CampaignCriterion->new({
            campaignId => $campaign_id,
            criterion  => $criterion
          })});
    push @operations, $operation;
  }

  # Set campaign criteria.
  my $result =
    $client->CampaignCriterionService()->mutate({operations => \@operations});

  # Display campaign criteria.
  if ($result->get_value()) {
    foreach my $campaign_criterion (@{$result->get_value()}) {
      printf "Campaign criterion with campaign id '%s', criterion id '%s', " .
        "and type '%s' was added.\n",
        $campaign_criterion->get_campaignId(),
        $campaign_criterion->get_criterion()->get_id(),
        $campaign_criterion->get_criterion()->get_type();
    }
  } else {
    print "No campaign criteria were added.\n";
  }

  return 1;
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Log SOAP XML request, response and API errors.
Google::Ads::AdWords::Logging::enable_all_logging();

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

# By default examples are set to die on any server returned fault.
$client->set_die_on_faults(1);

# Call the example
add_campaign_targeting_criteria($client, $campaign_id, $location_feed_id);

Add demographic targeting critera to an ad group

#!/usr/bin/perl -w
#
# Copyright 2017, Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example adds various types of targeting criteria to a campaign. To get
# campaigns, run basic_operations/get_campaigns.pl.

use strict;
use lib "../../../lib";
use utf8;

use Google::Ads::AdWords::Client;
use Google::Ads::AdWords::Logging;
use Google::Ads::AdWords::v201708::AdGroupCriterionOperation;
use Google::Ads::AdWords::v201708::AgeRange;
use Google::Ads::AdWords::v201708::BiddableAdGroupCriterion;
use Google::Ads::AdWords::v201708::Gender;

use Cwd qw(abs_path);

use constant GENDER_MALE            => 11;
use constant AGE_RANGE_UNDETERMINED => 503999;

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

# Example main subroutine.
sub add_demographic_targeting_criteria {
  my $client      = shift;
  my $ad_group_id = shift;

  my @criteria = ();

  # Create gender criteria. The IDs can be found in the documentation:
  # https://developers.google.com/adwords/api/docs/appendix/genders.
  my $gender_male =
    Google::Ads::AdWords::v201708::Gender->new({id => GENDER_MALE});
  push @criteria, $gender_male;

  # Create age range criteria. The IDs can be found in the documentation:
  # https://developers.google.com/adwords/api/docs/appendix/ages.
  my $age_range = Google::Ads::AdWords::v201708::AgeRange->new(
    {id => AGE_RANGE_UNDETERMINED});
  push @criteria, $age_range;

  # Create operations.
  my @operations = ();
  foreach my $criterion (@criteria) {
    my $operation =
      Google::Ads::AdWords::v201708::AdGroupCriterionOperation->new({
        operator => "ADD",
        operand => Google::Ads::AdWords::v201708::BiddableAdGroupCriterion->new(
          {
            adGroupId => $ad_group_id,
            criterion => $criterion
          })});
    push @operations, $operation;
  }

  # Add ad group criteria.
  my $result =
    $client->AdGroupCriterionService()->mutate({operations => \@operations});

  # Display campaign criteria.
  if ($result->get_value()) {
    foreach my $ad_group_criterion (@{$result->get_value()}) {
      printf "Ad group criterion with ad group id '%s', criterion id '%s', " .
        "and type '%s' was added.\n",
        $ad_group_criterion->get_adGroupId(),
        $ad_group_criterion->get_criterion()->get_id(),
        $ad_group_criterion->get_criterion()->get_type();
    }
  } else {
    print "No ad group criteria were added.\n";
  }

  return 1;
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Log SOAP XML request, response and API errors.
Google::Ads::AdWords::Logging::enable_all_logging();

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

# By default examples are set to die on any server returned fault.
$client->set_die_on_faults(1);

# Call the example
add_demographic_targeting_criteria($client, $ad_group_id);

Get all campaign targeting criteria

#!/usr/bin/perl -w
#
# Copyright 2017, Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example gets all campaign targeting criteris for a campaign.
# To add campaign targeting criteria, run
# targeting/add_campaign_targeting_criteria.pl. To get campaigns, run
# basic_operations/get_campaigns.pl.

use strict;
use lib "../../../lib";
use utf8;

use Google::Ads::AdWords::Client;
use Google::Ads::AdWords::Logging;
use Google::Ads::AdWords::v201708::Selector;
use Google::Ads::AdWords::v201708::Paging;
use Google::Ads::AdWords::Utilities::PageProcessor;

use Cwd qw(abs_path);

use constant PAGE_SIZE => 500;

# Replace with valid values of your account.
my $campaign_id = "INSERT_CAMPAIGN_ID_HERE";

# Example main subroutine.
sub get_campaign_targeting_criteria {
  my $client      = shift;
  my $campaign_id = shift;

  # Create predicate.
  my $campaign_predicate = Google::Ads::AdWords::v201708::Predicate->new({
      field    => "CampaignId",
      operator => "IN",
      values   => [$campaign_id]});

  # Create selector.
  my $paging = Google::Ads::AdWords::v201708::Paging->new({
      startIndex    => 0,
      numberResults => PAGE_SIZE
  });
  my $selector = Google::Ads::AdWords::v201708::Selector->new({
      predicates => [$campaign_predicate],
      fields     => ["Id", "CriteriaType", "CampaignId"],
      paging     => $paging
  });

  # Paginate through results.
  # The contents of the subroutine will be executed for each campaign criterion.
  Google::Ads::AdWords::Utilities::PageProcessor->new({
      client   => $client,
      service  => $client->CampaignCriterionService(),
      selector => $selector
    }
    )->process_entries(
    sub {
      my ($campaign_criterion) = @_;
      my $negative =
        $campaign_criterion->isa(
        "Google::Ads::AdWords::v201708::NegativeCampaignCriterion")
        ? "Negative "
        : "";
      printf $negative . "Campaign criterion with id \"%d\" and type " .
        "\"%s\" was found for campaign id \"%s\".\n",
        $campaign_criterion->get_criterion()->get_id(),
        $campaign_criterion->get_criterion()->get_Criterion__Type(),
        $campaign_criterion->get_campaignId();
    });

  return 1;
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Log SOAP XML request, response and API errors.
Google::Ads::AdWords::Logging::enable_all_logging();

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

# By default examples are set to die on any server returned fault.
$client->set_die_on_faults(1);

# Call the example
get_campaign_targeting_criteria($client, $campaign_id);

Get all targetable languages and carriers

#!/usr/bin/perl -w
#
# Copyright 2017, Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example illustrates how to retrieve all languages and carriers available
# for targeting.

use strict;
use lib "../../../lib";
use utf8;

use Google::Ads::AdWords::Client;
use Google::Ads::AdWords::Logging;

use Cwd qw(abs_path);

# Example main subroutine.
sub get_targetable_languages_and_carriers {
  my $client = shift;

  # Get all languages from ConstantDataService.
  my $languages = $client->ConstantDataService()->getLanguageCriterion();
  if ($languages) {
    foreach my $language (@{$languages}) {
      printf "Language name is '%s', ID is %d and code is '%s'.\n",
        $language->get_name(), $language->get_id(),
        $language->get_code();
    }
  }

  # Get all carriers from ConstantDataService.
  my $carriers = $client->ConstantDataService()->getCarrierCriterion();
  if ($carriers) {
    foreach my $carrier (@{$carriers}) {
      printf "Carrier name is '%s', ID is %d and country code is '%s'.\n",
        $carrier->get_name(), $carrier->get_id(),
        $carrier->get_countryCode();
    }
  }

  return 1;
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Log SOAP XML request, response and API errors.
Google::Ads::AdWords::Logging::enable_all_logging();

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

# By default examples are set to die on any server returned fault.
$client->set_die_on_faults(1);

# Call the example
get_targetable_languages_and_carriers($client);

Get location criteria by name

#!/usr/bin/perl -w
#
# Copyright 2017, Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example gets location criteria by name.

use strict;
use lib "../../../lib";
use utf8;

use Google::Ads::AdWords::Client;
use Google::Ads::AdWords::Logging;
use Google::Ads::AdWords::v201708::OrderBy;
use Google::Ads::AdWords::v201708::Predicate;
use Google::Ads::AdWords::v201708::Selector;

use Cwd qw(abs_path);

# Example main subroutine.
sub lookup_location {
  my $client = shift;

  # Create selector.
  my $selector = Google::Ads::AdWords::v201708::Selector->new({
      fields => [
        "Id",              "LocationName", "CanonicalName", "DisplayType",
        "ParentLocations", "Reach",        "TargetingStatus"
      ],
      predicates => [
        Google::Ads::AdWords::v201708::Predicate->new({
            field    => "LocationName",
            operator => "IN",
            values   => ["Paris", "Quebec", "Spain", "Deutschland"]}
        ),
        Google::Ads::AdWords::v201708::Predicate->new({
            field    => "Locale",
            operator => "EQUALS",
            values   => "en"
          })
      ],
      ordering => [
        Google::Ads::AdWords::v201708::OrderBy->new({
            field     => "LocationName",
            sortOrder => "ASCENDING"
          })]});

  # Get all campaigns.
  my $location_criteria =
    $client->LocationCriterionService()->get({selector => $selector});

  # Display campaigns.
  foreach my $location_criterion (@{$location_criteria}) {
    my @parent_locations = ();
    if ($location_criterion->get_location()->get_parentLocations()) {
      foreach my $parent_location (
        @{$location_criterion->get_location()->get_parentLocations()})
      {
        push @parent_locations,
          sprintf("%s (%s)",
          $parent_location->get_locationName(),
          $parent_location->get_displayType());
      }
    }

    my $location = $location_criterion->get_location();
    printf "The search term '%s' returned the location '%s' of type '%s' "
      . "with parent locations '%s', reach '%d' and targeting status '%s'.\n",
      $location_criterion->get_searchTerm, $location->get_locationName(),
      $location->get_displayType(),
      scalar(@parent_locations) ? join(", ", @parent_locations) : "N/A",
      $location_criterion->get_reach(), $location->get_targetingStatus();
  }

  return 1;
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Log SOAP XML request, response and API errors.
Google::Ads::AdWords::Logging::enable_all_logging();

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

# By default examples are set to die on any server returned fault.
$client->set_die_on_faults(1);

# Call the example
lookup_location($client);

Send feedback about...

AdWords API
AdWords API
Need help? Visit our support page.