Add Campaign Targeting Criteria

Java
// Copyright 2018 Google LLC
//
// 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
//
//     https://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.

package com.google.ads.googleads.examples.targeting;

import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v1.errors.GoogleAdsException;
import com.google.ads.googleads.v1.common.AddressInfo;
import com.google.ads.googleads.v1.common.KeywordInfo;
import com.google.ads.googleads.v1.common.ProximityInfo;
import com.google.ads.googleads.v1.enums.KeywordMatchTypeEnum.KeywordMatchType;
import com.google.ads.googleads.v1.enums.ProximityRadiusUnitsEnum.ProximityRadiusUnits;
import com.google.ads.googleads.v1.errors.GoogleAdsError;
import com.google.ads.googleads.v1.resources.CampaignCriterion;
import com.google.ads.googleads.v1.resources.CampaignCriterion.Builder;
import com.google.ads.googleads.v1.resources.CampaignName;
import com.google.ads.googleads.v1.resources.GeoTargetConstantName;
import com.google.ads.googleads.v1.services.CampaignCriterionOperation;
import com.google.ads.googleads.v1.services.CampaignCriterionServiceClient;
import com.google.ads.googleads.v1.services.MutateCampaignCriteriaResponse;
import com.google.ads.googleads.v1.services.MutateCampaignCriterionResult;
import com.google.common.collect.ImmutableList;
import com.google.protobuf.BoolValue;
import com.google.protobuf.DoubleValue;
import com.google.protobuf.StringValue;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

/**
 * Adds campaign targeting criteria. To get campaign targeting criteria, run
 * GetCampaignTargetingCriteria.java.
 */
public class AddCampaignTargetingCriteria {

  private static class AddCampaignTargetingCriteriaParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    private Long customerId;

