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.v17.common.AddressInfo; import com.google.ads.googleads.v17.common.KeywordInfo; import com.google.ads.googleads.v17.common.ProximityInfo; import com.google.ads.googleads.v17.enums.KeywordMatchTypeEnum.KeywordMatchType; import com.google.ads.googleads.v17.enums.ProximityRadiusUnitsEnum.ProximityRadiusUnits; import com.google.ads.googleads.v17.errors.GoogleAdsError; import com.google.ads.googleads.v17.errors.GoogleAdsException; import com.google.ads.googleads.v17.resources.CampaignCriterion; import com.google.ads.googleads.v17.resources.CampaignCriterion.Builder; import com.google.ads.googleads.v17.services.CampaignCriterionOperation; import com.google.ads.googleads.v17.services.CampaignCriterionServiceClient; import com.google.ads.googleads.v17.services.MutateCampaignCriteriaResponse; import com.google.ads.googleads.v17.services.MutateCampaignCriterionResult; import com.google.ads.googleads.v17.utils.ResourceNames; import com.google.common.collect.ImmutableList; 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/google-ads/api/reference/data/geotargets.") 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 = null; try { googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build(); } catch (FileNotFoundException fnfe) { System.err.printf( "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe); System.exit(1); } catch (IOException ioe) { System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe); System.exit(1); } 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); } System.exit(1); } } /** * 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 = ResourceNames.campaign(customerId, 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(campaignResourceName) .setNegative(true) .setKeyword( KeywordInfo.newBuilder() .setMatchType(KeywordMatchType.BROAD) .setText(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(campaignResourceName); criterionBuilder .getLocationBuilder() .setGeoTargetConstant(ResourceNames.geoTargetConstant(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(campaignResourceName); ProximityInfo.Builder proximityBuilder = builder.getProximityBuilder(); proximityBuilder.setRadius(10.0).setRadiusUnits(ProximityRadiusUnits.MILES); AddressInfo.Builder addressBuilder = proximityBuilder.getAddressBuilder(); addressBuilder .setStreetAddress("38 avenue de l'Opéra") .setCityName("Paris") .setPostalCode("75002") .setCountryCode("FR"); return builder.build(); } }
#C
// Copyright 2019 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 CommandLine; using Google.Ads.Gax.Examples; using Google.Ads.GoogleAds.Lib; using Google.Ads.GoogleAds.V17.Common; using Google.Ads.GoogleAds.V17.Errors; using Google.Ads.GoogleAds.V17.Resources; using Google.Ads.GoogleAds.V17.Services; using System; using System.Collections.Generic; using static Google.Ads.GoogleAds.V17.Enums.KeywordMatchTypeEnum.Types; using static Google.Ads.GoogleAds.V17.Enums.ProximityRadiusUnitsEnum.Types; namespace Google.Ads.GoogleAds.Examples.V17 { /// <summary> /// This code example illustrates adding campaign targeting criteria. /// </summary> public class AddCampaignTargetingCriteria : ExampleBase { /// <summary> /// Command line options for running the <see cref="AddCampaignTargetingCriteria"/> example. /// </summary> public class Options : OptionsBase { /// <summary> /// The Google Ads customer ID for which the call is made. /// </summary> [Option("customerId", Required = true, HelpText = "The Google Ads customer ID for which the call is made.")] public long CustomerId { get; set; } /// <summary> /// ID of the campaign to which targeting criteria are added. /// </summary> [Option("campaignId", Required = true, HelpText = "ID of the campaign to which targeting criteria are added.")] public long CampaignId { get; set; } /// <summary> /// The keyword text for which to add a criterion. /// </summary> [Option("keywordText", Required = true, HelpText = "The keyword text for which to add a criterion.")] public string KeywordText { get; set; } /// <summary> /// The locationId for which to add a criterion. /// </summary> [Option("locationId", Required = true, HelpText = "The locationId for which to add a criterion.")] public long LocationId { get; set; } } /// <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) { Options options = ExampleUtilities.ParseCommandLine<Options>(args); AddCampaignTargetingCriteria codeExample = new AddCampaignTargetingCriteria(); Console.WriteLine(codeExample.Description); codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.CampaignId, options.KeywordText, options.LocationId); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description => "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.V17.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}"); throw; } } /// <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\V17\GoogleAdsClient; use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClientBuilder; use Google\Ads\GoogleAds\Lib\V17\GoogleAdsException; use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder; use Google\Ads\GoogleAds\Util\V17\ResourceNames; use Google\Ads\GoogleAds\V17\Common\AddressInfo; use Google\Ads\GoogleAds\V17\Common\KeywordInfo; use Google\Ads\GoogleAds\V17\Common\LocationInfo; use Google\Ads\GoogleAds\V17\Common\ProximityInfo; use Google\Ads\GoogleAds\V17\Enums\KeywordMatchTypeEnum\KeywordMatchType; use Google\Ads\GoogleAds\V17\Enums\ProximityRadiusUnitsEnum\ProximityRadiusUnits; use Google\Ads\GoogleAds\V17\Errors\GoogleAdsError; use Google\Ads\GoogleAds\V17\Resources\CampaignCriterion; use Google\Ads\GoogleAds\V17\Services\CampaignCriterionOperation; use Google\Ads\GoogleAds\V17\Services\MutateCampaignCriteriaRequest; use Google\ApiCore\ApiException; /** * This example adds campaign targeting criteria. To get campaign targeting criteria, run * GetCampaignTargetingCriteria.php. */ class AddCampaignTargetingCriteria { private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE'; private const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'; // Specify the keyword text to be created as a negative campaign criterion. private 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/google-ads/api/reference/data/geotargets. private 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) // We set this value to true to show how to use GAPIC v2 source code. You can remove the // below line if you wish to use the old-style source code. Note that in that case, you // probably need to modify some parts of the code below to make it work. // For more information, see // https://developers.devsite.corp.google.com/google-ads/api/docs/client-libs/php/gapic. ->usingGapicV2Source(true) ->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 ); } exit(1); } catch (ApiException $apiException) { printf( "ApiException was thrown with message '%s'.%s", $apiException->getMessage(), PHP_EOL ); exit(1); } } /** * Runs the example. * * @param GoogleAdsClient $googleAdsClient the Google Ads API client * @param int $customerId the customer ID * @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, int $customerId, int $campaignId, string $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( MutateCampaignCriteriaRequest::build($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( string $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' => $keywordText, 'match_type' => KeywordMatchType::BROAD ]), // Sets the campaign criterion as a negative criterion. 'negative' => true, 'campaign' => $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( int $locationId, string $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([ // 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. 'geo_target_constant' => ResourceNames::forGeoTargetConstant($locationId) ]), 'campaign' => $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(string $campaignResourceName) { // Constructs a campaign criterion as a proximity. $campaignCriterion = new CampaignCriterion([ 'proximity' => new ProximityInfo([ 'address' => new AddressInfo([ 'street_address' => '38 avenue de l\'Opéra', 'city_name' => 'Paris', 'postal_code' => '75002', 'country_code' => 'FR', ]), 'radius' => 10.0, // Default is kilometers. 'radius_units' => ProximityRadiusUnits::MILES ]), 'campaign' => $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.""" import argparse import sys from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException def main(client, customer_id, campaign_id, keyword_text, location_id): campaign_criterion_service = client.get_service("CampaignCriterionService") operations = [ create_location_op(client, customer_id, campaign_id, location_id), create_negative_keyword_op( client, customer_id, campaign_id, keyword_text ), create_proximity_op(client, customer_id, campaign_id), ] campaign_criterion_response = ( campaign_criterion_service.mutate_campaign_criteria( customer_id=customer_id, operations=operations ) ) for result in campaign_criterion_response.results: print(f'Added campaign criterion "{result.resource_name}".') def create_location_op(client, customer_id, campaign_id, location_id): campaign_service = client.get_service("CampaignService") geo_target_constant_service = client.get_service("GeoTargetConstantService") # Create the campaign criterion. campaign_criterion_operation = client.get_type("CampaignCriterionOperation") campaign_criterion = campaign_criterion_operation.create campaign_criterion.campaign = 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 = ( 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_text): campaign_service = client.get_service("CampaignService") # Create the campaign criterion. campaign_criterion_operation = client.get_type("CampaignCriterionOperation") campaign_criterion = campaign_criterion_operation.create campaign_criterion.campaign = campaign_service.campaign_path( customer_id, campaign_id ) campaign_criterion.negative = True criterion_keyword = campaign_criterion.keyword criterion_keyword.text = keyword_text criterion_keyword.match_type = client.enums.KeywordMatchTypeEnum.BROAD return campaign_criterion_operation def create_proximity_op(client, customer_id, campaign_id): campaign_service = client.get_service("CampaignService") # Create the campaign criterion. campaign_criterion_operation = client.get_type("CampaignCriterionOperation") campaign_criterion = campaign_criterion_operation.create campaign_criterion.campaign = campaign_service.campaign_path( customer_id, campaign_id ) campaign_criterion.proximity.address.street_address = "38 avenue de l'Opera" campaign_criterion.proximity.address.city_name = "Paris" campaign_criterion.proximity.address.postal_code = "75002" campaign_criterion.proximity.address.country_code = "FR" campaign_criterion.proximity.radius = 10 # Default is kilometers. campaign_criterion.proximity.radius_units = ( client.enums.ProximityRadiusUnitsEnum.MILES ) return campaign_criterion_operation if __name__ == "__main__": 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=str, required=True, help="The Google Ads customer ID.", ) parser.add_argument( "-i", "--campaign_id", type=str, required=True, help="The campaign ID." ) parser.add_argument( "-k", "--keyword_text", type=str, required=True, help="The keyword text to be added to the campaign.", ) parser.add_argument( "-l", "--location_id", type=str, 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/google-ads/api/reference/data/geotargets" ), ) args = parser.parse_args() # GoogleAdsClient will read the google-ads.yaml configuration file in the # home directory if none is specified. googleads_client = GoogleAdsClient.load_from_storage(version="v17") try: main( googleads_client, args.customer_id, args.campaign_id, args.keyword_text, args.location_id, ) except GoogleAdsException as ex: print( f'Request with ID "{ex.request_id}" failed with status ' f'"{ex.error.code().name}" and includes the following errors:' ) for error in ex.failure.errors: print(f'\tError with message "{error.message}".') if error.location: for field_path_element in error.location.field_path_elements: print(f"\t\tOn field: {field_path_element.field_name}") sys.exit(1)
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.campaign_criterion 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 = [negative_keyword, location, proximity] response = criteria_service.mutate_campaign_criteria( customer_id: customer_id, operations: 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) client.operation.create_resource.campaign_criterion do |criterion| criterion.campaign = client.path.campaign(customer_id, campaign_id) criterion.proximity = client.resource.proximity_info do |proximity| proximity.address = client.resource.address_info do |address| address.street_address = "38 avenue de l'Opéra" address.city_name = "Paris" address.postal_code = "75002" address.country_code = "FR" end proximity.radius = 10 proximity.radius_units = :MILES end end end def create_location(client, customer_id, campaign_id, location_id) client.operation.create_resource.campaign_criterion do |criterion| criterion.campaign = client.path.campaign(customer_id, campaign_id) criterion.location = client.resource.location_info do |li| # 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. li.geo_target_constant = client.path.geo_target_constant(location_id) end end end def create_negative_keyword(client, customer_id, campaign_id, keyword) client.operation.create_resource.campaign_criterion do |criterion| criterion.campaign = client.path.campaign(customer_id, campaign_id) criterion.negative = true criterion.keyword = client.resource.keyword_info do |ki| ki.text = keyword ki.match_type = :BROAD end end 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_GOOGLE_ADS_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/google-ads/api/reference/data/geotargets 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-text KEYWORD-TEXT', 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 raise end end
Perl
#!/usr/bin/perl -w # # Copyright 2019, 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. # # This example adds campaign targeting criteria. To get campaign targeting # criteria, run get_campaign_targeting_criteria.pl. use strict; use warnings; use utf8; use FindBin qw($Bin); use lib "$Bin/../../lib"; use Google::Ads::GoogleAds::Client; use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; use Google::Ads::GoogleAds::V17::Resources::CampaignCriterion; use Google::Ads::GoogleAds::V17::Common::KeywordInfo; use Google::Ads::GoogleAds::V17::Common::LocationInfo; use Google::Ads::GoogleAds::V17::Common::ProximityInfo; use Google::Ads::GoogleAds::V17::Common::AddressInfo; use Google::Ads::GoogleAds::V17::Enums::KeywordMatchTypeEnum qw(BROAD); use Google::Ads::GoogleAds::V17::Enums::ProximityRadiusUnitsEnum qw(MILES); use Google::Ads::GoogleAds::V17::Services::CampaignCriterionService::CampaignCriterionOperation; use Google::Ads::GoogleAds::V17::Utils::ResourceNames; use Getopt::Long qw(:config auto_help); use Pod::Usage; use Cwd qw(abs_path); # 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. my $customer_id = "INSERT_CUSTOMER_ID_HERE"; my $campaign_id = "INSERT_CAMPAIGN_ID_HERE"; # Specify the keyword text to be created as a negative campaign criterion. my $keyword_text = "jupiter cruise"; # Specify the location ID below. # For more information on determining LOCATION_ID value, see: # https://developers.google.com/google-ads/api/reference/data/geotargets. my $location_id = 21167; # NEW YORK sub add_campaign_targeting_criteria { my ($api_client, $customer_id, $campaign_id, $keyword_text, $location_id) = @_; my $campaign_resource_name = Google::Ads::GoogleAds::V17::Utils::ResourceNames::campaign($customer_id, $campaign_id); my $operations = [ create_negative_keyword_campaign_criterion_operation( $keyword_text, $campaign_resource_name ), create_location_campaign_criterion_operation( $location_id, $campaign_resource_name ), create_proximity_campaign_criterion_operation($campaign_resource_name)]; # Add the campaign criterion. my $campaign_criteria_response = $api_client->CampaignCriterionService()->mutate({ customerId => $customer_id, operations => $operations }); my $campaign_criterion_results = $campaign_criteria_response->{results}; printf "Added %d campaign criteria:\n", scalar @$campaign_criterion_results; foreach my $campaign_criterion_result (@$campaign_criterion_results) { printf "\t%s\n", $campaign_criterion_result->{resourceName}; } return 1; } # Creates a campaign criterion operation using the specified keyword text. # The keyword text will be used to create a negative campaign criterion. sub create_negative_keyword_campaign_criterion_operation { my ($keyword, $campaign_resource_name) = @_; # Construct a negative campaign criterion for the specified campaign # using the specified keyword text info. my $campaign_criterion = Google::Ads::GoogleAds::V17::Resources::CampaignCriterion->new({ # Create a keyword with BROAD match type. keyword => Google::Ads::GoogleAds::V17::Common::KeywordInfo->new({ text => $keyword, matchType => BROAD } ), # Set the campaign criterion as negative. negative => "true", campaign => $campaign_resource_name }); return Google::Ads::GoogleAds::V17::Services::CampaignCriterionService::CampaignCriterionOperation ->new({ create => $campaign_criterion }); } # Creates a campaign criterion operation using the specified location ID. sub create_location_campaign_criterion_operation { my ($location_id, $campaign_resource_name) = @_; # Construct a campaign criterion for the specified campaign using the # specified location ID. my $campaign_criterion = Google::Ads::GoogleAds::V17::Resources::CampaignCriterion->new({ # Create a location using the specified location ID. location => Google::Ads::GoogleAds::V17::Common::LocationInfo->new({ # Besides using location ID, you can also search by location names # using GeoTargetConstantService::suggest() and directly apply # GeoTargetConstant->{resourceName} here. An example can be found # in get_geo_target_constants_by_names.pl. geoTargetConstant => Google::Ads::GoogleAds::V17::Utils::ResourceNames::geo_target_constant( $location_id)} ), campaign => $campaign_resource_name }); return Google::Ads::GoogleAds::V17::Services::CampaignCriterionService::CampaignCriterionOperation ->new({ create => $campaign_criterion }); } # Creates a campaign criterion operation for the area around a specific # address (proximity). sub create_proximity_campaign_criterion_operation { my ($campaign_resource_name) = @_; # Construct a campaign criterion as a proximity. my $campaign_criterion = Google::Ads::GoogleAds::V17::Resources::CampaignCriterion->new({ proximity => Google::Ads::GoogleAds::V17::Common::ProximityInfo->new({ address => Google::Ads::GoogleAds::V17::Common::AddressInfo->new({ streetAddress => "38 avenue de l'Opéra", cityName => "cityName", postalCode => "75002", countryCode => "FR" } ), radius => 10.0, # Default is kilometers. radiusUnits => MILES } ), campaign => $campaign_resource_name }); return Google::Ads::GoogleAds::V17::Services::CampaignCriterionService::CampaignCriterionOperation ->new({ create => $campaign_criterion }); } # Don't run the example if the file is being included. if (abs_path($0) ne abs_path(__FILE__)) { return 1; } # Get Google Ads Client, credentials will be read from ~/googleads.properties. my $api_client = Google::Ads::GoogleAds::Client->new(); # By default examples are set to die on any server returned fault. $api_client->set_die_on_faults(1); # Parameters passed on the command line will override any parameters set in code. GetOptions( "customer_id=s" => \$customer_id, "campaign_id=i" => \$campaign_id, "keyword_text=s" => \$keyword_text, "location_id=i" => \$location_id ); # Print the help message if the parameters are not initialized in the code nor # in the command line. pod2usage(2) if not check_params($customer_id, $campaign_id, $keyword_text, $location_id); # Call the example. add_campaign_targeting_criteria($api_client, $customer_id =~ s/-//gr, $campaign_id, $keyword_text, $location_id); =pod =head1 NAME add_campaign_targeting_criteria =head1 DESCRIPTION This example adds campaign targeting criteria. To get campaign targeting criteria, run get_campaign_targeting_criteria.pl. =head1 SYNOPSIS add_campaign_targeting_criteria.pl [options] -help Show the help message. -customer_id The Google Ads customer ID. -campaign_id The campaign ID. -keyword_text [optional] The keyword to be created as a negative campaign criterion. -location_id [optional] The location ID. =cut