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/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2011, Google Inc. All Rights Reserved.
#
# License:: 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 list, run get_campaigns.rb.

require 'adwords_api'

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

  # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
  # the configuration file or provide your own logger:
  # adwords.logger = Logger.new('adwords_xml.log')

  campaign_criterion_srv =
      adwords.service(:CampaignCriterionService, API_VERSION)

  # Create campaign criteria.
  campaign_criteria = [
    # Location criteria. The IDs can be found in the documentation or retrieved
    # with the LocationCriterionService.
    {:xsi_type => 'Location', :id => 21137}, # California, USA
    {:xsi_type => 'Location', :id => 2484},  # Mexico
    # Language criteria. The IDs can be found in the documentation or retrieved
    # with the ConstantDataService.
    {:xsi_type => 'Language', :id => 1000},  # English
    {:xsi_type => 'Language', :id => 1003},  # Spanish
  ]

  # Distance targeting. Area of 10 miles around targets above.
  unless location_feed_id.nil?
    campaign_criteria << {
      :xsi_type => 'LocationGroups',
      :feed_id => location_feed_id,
      :matching_function => {
        :operator => 'IDENTITY',
        :lhs_operand => [{
          :xsi_type => 'LocationExtensionOperand',
          :radius => {
            :xsi_type => 'ConstantOperand',
            :type => 'DOUBLE',
            :unit => 'MILES',
            :double_value => 10
          }
        }]
      }
    }
  end

  # Create operations.
  operations = campaign_criteria.map do |criterion|
    {:operator => 'ADD',
     :operand => {
         :campaign_id => campaign_id,
         :criterion => criterion}
    }
  end

  # Add negative campaign criterion.
  operations << {
    :operator => 'ADD',
    :operand => {
      # The 'xsi_type' field allows you to specify the xsi:type of the object
      # being created. It's only necessary when you must provide an explicit
      # type that the client library can't infer.
      :xsi_type => 'NegativeCampaignCriterion',
      :campaign_id => campaign_id,
      :criterion => {
        :xsi_type => 'Keyword',
        :text => 'jupiter cruise',
        :match_type => 'BROAD'
      }
    }
  }

  response = campaign_criterion_srv.mutate(operations)

  if response and response[:value]
    criteria = response[:value]
    criteria.each do |campaign_criterion|
      criterion = campaign_criterion[:criterion]
      puts ("Campaign criterion with campaign ID %d, criterion ID %d and " +
          "type '%s' was added.") % [campaign_criterion[:campaign_id],
          criterion[:id], criterion[:criterion_type]]
    end
  else
    puts 'No criteria were returned.'
  end
end

if __FILE__ == $0
  API_VERSION = :v201705

  begin
    campaign_id = 'INSERT_CAMPAIGN_ID_HERE'
    # Replace the value below with the ID 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, set this value to nil or delete
    # the variable.
    location_feed_id = 'INSERT_LOCATION_FEED_ID_HERE'
    add_campaign_targeting_criteria(campaign_id, location_feed_id)

  # Authorization error.
  rescue AdsCommon::Errors::OAuth2VerificationRequired => e
    puts "Authorization credentials are not valid. Edit adwords_api.yml for " +
        "OAuth2 client ID and secret and run misc/setup_oauth2.rb example " +
        "to retrieve and store OAuth2 tokens."
    puts "See this wiki page for more details:\n\n  " +
        'https://github.com/googleads/google-api-ads-ruby/wiki/OAuth2'

  # HTTP errors.
  rescue AdsCommon::Errors::HttpError => e
    puts "HTTP Error: %s" % e

  # API errors.
  rescue AdwordsApi::Errors::ApiException => e
    puts "Message: %s" % e.message
    puts 'Errors:'
    e.errors.each_with_index do |error, index|
      puts "\tError [%d]:" % (index + 1)
      error.each do |field, value|
        puts "\t\t%s: %s" % [field, value]
      end
    end
  end
end

Add demographic targeting critera to an ad group

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2012, Google Inc. All Rights Reserved.
#
# License:: 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 demographic criteria to an ad group. To get ad groups list,
# run get_ad_groups.rb.