    @Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true)
    private Long campaignId;

    @Parameter(names = ArgumentNames.KEYWORD_TEXT, required = true)
    private String keywordText;

    @Parameter(
        names = ArgumentNames.LOCATION_ID,
        required = true,
        description =
            "A location criterion ID. For example, specify 21167 for New York. For more information"
                + " on determining this value, see: "
                + " https://developers.google.com/adwords/api/docs/appendix/geotargeting.")
    private Long locationId;
  }

  public static void main(String[] args) {
    AddCampaignTargetingCriteriaParams params = new AddCampaignTargetingCriteriaParams();
    if (!params.parseArguments(args)) {

      // Either pass the required parameters for this example on the command line, or insert them
      // into the code here. See the parameter class definition above for descriptions.
      params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
      params.campaignId = Long.parseLong("INSERT_CAMPAIGN_ID_HERE");
      params.keywordText = "INSERT_KEYWORD_HERE";
      params.locationId = Long.parseLong("INSERT_LOCATION_ID_HERE");
    }

    GoogleAdsClient googleAdsClient;
    try {
      googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
    } catch (FileNotFoundException fnfe) {
      System.err.printf(
          "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
      return;
    } catch (IOException ioe) {
      System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
      return;
    }

    try {
      new AddCampaignTargetingCriteria()
          .runExample(
              googleAdsClient,
              params.customerId,
              params.campaignId,
              params.keywordText,
              params.locationId);
    } catch (GoogleAdsException gae) {
      // GoogleAdsException is the base class for most exceptions thrown by an API request.
      // Instances of this exception have a message and a GoogleAdsFailure that contains a
      // collection of GoogleAdsErrors that indicate the underlying causes of the
      // GoogleAdsException.
      System.err.printf(
          "Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
          gae.getRequestId());
      int i = 0;
      for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
        System.err.printf("  Error %d: %s%n", i++, googleAdsError);
      }
    }
  }

  /**
   * Runs the example.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID in which to create criterion.
   * @param campaignId the campaign ID in which to create criterion.
   * @param keywordText the keyword text for which to add a criterion.
   * @param locationId the locationId for which to add a criterion.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private void runExample(
      GoogleAdsClient googleAdsClient,
      long customerId,
      long campaignId,
      String keywordText,
      long locationId) {
    String campaignResourceName =
        CampaignName.format(Long.toString(customerId), Long.toString(campaignId));

    List<CampaignCriterionOperation> operations =
        ImmutableList.of(
            CampaignCriterionOperation.newBuilder()
                .setCreate(buildNegativeKeywordCriterion(keywordText, campaignResourceName))
                .build(),
            CampaignCriterionOperation.newBuilder()
                .setCreate(buildLocationIdCriterion(locationId, campaignResourceName))
                .build(),
            CampaignCriterionOperation.newBuilder()
                .setCreate(buildProximityLocation(campaignResourceName)).build());

    try (CampaignCriterionServiceClient campaignCriterionServiceClient =
        googleAdsClient.getLatestVersion().createCampaignCriterionServiceClient()) {
      MutateCampaignCriteriaResponse response =
          campaignCriterionServiceClient.mutateCampaignCriteria(
              Long.toString(customerId), operations);
      System.out.printf("Added %d campaign criteria:%n", response.getResultsCount());
      for (MutateCampaignCriterionResult result : response.getResultsList()) {
        System.out.println(result.getResourceName());
      }
    }
  }

  /**
   * Creates a negative keyword as a campaign targeting criterion.
   *
   * @param keywordText the keyword text to exclude.
   * @param campaignResourceName the campaign where the keyword will be excluded.
   * @return a campaign criterion object with the negative keyword targeting.
   */
  private static CampaignCriterion buildNegativeKeywordCriterion(
      String keywordText, String campaignResourceName) {
    return CampaignCriterion.newBuilder()
        .setCampaign(StringValue.of(campaignResourceName))
        .setNegative(BoolValue.of(true))
        .setKeyword(
            KeywordInfo.newBuilder()
                .setMatchType(KeywordMatchType.BROAD)
                .setText(StringValue.of(keywordText))
                .build())
        .build();
  }

  /**
   * Creates a location constant (provided by GeoTargetConstantService) as a campaign targeting
   * criterion. Please refer to GetGeoTargetConstantsByName.java for retrieval of location
   * constants.
   *
   * @param locationId the location to target.
   * @param campaignResourceName the campaign resource name to target.
   * @return a campaign criterion object with the specified locationId and resource name.
   */
  private static CampaignCriterion buildLocationIdCriterion(
      long locationId, String campaignResourceName) {
    Builder criterionBuilder =
        CampaignCriterion.newBuilder().setCampaign(StringValue.of(campaignResourceName));

    criterionBuilder
        .getLocationBuilder()
        .setGeoTargetConstant(
            StringValue.of(GeoTargetConstantName.format(String.valueOf(locationId))));

    return criterionBuilder.build();
  }

  /**
   * Creates a campaign criterion from an address and proximity radius.
   *
   * @param campaignResourceName the campaign resource name to target.
   * @return a campaign criterion object with the specified address and targeting radius.
   */
  private static CampaignCriterion buildProximityLocation(String campaignResourceName) {
    Builder builder =
        CampaignCriterion.newBuilder().setCampaign(StringValue.of(campaignResourceName));

    ProximityInfo.Builder proximityBuilder = builder.getProximityBuilder();
    proximityBuilder.setRadius(DoubleValue.of(10.0)).setRadiusUnits(ProximityRadiusUnits.MILES);

    AddressInfo.Builder addressBuilder = proximityBuilder.getAddressBuilder();
    addressBuilder
        .setStreetAddress(StringValue.of("38 avenue de l'Opéra"))
        .setCityName(StringValue.of("Paris"))
        .setPostalCode(StringValue.of("75002"))
        .setCountryCode(StringValue.of("FR"));

    return builder.build();
  }
}
C#
// Copyright 2018 Google LLC
//
// 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.

using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V1.Errors;
using Google.Ads.GoogleAds.V1.Common;
using Google.Ads.GoogleAds.V1.Resources;
using Google.Ads.GoogleAds.V1.Services;

