GoogleAds API - Java / How to get all existing Keyword Plans?

Viewed 167

I figured out how to create & delete keyword plans, but I couldn't figure out how I can get a list of all my existing keyword plans (resource names / plan ids)?

final long customerId = Long.valueOf("XXXXXXXXXX");    
GoogleAdsClient googleAdsClient = new ...
KeywordPlanServiceClient client = googleAdsClient.getVersion8().createKeywordPlanServiceClient();

String[] allExistingKeywordPlans = client. ???

<dependency>
    <groupId>com.google.api-ads</groupId>
    <artifactId>google-ads</artifactId>
    <version>16.0.0</version>
</dependency>

Further resources: https://developers.google.com/google-ads/api/docs/samples/add-keyword-plan

Any hints on how this can be solved is highly appreciated! Many thanks in advance!

2 Answers

Maybe you can try to fetch the keyword_plan resource from your account. This is how I've done it to create remove operations for all the existing keywordPlans.

GoogleAdsServiceClient.SearchPagedResponse response = client.search(SearchGoogleAdsRequest.newBuilder()
                    .setQuery("SELECT keyword_plan.resource_name FROM keyword_plan")
                    .setCustomerId(Objects.requireNonNull(googleAdsClient.getLoginCustomerId()).toString())
                    .build());
List<KeywordPlanOperation> keywordPlanOperations = response.getPage().getResponse().getResultsList().stream()
                    .map(x -> KeywordPlanOperation.newBuilder()
                            .setRemove(x.getKeywordPlan().getResourceName())
                            .build())
                    .collect(Collectors.toList());

Of course this can also be applied to your use-case.

This is for PHP if you like to remove all of the existing keyword plans:

$googleAdsServiceClient = $this->googleAdsClient->getGoogleAdsServiceClient();

/** @var GoogleAdsServerStreamDecorator $stream */
$stream = $googleAdsServiceClient->searchStream(
    $linkedCustomerId,
    'SELECT keyword_plan.resource_name FROM keyword_plan'
);

$keywordPlanServiceClient = $this->googleAdsClient->getKeywordPlanServiceClient();

/** @var GoogleAdsRow $googleAdsRow */
foreach ($stream->iterateAllElements() as $googleAdsRow) {

    $keywordPlanOperation = new KeywordPlanOperation();
    $keywordPlanOperation->setRemove($googleAdsRow->getKeywordPlan()->getResourceName());
    $keywordPlanServiceClient->mutateKeywordPlans($this->linkedCustomerId, [$keywordPlanOperation]);
}
Related