require 'adwords_api'

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

  # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
  # the configuration file or provide your own logger:
  # adwords.logger = Logger.new('adwords_xml.log')

  ad_group_criterion_srv =
      adwords.service(:AdGroupCriterionService, API_VERSION)

  # Create ad group criteria.
  ad_group_criteria = [
    # Targeting criterion.
    {
      :xsi_type => 'BiddableAdGroupCriterion',
      :ad_group_id => ad_group_id,
      :criterion => {
        :xsi_type => 'Gender',
        # See system codes section for IDs:
        # https://developers.google.com/adwords/api/docs/appendix/genders
        :id => 11
      }
    },
    # Exclusion criterion.
    {
      :xsi_type => 'NegativeAdGroupCriterion',
      :ad_group_id => ad_group_id,
      :criterion => {
        :xsi_type => 'AgeRange',
        # See system codes section for IDs:
        # https://developers.google.com/adwords/api/docs/appendix/ages
        :id => 503999
      }
    }
  ]

  # Create operations.
  operations = ad_group_criteria.map do |criterion|
    {:operator => 'ADD', :operand => criterion}
  end

  response = ad_group_criterion_srv.mutate(operations)

  if response and response[:value]
    criteria = response[:value]
    criteria.each do |ad_group_criterion|
      criterion = ad_group_criterion[:criterion]
      puts ("Ad group criterion with ad group ID %d, criterion ID %d and " +
          "type '%s' was added.") % [ad_group_criterion[:ad_group_id],
          criterion[:id], criterion[:criterion_type]]
    end
  else
    puts 'No criteria were returned.'
  end
end

if __FILE__ == $0
  API_VERSION = :v201705

  begin
    ad_group_id = 'INSERT_AD_GROUP_ID_HERE'
    add_demographic_targeting_criteria(ad_group_id)

  # Authorization error.
  rescue AdsCommon::Errors::OAuth2VerificationRequired => e
    puts "Authorization credentials are not valid. Edit adwords_api.yml for " +
        "OAuth2 client ID and secret and run misc/setup_oauth2.rb example " +
        "to retrieve and store OAuth2 tokens."
    puts "See this wiki page for more details:\n\n  " +
        'https://github.com/googleads/google-api-ads-ruby/wiki/OAuth2'

  # HTTP errors.
  rescue AdsCommon::Errors::HttpError => e
    puts "HTTP Error: %s" % e

  # API errors.
  rescue AdwordsApi::Errors::ApiException => e
    puts "Message: %s" % e.message
    puts 'Errors:'
    e.errors.each_with_index do |error, index|
      puts "\tError [%d]:" % (index + 1)
      error.each do |field, value|
        puts "\t\t%s: %s" % [field, value]
      end
    end
  end
end

Get all campaign targeting criteria

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2011, Google Inc. All Rights Reserved.
#
# License:: 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 the campaign targets. To set
# campaign targets, run add_campaign_targeting_criteria.rb.

require 'adwords_api'

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

  # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
  # the configuration file or provide your own logger:
  # adwords.logger = Logger.new('adwords_xml.log')

  campaign_criterion_srv =
      adwords.service(:CampaignCriterionService, API_VERSION)

  # Selector to get all the targeting for this campaign.
  selector = {
    :fields => ['Id', 'CriteriaType', 'KeywordText'],
    :predicates => [
      {:field => 'CampaignId', :operator => 'EQUALS', :values => [campaign_id]}
    ],
    :paging => {
      :start_index => 0,
      :number_results => PAGE_SIZE
    }
  }

  # Set initial values.
  offset, page = 0, {}

  begin
    page = campaign_criterion_srv.get(selector)
    if page[:entries]
      page[:entries].each do |typed_criterion|
        negative = typed_criterion[:xsi_type] == 'NegativeCampaignCriterion' ?
           ' (negative)' : ''
        criterion = typed_criterion[:criterion]
        puts ("Campaign criterion%s with ID %d, type '%s' and text '%s'" +
            " was found.") %
            [negative, criterion[:id], criterion[:type], criterion[:text]]
      end
      # Increment values to request the next page.
      offset += PAGE_SIZE
      selector[:paging][:start_index] = offset
    end
  end while page[:total_num_entries] > offset

  if page.include?(:total_num_entries)
    puts "\tCampaign ID %d has %d criteria." %
        [campaign_id, page[:total_num_entries]]
  end
end

if __FILE__ == $0
  API_VERSION = :v201705
  PAGE_SIZE = 500

  begin
    # Specify campaign ID to get targeting for.
    campaign_id = 'INSERT_CAMPAIGN_ID_HERE'.to_i
    get_campaign_targeting_criteria(campaign_id)

  # Authorization error.
  rescue AdsCommon::Errors::OAuth2VerificationRequired => e
    puts "Authorization credentials are not valid. Edit adwords_api.yml for " +
        "OAuth2 client ID and secret and run misc/setup_oauth2.rb example " +
        "to retrieve and store OAuth2 tokens."
    puts "See this wiki page for more details:\n\n  " +
        'https://github.com/googleads/google-api-ads-ruby/wiki/OAuth2'

  # HTTP errors.
  rescue AdsCommon::Errors::HttpError => e
    puts "HTTP Error: %s" % e

  # API errors.
  rescue AdwordsApi::Errors::ApiException => e
    puts "Message: %s" % e.message
    puts 'Errors:'
    e.errors.each_with_index do |error, index|
      puts "\tError [%d]:" % (index + 1)
      error.each do |field, value|
        puts "\t\t%s: %s" % [field, value]
      end
    end
  end
end