using System;

using static Google.Ads.GoogleAds.V1.Enums.KeywordMatchTypeEnum.Types;
using static Google.Ads.GoogleAds.V1.Enums.ProximityRadiusUnitsEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V1
{
    /// <summary>
    /// This code example illustrates adding campaign targeting criteria.
    /// </summary>
    public class AddCampaignTargetingCriteria : ExampleBase
    {
        /// <summary>
        /// Main method, to run this code example as a standalone application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            AddCampaignTargetingCriteria codeExample = new AddCampaignTargetingCriteria();
            Console.WriteLine(codeExample.Description);

            // The Google Ads customer ID for which the call is made.
            long customerId = long.Parse("INSERT_CUSTOMER_ID_HERE");

            // ID of the campaign to which targeting criteria are added.
            long campaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");

            // ID of the campaign to which targeting criteria are added.
            string keywordText = "INSERT_KEYWORD_TEXT_HERE";

            // ID of the campaign to which targeting criteria are added.
            long locationId = long.Parse("INSERT_LOCATION_ID_HERE");

            codeExample.Run(new GoogleAdsClient(), customerId, campaignId,
                keywordText, locationId);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get
            {
                return "This code example illustrates adding campaign targeting criteria.";
            }
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignId">ID of the campaign to which targeting criteria are added.
        /// </param>
        /// <param name="keywordText">the keyword text for which to add a criterion.</param>
        /// <param name="locationId">the locationId for which to add a criterion.</param>
        public void Run(GoogleAdsClient client, long customerId, long campaignId,
            string keywordText, long locationId)
        {
            // Get the CampaignCriterionService.
            CampaignCriterionServiceClient campaignCriterionService =
                client.GetService(Services.V1.CampaignCriterionService);

            // Set the Campaign Resource Name
            string campaignResourceName = ResourceNames.Campaign(customerId, campaignId);

            // Add a campaign level negative keyword from keywordText.
            CampaignCriterion keywordCriterion = buildNegativeKeywordCriterion(keywordText,
                campaignResourceName);

            // Creates a location constant (provided by GeoTargetConstantService) as a campaign
            // targeting criterion. Please refer to GetGeoTargetConstantsByName.cs for retrieval
            // of location constants.
            CampaignCriterion locationCriterion = buildLocationCriterion(locationId,
                campaignResourceName);

            // Add a proximity criterion
            CampaignCriterion proximityCriterion = buildProximityCriterion(campaignResourceName);

            // Create the operations.
            CampaignCriterionOperation negativeCriterionOperation =
                new CampaignCriterionOperation()
                {
                    Create = keywordCriterion
                };

            CampaignCriterionOperation locationCriterionOperation =
                new CampaignCriterionOperation()
                {
                    Create = locationCriterion
                };

            CampaignCriterionOperation proximityCriterionOperation =
                new CampaignCriterionOperation()
                {
                    Create = proximityCriterion
                };

            CampaignCriterionOperation[] operations = new CampaignCriterionOperation[] {
                negativeCriterionOperation,
                locationCriterionOperation,
                proximityCriterionOperation
            };

            try
            {
                // Create the campaign criterion.
                MutateCampaignCriteriaResponse response =
                    campaignCriterionService.MutateCampaignCriteria(customerId.ToString(),
                        operations);

                // Display the results.
                foreach (MutateCampaignCriterionResult criterionResult in response.Results)
                {
                    Console.WriteLine($"New campaign criterion with resource name = " +
                        $"'{criterionResult.ResourceName}' was added to campaign " +
                        "ID {campaignId}.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
            }
        }

        /// <summary>
        /// Creates a negative keyword as a campaign targeting criterion.
        /// </summary>
        /// <param name="keywordText">the keyword text to exclude.</param>
        /// <param name="campaignResourceName">the campaign where the keyword will be excluded.
        /// </param>
        /// <returns>a campaign criterion object with the negative keyword targeting.</returns>
        private CampaignCriterion buildNegativeKeywordCriterion(string keywordText,
            string campaignResourceName)
        {
            return new CampaignCriterion()
            {
                Campaign = campaignResourceName,
                Negative = true,
                Keyword = new KeywordInfo()
                {
                    MatchType = KeywordMatchType.Broad,
                    Text = keywordText
                }
            };
        }

        /// <summary>
        /// Creates a negative keyword as a campaign targeting criterion.
        /// </summary>
        /// <param name="locationId">the location to target.</param>
        /// <param name="campaignResourceName">the campaign where the keyword will be excluded.
        /// </param>
        /// <returns>a campaign criterion object with the specified locationId and resource name.
        /// </returns>
        private CampaignCriterion buildLocationCriterion(long locationId,
            string campaignResourceName)
        {
            GeoTargetConstantName location = new GeoTargetConstantName(locationId.ToString());
            return new CampaignCriterion()
            {
                Campaign = campaignResourceName,
                Location = new LocationInfo()
                {
                    GeoTargetConstant = location.ToString()
                }
            };
        }

        /// <summary>
        /// Creates a proximity Criterion.
        /// </summary>
        /// <param name="campaignResourceName">the campaign where the proximity will be added.
        /// </param>
        /// <returns>a campaign criterion object with the specified locationId and resource name.
        /// </returns>
        private CampaignCriterion buildProximityCriterion(string campaignResourceName)
        {
            ProximityInfo proximity = new ProximityInfo()
            {
                Address = new AddressInfo()
                {
                    StreetAddress = "38 avenue de l'Opéra",
                    CityName = "Paris",
                    PostalCode = "75002",
                    CountryCode = "FR"
                },
                Radius = 10d,
                // Default is kilometers.
                RadiusUnits = ProximityRadiusUnits.Miles
            };

            return new CampaignCriterion()
            {
                Campaign = campaignResourceName,
                Proximity = proximity
            };
        }
    }
}
PHP
<?php
/**
 * Copyright 2018 Google LLC
 *
 * 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
 *
 *     https://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.
 */

namespace Google\Ads\GoogleAds\Examples\Targeting;

require __DIR__ . '/../../vendor/autoload.php';

use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Lib\V1\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V1\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V1\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Util\V1\ResourceNames;
use Google\Ads\GoogleAds\V1\Common\AddressInfo;
use Google\Ads\GoogleAds\V1\Common\KeywordInfo;
use Google\Ads\GoogleAds\V1\Common\LocationInfo;
use Google\Ads\GoogleAds\V1\Common\ProximityInfo;
use Google\Ads\GoogleAds\V1\Enums\KeywordMatchTypeEnum\KeywordMatchType;
use Google\Ads\GoogleAds\V1\Enums\ProximityRadiusUnitsEnum\ProximityRadiusUnits;
use Google\Ads\GoogleAds\V1\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V1\Resources\CampaignCriterion;
use Google\Ads\GoogleAds\V1\Services\CampaignCriterionOperation;
use Google\ApiCore\ApiException;
use Google\Protobuf\BoolValue;
use Google\Protobuf\DoubleValue;
use Google\Protobuf\StringValue;

/**
 * This example adds campaign targeting criteria. To get campaign targeting criteria, run
 * GetCampaignTargetingCriteria.php.
 */
class AddCampaignTargetingCriteria
{
    const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
    // Specify the keyword text to be created as a negative campaign criterion.
    const KEYWORD_TEXT = 'INSERT_KEYWORD_TEXT_HERE';
    // Specify the location ID below.
    // For more information on determining LOCATION_ID value, see:
    // https://developers.google.com/adwords/api/docs/appendix/geotargeting.
    const LOCATION_ID = 21167; // New York

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::CAMPAIGN_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::KEYWORD_TEXT => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::LOCATION_ID => GetOpt::OPTIONAL_ARGUMENT
        ]);

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

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::CAMPAIGN_ID] ?: self::CAMPAIGN_ID,
                $options[ArgumentNames::KEYWORD_TEXT] ?: self::KEYWORD_TEXT,
                $options[ArgumentNames::LOCATION_ID] ?: self::LOCATION_ID
            );
        } catch (GoogleAdsException $googleAdsException) {
            printf(
                "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
                $googleAdsException->getRequestId(),
                PHP_EOL,
                PHP_EOL
            );
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
                /** @var GoogleAdsError $error */
                printf(
                    "\t%s: %s%s",
                    $error->getErrorCode()->getErrorCode(),
                    $error->getMessage(),
                    PHP_EOL
                );
            }
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the client customer ID without hyphens
     * @param int $campaignId the campaign ID to add a criterion to
     * @param string $keywordText the keyword text to be added as a negative campaign criterion
     * @param int $locationId the location ID to be targeted
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        $customerId,
        $campaignId,
        $keywordText,
        $locationId
    ) {
        $campaignResourceName = ResourceNames::forCampaign($customerId, $campaignId);

        $operations = [
            // Creates a campaign criterion operation for the specified keyword text.
            self::createNegativeKeywordCampaignCriterionOperation(
                $keywordText,
                $campaignResourceName
            ),
            // Creates a campaign criterion operation for the specified location ID.
            self::createLocationCampaignCriterionOperation($locationId, $campaignResourceName),
            // Creates a campaign criterion operation for the area around a specific address
            // (proximity).
            self::createProximityCampaignCriterionOperation($campaignResourceName)
        ];

        // Issues a mutate request to add the campaign criterion.
        $campaignCriterionServiceClient = $googleAdsClient->getCampaignCriterionServiceClient();
        $response =
            $campaignCriterionServiceClient->mutateCampaignCriteria($customerId, $operations);

        printf("Added %d campaign criteria:%s", $response->getResults()->count(), PHP_EOL);

        foreach ($response->getResults() as $addedCampaignCriterion) {
            /** @var CampaignCriterion $addedCampaignCriterion */
            print $addedCampaignCriterion->getResourceName() . PHP_EOL;
        }
    }

    /**
     * Creates a campaign criterion operation using the specified keyword text. The keyword text
     * will be used to create a negative campaign criterion.
     *
     * @param string $keywordText the keyword text to be added
     * @param string $campaignResourceName the campaign resource name that the created criterion
     *      belongs to
     * @return CampaignCriterionOperation the created campaign criterion operation
     */
    private static function createNegativeKeywordCampaignCriterionOperation(
        $keywordText,
        $campaignResourceName
    ) {
        // Constructs a negative campaign criterion for the specified campaign ID using the
        // specified keyword text info.
        $campaignCriterion = new CampaignCriterion([
            // Creates a keyword with BROAD match type.
            'keyword' => new KeywordInfo([
                'text' => new StringValue(['value' => $keywordText]),
                'match_type' => KeywordMatchType::BROAD
            ]),
            // Sets the campaign criterion as a negative criterion.
            'negative' => new BoolValue(['value' => true]),
            'campaign' => new StringValue(['value' => $campaignResourceName])
        ]);

        return new CampaignCriterionOperation(['create' => $campaignCriterion]);
    }

    /**
     * Creates a campaign criterion operation using the specified location ID.
     *
     * @param int $locationId the specified location ID
     * @param string $campaignResourceName the campaign resource name that the created criterion
     *      belongs to
     * @return CampaignCriterionOperation the created campaign criterion operation
     */
    private static function createLocationCampaignCriterionOperation(
        $locationId,
        $campaignResourceName
    ) {
        // Constructs a campaign criterion for the specified campaign ID using the specified
        // location ID.
        $campaignCriterion = new CampaignCriterion([
            // Creates a location using the specified location ID.
            'location' => new LocationInfo([
                'geo_target_constant' => new StringValue(
                    // Besides using location ID, you can also search by location names using
                    // GeoTargetConstantServiceClient::suggestGeoTargetConstants() and directly
                    // apply GeoTargetConstant::$resourceName here. An example can be found
                    // in GetGeoTargetConstantByNames.php.
                    ['value' => ResourceNames::forGeoTargetConstant($locationId)]
                )
            ]),
            'campaign' => new StringValue(['value' => $campaignResourceName])
        ]);

        return new CampaignCriterionOperation(['create' => $campaignCriterion]);
    }

    /**
     * Creates a campaign criterion operation for the area around a specific address (proximity).
     *
     * @param string $campaignResourceName the campaign resource name that the created criterion
     *      belongs to
     * @return CampaignCriterionOperation the created campaign criterion operation
     */
    private static function createProximityCampaignCriterionOperation($campaignResourceName)
    {
        // Constructs a campaign criterion as a proximity.
        $campaignCriterion = new CampaignCriterion([
            'proximity' => new ProximityInfo([
                'address' => new AddressInfo([
                    'street_address' => new StringValue(['value' => '38 avenue de l\'Opéra']),
                    'city_name' => new StringValue(['value' => 'Paris']),
                    'postal_code' => new StringValue(['value' => '75002']),
                    'country_code' => new StringValue(['value' => 'FR']),
                ]),
                'radius' => new DoubleValue(['value' => 10.0]),
                // Default is kilometers.
                'radius_units' => ProximityRadiusUnits::MILES
            ]),
            'campaign' => new StringValue(['value' => $campaignResourceName])
        ]);

        return new CampaignCriterionOperation(['create' => $campaignCriterion]);
    }
}

