Skip to content

Commit 3199063

Browse files
authored
New GenerateKeywordIdeas example for the KeywordPlanService (#49)
Add new GenerateKeywordIdeas example for the KeywordPlanService
1 parent e8afd82 commit 3199063

2 files changed

Lines changed: 200 additions & 0 deletions

File tree

Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
// Copyright 2018 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// https://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package com.google.ads.googleads.examples.planning;
16+
17+
import com.beust.jcommander.Parameter;
18+
import com.google.ads.googleads.examples.utils.ArgumentNames;
19+
import com.google.ads.googleads.examples.utils.CodeSampleParams;
20+
import com.google.ads.googleads.lib.GoogleAdsClient;
21+
import com.google.ads.googleads.lib.GoogleAdsException;
22+
import com.google.ads.googleads.lib.utils.ResourceNames;
23+
import com.google.ads.googleads.v0.enums.KeywordPlanNetworkEnum.KeywordPlanNetwork;
24+
import com.google.ads.googleads.v0.errors.GoogleAdsError;
25+
import com.google.ads.googleads.v0.services.GenerateKeywordIdeaResponse;
26+
import com.google.ads.googleads.v0.services.GenerateKeywordIdeaResult;
27+
import com.google.ads.googleads.v0.services.GenerateKeywordIdeasRequest;
28+
import com.google.ads.googleads.v0.services.KeywordPlanIdeaServiceClient;
29+
import com.google.protobuf.StringValue;
30+
import java.io.FileNotFoundException;
31+
import java.io.IOException;
32+
import java.util.ArrayList;
33+
import java.util.Arrays;
34+
import java.util.List;
35+
import java.util.stream.Collectors;
36+
import javax.annotation.Nullable;
37+
38+
/** This example generates keyword ideas from a list of seed keywords. */
39+
public class GenerateKeywordIdeas {
40+
41+
private static class GenerateKeywordIdeasParams extends CodeSampleParams {
42+
43+
@Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
44+
private Long customerId;
45+
46+
@Parameter(
47+
names = ArgumentNames.LOCATION_ID,
48+
required = true,
49+
description =
50+
"Location criteria IDs. For example, specify 21167 for New York. For more information"
51+
+ " on determining this value, see: "
52+
+ " https://developers.google.com/adwords/api/docs/appendix/geotargeting.")
53+
private List<Long> locationIds;
54+
55+
@Parameter(
56+
names = ArgumentNames.LANGUAGE_ID,
57+
required = true,
58+
description =
59+
"A language criterion ID. For example, specify 1000 for English. For more information"
60+
+ " on determining this value, see: "
61+
+ " https://developers.google.com/adwords/api/docs/appendix/codes-formats#languages")
62+
private Long languageId;
63+
64+
@Parameter(names = ArgumentNames.KEYWORD_TEXT)
65+
private List<String> keywords = new ArrayList<>();
66+
67+
@Parameter(
68+
names = ArgumentNames.PAGE_URL,
69+
description = "URL of a page related to your business")
70+
private String pageUrl;
71+
}
72+
73+
public static void main(String[] args) throws IOException {
74+
GenerateKeywordIdeasParams params = new GenerateKeywordIdeasParams();
75+
if (!params.parseArguments(args)) {
76+
// Either pass the required parameters for this example on the command line, or insert them
77+
// into the code here. See the parameter class definition above for descriptions.
78+
params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
79+
params.locationIds =
80+
Arrays.asList(
81+
Long.parseLong("INSERT_LOCATION_ID_1_HERE"),
82+
Long.parseLong("INSERT_LOCATION_ID_2_HERE"));
83+
params.languageId = Long.parseLong("INSERT_LANGUAGE_ID_HERE");
84+
params.keywords = Arrays.asList("INSERT_KEYWORD_1_HERE", "INSERT_KEYWORD_2_HERE");
85+
// Optional: Use a URL related to your business to generate ideas.
86+
params.pageUrl = null;
87+
}
88+
89+
GoogleAdsClient googleAdsClient;
90+
try {
91+
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
92+
} catch (FileNotFoundException fnfe) {
93+
System.err.printf(
94+
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
95+
return;
96+
} catch (IOException ioe) {
97+
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
98+
return;
99+
}
100+
101+
try {
102+
new GenerateKeywordIdeas()
103+
.runExample(
104+
googleAdsClient,
105+
params.customerId,
106+
params.languageId,
107+
params.locationIds,
108+
params.keywords,
109+
params.pageUrl);
110+
} catch (GoogleAdsException gae) {
111+
// GoogleAdsException is the base class for most exceptions thrown by an API request.
112+
// Instances of this exception have a message and a GoogleAdsFailure that contains a
113+
// collection of GoogleAdsErrors that indicate the underlying causes of the
114+
// GoogleAdsException.
115+
System.err.printf(
116+
"Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
117+
gae.getRequestId());
118+
int i = 0;
119+
for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
120+
System.err.printf(" Error %d: %s%n", i++, googleAdsError);
121+
}
122+
}
123+
}
124+
125+
/**
126+
* Runs the example.
127+
*
128+
* @param googleAdsClient the Google Ads API client.
129+
* @param customerId the client customer ID.
130+
* @param languageId the language ID.
131+
* @param locationIds the location IDs.
132+
* @param keywords the list of keywords to use as a seed for ideas.
133+
* @param pageUrl optional URL related to your business to use as a seed for ideas.
134+
* @throws GoogleAdsException if an API request failed with one or more service errors.
135+
* @throws IllegalArgumentException if {@code keywords} is empty and {@code pageUrl} is null.
136+
* @throws Exception if the example failed due to other errors.
137+
*/
138+
private void runExample(
139+
GoogleAdsClient googleAdsClient,
140+
long customerId,
141+
long languageId,
142+
List<Long> locationIds,
143+
List<String> keywords,
144+
@Nullable String pageUrl) {
145+
try (KeywordPlanIdeaServiceClient keywordPlanServiceClient =
146+
googleAdsClient.getKeywordPlanIdeaServiceClient()) {
147+
GenerateKeywordIdeasRequest.Builder requestBuilder =
148+
GenerateKeywordIdeasRequest.newBuilder()
149+
.setCustomerId(Long.toString(customerId))
150+
// Set the language resource using the provided language ID.
151+
.setLanguage(StringValue.of(ResourceNames.languageConstant(languageId)))
152+
// Set the network. To restrict to only Google Search, change the parameter below to
153+
// KeywordPlanNetwork.GOOGLE_SEARCH.
154+
.setKeywordPlanNetwork(KeywordPlanNetwork.GOOGLE_SEARCH_AND_PARTNERS);
155+
156+
// Add the resource name of each location ID to the request.
157+
for (Long locationId : locationIds) {
158+
requestBuilder.addGeoTargetConstants(
159+
StringValue.of(ResourceNames.geoTargetConstant(locationId)));
160+
}
161+
162+
// Make sure that keywords and/or page URL were specified. The request must have exactly one
163+
// of urlSeed, keywordSeed, or keywordAndUrlSeed set.
164+
if (keywords.isEmpty() && pageUrl == null) {
165+
throw new IllegalArgumentException(
166+
"At least one of keywords or page URL is required, but neither was specified.");
167+
}
168+
169+
if (keywords.isEmpty()) {
170+
// Only page URL was specified, so use a UrlSeed.
171+
requestBuilder.getUrlSeedBuilder().setUrl(StringValue.of(pageUrl));
172+
} else if (pageUrl == null) {
173+
// Only keywords were specified, so use a KeywordSeed.
174+
requestBuilder
175+
.getKeywordSeedBuilder()
176+
.addAllKeywords(keywords.stream().map(StringValue::of).collect(Collectors.toList()));
177+
} else {
178+
// Both page URL and keywords were specified, so use a KeywordAndUrlSeed.
179+
requestBuilder
180+
.getKeywordAndUrlSeedBuilder()
181+
.setUrl(StringValue.of(pageUrl))
182+
.addAllKeywords(keywords.stream().map(StringValue::of).collect(Collectors.toList()));
183+
}
184+
185+
// Send the keyword ideas request.
186+
GenerateKeywordIdeaResponse response =
187+
keywordPlanServiceClient.generateKeywordIdeas(requestBuilder.build());
188+
// Print each result in the response.
189+
for (GenerateKeywordIdeaResult result : response.getResultsList()) {
190+
System.out.printf(
191+
"Keyword idea text '%s' has %d average monthly searches and '%s' competition.%n",
192+
result.getText().getValue(),
193+
result.getKeywordIdeaMetrics().getAvgMonthlySearches().getValue(),
194+
result.getKeywordIdeaMetrics().getCompetition());
195+
}
196+
}
197+
}
198+
}

google-ads-examples/src/main/java/com/google/ads/googleads/examples/utils/ArgumentNames.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,12 @@ public final class ArgumentNames {
2828
public static final String CPC_BID_CEILING_MICRO_AMOUNT = "--cpcBidCeilingMicroAmount";
2929
public static final String ARTIFACT_NAME = "--artifactName";
3030
public static final String KEYWORD_TEXT = "--keywordText";
31+
public static final String LANGUAGE_ID = "--languageId";
3132
public static final String LOCATION_ID = "--locationId";
3233
public static final String RECOMMENDATION_ID = "--recommendationId";
3334
public static final String HOTEL_CENTER_ACCOUNT_ID = "--hotelCenterAccountId";
3435
public static final String MERCHANT_CENTER_ACCOUNT_ID = "--merchantCenterAccountId";
3536
public static final String CREATE_DEFAULT_LISTING_GROUP = "--createDefaultListingGroup";
3637
public static final String REPLACE_EXISTING_TREE = "--replaceExistingTree";
38+
public static final String PAGE_URL = "--pageUrl";
3739
}

0 commit comments

Comments
 (0)