Get all targetable languages and carriers

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2011, Google Inc. All Rights Reserved.
#
# License:: 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.

require 'adwords_api'

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

  # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
  # the configuration file or provide your own logger:
  # adwords.logger = Logger.new('adwords_xml.log')

  constant_data_srv = adwords.service(:ConstantDataService, API_VERSION)

  # Get all languages from ConstantDataService.
  languages = constant_data_srv.get_language_criterion()

  if languages
    languages.each do |language|
      puts "Language name is '%s', ID is %d and code is '%s'." %
          [language[:name], language[:id], language[:code]]
    end
  else
    puts 'No languages were found.'
  end

  # Get all carriers from ConstantDataService.
  carriers = constant_data_srv.get_carrier_criterion()

  if carriers
    carriers.each do |carrier|
      puts "Carrier name is '%s', ID is %d and country code is '%s'." %
          [carrier[:name], carrier[:id], carrier[:country_code]]
    end
  else
    puts 'No carriers were retrieved.'
  end
end

if __FILE__ == $0
  API_VERSION = :v201705

  begin
    get_targetable_languages_and_carriers()

  # Authorization error.
  rescue AdsCommon::Errors::OAuth2VerificationRequired => e
    puts "Authorization credentials are not valid. Edit adwords_api.yml for " +
        "OAuth2 client ID and secret and run misc/setup_oauth2.rb example " +
        "to retrieve and store OAuth2 tokens."
    puts "See this wiki page for more details:\n\n  " +
        'https://github.com/googleads/google-api-ads-ruby/wiki/OAuth2'

  # HTTP errors.
  rescue AdsCommon::Errors::HttpError => e
    puts "HTTP Error: %s" % e

  # API errors.
  rescue AdwordsApi::Errors::ApiException => e
    puts "Message: %s" % e.message
    puts 'Errors:'
    e.errors.each_with_index do |error, index|
      puts "\tError [%d]:" % (index + 1)
      error.each do |field, value|
        puts "\t\t%s: %s" % [field, value]
      end
    end
  end
end

Get location criteria by name

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2011, Google Inc. All Rights Reserved.
#
# License:: 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.

require 'adwords_api'

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

  # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
  # the configuration file or provide your own logger:
  # adwords.logger = Logger.new('adwords_xml.log')

  location_criterion_srv =
      adwords.service(:LocationCriterionService, API_VERSION)

  # List of locations to look up.
  location_names = ['Paris', 'Quebec', 'Spain', 'Deutschland']
  # Locale to retrieve names in.
  locale = 'en'

  # Get the criteria by names.
  selector = {
      :fields => ['Id', 'LocationName', 'CanonicalName', 'DisplayType',
          'ParentLocations', 'Reach', 'TargetingStatus'],
      :predicates => [
          # Location names must match exactly, only EQUALS and IN are supported.
          {:field => 'LocationName',
           :operator => 'IN',
           :values => location_names},
          # Set the locale of the returned location names.
          {:field => 'Locale', :operator => 'EQUALS', :values => [locale]}
    ]
  }
  criteria = location_criterion_srv.get(selector)

  if criteria
    criteria.each do |criterion|
      # Extract all parent location names as one comma-separated string.
      parent_location = if criterion[:location][:parent_locations] and
          !criterion[:location][:parent_locations].empty?
        locations_array = criterion[:location][:parent_locations].map do |loc|
          loc[:location_name]
        end
        locations_array.join(', ')
      else
        'N/A'
      end
      puts ("The search term '%s' returned the location '%s' of type '%s' " +
          "with ID %d, parent locations '%s' and reach %d (%s)") %
          [criterion[:search_term], criterion[:location][:location_name],
           criterion[:location][:criterion_type], criterion[:location][:id],
           parent_location, criterion[:reach],
           criterion[:location][:targeting_status]]
    end
  else
    puts 'No criteria were returned.'
  end
end

if __FILE__ == $0
  API_VERSION = :v201705

  begin
    lookup_location()

  # Authorization error.
  rescue AdsCommon::Errors::OAuth2VerificationRequired => e
    puts "Authorization credentials are not valid. Edit adwords_api.yml for " +
        "OAuth2 client ID and secret and run misc/setup_oauth2.rb example " +
        "to retrieve and store OAuth2 tokens."
    puts "See this wiki page for more details:\n\n  " +
        'https://github.com/googleads/google-api-ads-ruby/wiki/OAuth2'

  # HTTP errors.
  rescue AdsCommon::Errors::HttpError => e
    puts "HTTP Error: %s" % e

  # API errors.
  rescue AdwordsApi::Errors::ApiException => e
    puts "Message: %s" % e.message
    puts 'Errors:'
    e.errors.each_with_index do |error, index|
      puts "\tError [%d]:" % (index + 1)
      error.each do |field, value|
        puts "\t\t%s: %s" % [field, value]
      end
    end
  end
end

Send feedback about...

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