AddCampaignTargetingCriteria::main();
Python
#!/usr/bin/env python
# Copyright 2018 Google LLC
#
# 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
#
#     https://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 campaign targeting criteria."""

from __future__ import absolute_import

import argparse
import six
import sys

import google.ads.google_ads.client


def main(client, customer_id, campaign_id, keyword, location_id):
    campaign_criterion_service = client.get_service('CampaignCriterionService',
                                                    version='v1')

    operations = [
        create_location_op(client, customer_id, campaign_id, location_id),
        create_negative_keyword_op(client, customer_id, campaign_id, keyword),
        create_proximity_op(client, customer_id, campaign_id)
    ]

    try:
        campaign_criterion_response = (
            campaign_criterion_service.mutate_campaign_criteria(
                customer_id, operations))
    except google.ads.google_ads.errors.GoogleAdsException as ex:
        print('Request with ID "%s" failed with status "%s" and includes the '
              'following errors:' % (ex.request_id, ex.error.code().name))
        for error in ex.failure.errors:
            print('\tError with message "%s".' % error.message)
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print('\t\tOn field: %s' % field_path_element.field_name)
        sys.exit(1)

    for result in campaign_criterion_response.results:
        print('Added campaign criterion "%s".' % result.resource_name)


def create_location_op(client, customer_id, campaign_id, location_id):
    campaign_service = client.get_service('CampaignService', version='v1')
    geo_target_constant_service = client.get_service('GeoTargetConstantService',
                                                     version='v1')

    # Create the campaign criterion.
    campaign_criterion_operation = client.get_type('CampaignCriterionOperation',
                                                   version='v1')
    campaign_criterion = campaign_criterion_operation.create
    campaign_criterion.campaign.value = campaign_service.campaign_path(
        customer_id, campaign_id)

    # Besides using location_id, you can also search by location names from
    # GeoTargetConstantService.suggest_geo_target_constants() and directly
    # apply GeoTargetConstant.resource_name here. An example can be found
    # in get_geo_target_constant_by_names.py.
    campaign_criterion.location.geo_target_constant.value = (
        geo_target_constant_service.geo_target_constant_path(location_id))

    return campaign_criterion_operation


def create_negative_keyword_op(client, customer_id, campaign_id, keyword):
    campaign_service = client.get_service('CampaignService', version='v1')

    # Create the campaign criterion.
    campaign_criterion_operation = client.get_type('CampaignCriterionOperation',
                                                   version='v1')
    campaign_criterion = campaign_criterion_operation.create
    campaign_criterion.campaign.value = campaign_service.campaign_path(
        customer_id, campaign_id)
    campaign_criterion.negative.value = True
    criterion_keyword = campaign_criterion.keyword
    criterion_keyword.text.value = keyword
    criterion_keyword.match_type = client.get_type('KeywordMatchTypeEnum',
                                                   version='v1').BROAD

    return campaign_criterion_operation


def create_proximity_op(client, customer_id, campaign_id):
    campaign_service = client.get_service('CampaignService', version='v1')

    # Create the campaign criterion.
    campaign_criterion_operation = client.get_type('CampaignCriterionOperation',
                                                   version='v1')
    campaign_criterion = campaign_criterion_operation.create
    campaign_criterion.campaign.value = campaign_service.campaign_path(
        customer_id, campaign_id)
    campaign_criterion.proximity.address.street_address.value = (
        '38 avenue de l\'Opera')
    campaign_criterion.proximity.address.city_name.value = 'Paris'
    campaign_criterion.proximity.address.postal_code.value = '75002'
    campaign_criterion.proximity.address.country_code.value = 'FR'
    campaign_criterion.proximity.radius.value = 10
    # Default is kilometers.
    campaign_criterion.proximity.radius_units = client.get_type(
        'ProximityRadiusUnitsEnum').MILES

    return campaign_criterion_operation


if __name__ == '__main__':
    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    google_ads_client = (google.ads.google_ads.client.GoogleAdsClient
                         .load_from_storage())

    parser = argparse.ArgumentParser(
        description=('Adds campaign targeting criteria for the specified '
                     'campaign under the given customer ID.'))
    # The following argument(s) should be provided to run the example.
    parser.add_argument('-c', '--customer_id', type=six.text_type,
                        required=True, help='The Google Ads customer ID.')
    parser.add_argument('-i', '--campaign_id', type=six.text_type,
                        required=True, help='The campaign ID.')
    parser.add_argument('-k', '--keyword', type=six.text_type, required=True,
                        help='The keyword to be added to the campaign.')
    parser.add_argument(
        '-l', '--location_id', type=six.text_type, required=False,
        default='21167',  # New York
        help=('A location criterion ID, this field is optional. If not '
              'specified, will default to New York. For more information on '
              'determining this value, see: '
              'https://developers.google.com/adwords/api/docs/appendix/'
              'geotargeting.'))
    args = parser.parse_args()

    main(google_ads_client, args.customer_id, args.campaign_id, args.keyword,
         args.location_id)
Ruby
#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2018 Google LLC
#
# 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
#
#     https://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 code example illustrates adding campaign targeting criteria.

require 'optparse'
require 'google/ads/google_ads'

def add_campaign_targeting_criteria(
    customer_id, campaign_id, keyword, location_id)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  criteria_service = client.service(:CampaignCriterion)

  negative_keyword = create_negative_keyword(client, customer_id,
      campaign_id, keyword)
  location = create_location(client, customer_id, campaign_id, location_id)
  proximity = create_proximity(client, customer_id, campaign_id)

  operations = [
    {create: negative_keyword},
    {create: location},
    {create: proximity}
  ]

  response = criteria_service.mutate_campaign_criteria(customer_id, operations)
  response.results.each do |resource|
    puts sprintf("Added campaign criterion %s", resource.resource_name)
  end
end

def create_proximity(client, customer_id, campaign_id)
  criterion = client.resource(:CampaignCriterion)
  criterion.campaign = client.wrapper.string(
      client.path.campaign(customer_id, campaign_id))

  criterion.proximity = client.resource(:ProximityInfo)
  criterion.proximity.address = client.resource(:AddressInfo)
  criterion.proximity.address.street_address =
      client.wrapper.string("38 avenue de l'Opéra")
  criterion.proximity.address.city_name = client.wrapper.string("Paris")
  criterion.proximity.address.postal_code = client.wrapper.string("75002")
  criterion.proximity.address.country_code = client.wrapper.string("FR")
  criterion.proximity.radius = client.wrapper.double(10)
  # Default is kilometers.
  criterion.proximity.radius_units = client.enum(:ProximityRadiusUnits)::MILES

  return criterion
end

def create_location(client, customer_id, campaign_id, location_id)
  criterion = client.resource(:CampaignCriterion)
  criterion.campaign = client.wrapper.string(
      client.path.campaign(customer_id, campaign_id))

  criterion.location = client.resource(:LocationInfo)
  # Besides using location_id, you can also search by location names from
  # GeoTargetConstantService.suggest_geo_target_constants() and directly
  # apply GeoTargetConstant.resource_name here. An example can be found
  # in get_geo_target_constant_by_names.rb.
  criterion.location.geo_target_constant = client.wrapper.string(
      client.path.geo_target_constant(location_id))

  return criterion
end

def create_negative_keyword(client, customer_id, campaign_id, keyword)
  criterion = client.resource(:CampaignCriterion)
  criterion.campaign = client.wrapper.string(
      client.path.campaign(customer_id, campaign_id))
  criterion.negative = client.wrapper.bool(true)
  criterion.keyword = client.resource(:KeywordInfo)
  criterion.keyword.text = client.wrapper.string(keyword)
  criterion.keyword.match_type = client.enum(:KeywordMatchType)::BROAD

  return criterion
end

if __FILE__ == $PROGRAM_NAME
  options = {}

  # The following parameter(s) should be provided to run the example. You can
  # either specify these by changing the INSERT_XXX_ID_HERE values below, or on
  # the command line.
  #
  # Parameters passed on the command line will override any parameters set in
  # code.
  #
  # Running the example with -h will print the command line usage.
  options[:customer_id] = 'INSERT_ADWORDS_CUSTOMER_ID_HERE'
  options[:campaign_id] = 'INSERT_CAMPAIGN_ID_HERE'
  options[:keyword] = 'jupiter cruise'
  # For more information on determining location_id value, see:
  # https://developers.google.com/adwords/api/docs/appendix/geotargeting.
  options[:location_id] = '21167' # New York

  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: ruby %s [options]', File.basename(__FILE__))

    opts.separator ''
    opts.separator 'Options:'

    opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
      options[:customer_id] = v
    end

    opts.on('-c', '--campaign-id CAMPAIGN-ID', String, 'Campaign ID') do |v|
      options[:campaign_id] = v
    end

    opts.on('-k', '--keyword KEYWORD', String, '(Optional) Keyword') do |v|
      options[:keyword] = v
    end

    opts.on('-l', '--location-id LOCATION-ID', String, '(Optional) Location ID') do |v|
      options[:location_id] = v
    end

    opts.separator ''
    opts.separator 'Help:'

    opts.on_tail('-h', '--help', 'Show this message') do
      puts opts
      exit
    end
  end.parse!

  begin
    add_campaign_targeting_criteria(options.fetch(:customer_id).tr("-", ""),
        options[:campaign_id], options[:keyword], options[:location_id])
    rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
      e.failure.errors.each do |error|
        STDERR.printf("Error with message: %s\n", error.message)
        if error.location
          error.location.field_path_elements.each do |field_path_element|
            STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
          end
        end
        error.error_code.to_h.each do |k, v|
          next if v == :UNSPECIFIED
          STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
        end
      end
  rescue Google::Gax::RetryError => e
    STDERR.printf("Error: '%s'\n\tCause: '%s'\n\tCode: %d\n\tDetails: '%s'\n" \
        "\tRequest-Id: '%s'\n", e.message, e.cause.message, e.cause.code,
        e.cause.details, e.cause.metadata['request-id'])
  end
end

Send feedback about...

Google Ads API
Google Ads API
Need help? Visit our support page.