Shopping Campaign Samples

The code samples below provide examples for managing Shopping campaigns using the AdWords API. Client Library.

Add product partition tree

// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.

package adwords.axis.v201705.shoppingcampaigns;

import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.utils.v201705.shopping.ProductDimensions;
import com.google.api.ads.adwords.axis.utils.v201705.shopping.ProductPartitionNode;
import com.google.api.ads.adwords.axis.utils.v201705.shopping.ProductPartitionTree;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupCriterionOperation;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupCriterionServiceInterface;
import com.google.api.ads.adwords.axis.v201705.cm.ProductCanonicalConditionCondition;
import com.google.api.ads.adwords.axis.v201705.cm.ProductDimensionType;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.client.auth.oauth2.Credential;
import java.util.List;

/**
 * This example clears out any existing ProductPartition criteria on the ad group and rebuilds the
 * tree to contain:
 *
 * <pre>
 *ROOT
 *ProductCanonicalCondition NEW $0.20
 *ProductCanonicalCondition USED $0.10
 *ProductCanonicalCondition null (everything else)
 *  ProductBrand CoolBrand $0.90
 *  ProductBrand CheapBrand $0.01
 *  ProductBrand null (everything else)
 *    ProductType Level1 Luggage & Bags $0.75
 *    ProductType Level1 null (everything else) $0.11
 *</pre>
 *
 * <p>Credentials and properties in {@code fromFile()} are pulled from the
 * "ads.properties" file. See README for more info.
 */
public class AddProductPartitionTree {
  public static void main(String[] args) throws Exception {
    // Generate a refreshable OAuth2 credential.
    Credential oAuth2Credential = new OfflineCredentials.Builder()
        .forApi(Api.ADWORDS)
        .fromFile()
        .build()
        .generateCredential();

    // Construct an AdWordsSession.
    AdWordsSession session = new AdWordsSession.Builder()
        .fromFile()
        .withOAuth2Credential(oAuth2Credential)
        .build();

    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();

    Long adGroupId = Long.valueOf("INSERT_AD_GROUP_ID_HERE");
    
    runExample(adWordsServices, session, adGroupId);
  }

  public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session,
      Long adGroupId) throws Exception {
    // Build a new ProductPartitionTree using the ad group's current set of criteria.
    ProductPartitionTree partitionTree =
        ProductPartitionTree.createAdGroupTree(adWordsServices, session, adGroupId);

    System.out.printf("Original tree:%n%s%n", partitionTree);

    // Clear out any existing criteria.
    ProductPartitionNode rootNode = partitionTree.getRoot().removeAllChildren();

    // Make the root node a subdivision.
    rootNode = rootNode.asSubdivision();

    // Add a unit node for condition = NEW.
    rootNode.addChild(
        ProductDimensions.createCanonicalCondition(ProductCanonicalConditionCondition.NEW))
        .asBiddableUnit().setBid(200000L);

    // Add a unit node for condition = USED.
    rootNode.addChild(
        ProductDimensions.createCanonicalCondition(ProductCanonicalConditionCondition.USED))
        .asBiddableUnit().setBid(100000L);

    // Add a subdivision node for condition = null (everything else).
    ProductPartitionNode otherConditionNode =
        rootNode.addChild(ProductDimensions.createCanonicalCondition(null)).asSubdivision();

    // Add a unit node under condition = null for brand = "CoolBrand".
    otherConditionNode.addChild(ProductDimensions.createBrand("CoolBrand")).asBiddableUnit()
        .setBid(900000L);

    // Add a unit node under condition = null for brand = "CheapBrand".
    otherConditionNode.addChild(ProductDimensions.createBrand("CheapBrand")).asBiddableUnit()
        .setBid(10000L);

    // Add a subdivision node under condition = null for brand = null (everything else).
    ProductPartitionNode otherBrandNode =
        otherConditionNode.addChild(ProductDimensions.createBrand(null)).asSubdivision();

    // Add unit nodes under condition = null/brand = null.
    // The value for each bidding category is a fixed ID for a specific
    // category. You can retrieve IDs for categories from the ConstantDataService.
    // See the 'GetProductCategoryTaxonomy' example for more details.

    // Add a unit node under condition = null/brand = null for product type
    // level 1 = 'Luggage & Bags'.
    otherBrandNode.addChild(ProductDimensions.createBiddingCategory(
        ProductDimensionType.BIDDING_CATEGORY_L1, -5914235892932915235L)).asBiddableUnit()
        .setBid(750000L);

    // Add a unit node under condition = null/brand = null for product type
    // level 1 = null (everything else).
    otherBrandNode.addChild(
        ProductDimensions.createBiddingCategory(ProductDimensionType.BIDDING_CATEGORY_L1, null))
        .asBiddableUnit().setBid(110000L);

    // Get the ad group criterion service.
    AdGroupCriterionServiceInterface adGroupCriterionService =
        adWordsServices.get(session, AdGroupCriterionServiceInterface.class);

    // Make the mutate request, using the operations returned by the ProductPartitionTree.
    List<AdGroupCriterionOperation> mutateOperations = partitionTree.getMutateOperations();

    if (mutateOperations.isEmpty()) {
      System.out.println("Skipping the mutate call because the original tree and the current tree "
          + "are logically identical.");
    } else {
      adGroupCriterionService.mutate(mutateOperations.toArray(new AdGroupCriterionOperation[0]));
    }

    // The request was successful, so create a new ProductPartitionTree based on the updated state
    // of the ad group.
    partitionTree = ProductPartitionTree.createAdGroupTree(adWordsServices, session, adGroupId);

    // Show the tree
    System.out.printf("Updated tree:%n%s%n", partitionTree);
  }
}

Add product scope

// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.

package adwords.axis.v201705.shoppingcampaigns;

import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.v201705.cm.CampaignCriterion;
import com.google.api.ads.adwords.axis.v201705.cm.CampaignCriterionOperation;
import com.google.api.ads.adwords.axis.v201705.cm.CampaignCriterionReturnValue;
import com.google.api.ads.adwords.axis.v201705.cm.CampaignCriterionServiceInterface;
import com.google.api.ads.adwords.axis.v201705.cm.Operator;
import com.google.api.ads.adwords.axis.v201705.cm.ProductBiddingCategory;
import com.google.api.ads.adwords.axis.v201705.cm.ProductBrand;
import com.google.api.ads.adwords.axis.v201705.cm.ProductCanonicalCondition;
import com.google.api.ads.adwords.axis.v201705.cm.ProductCanonicalConditionCondition;
import com.google.api.ads.adwords.axis.v201705.cm.ProductCustomAttribute;
import com.google.api.ads.adwords.axis.v201705.cm.ProductDimension;
import com.google.api.ads.adwords.axis.v201705.cm.ProductDimensionType;
import com.google.api.ads.adwords.axis.v201705.cm.ProductOfferId;
import com.google.api.ads.adwords.axis.v201705.cm.ProductScope;
import com.google.api.ads.adwords.axis.v201705.cm.ProductType;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.client.auth.oauth2.Credential;

/**
 * This example restricts the products that will be included in the
 * campaign by setting a ProductScope.
 *
 * <p>Credentials and properties in {@code fromFile()} are pulled from the
 * "ads.properties" file. See README for more info.
 */
public class AddProductScope {
  public static void main(String[] args) throws Exception {
    // Generate a refreshable OAuth2 credential.
    Credential oAuth2Credential = new OfflineCredentials.Builder()
        .forApi(Api.ADWORDS)
        .fromFile()
        .build()
        .generateCredential();

    // Construct an AdWordsSession.
    AdWordsSession session = new AdWordsSession.Builder()
        .fromFile()
        .withOAuth2Credential(oAuth2Credential)
        .build();

    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();

    Long campaignId = Long.valueOf("INSERT_CAMPAIGN_ID_HERE");
    
    runExample(adWordsServices, session, campaignId);
  }

  public static void runExample(
      AdWordsServicesInterface adWordsServices, AdWordsSession session, Long campaignId)
      throws Exception {
    // Get the campaign criterion service.
    CampaignCriterionServiceInterface campaignCriterionService = adWordsServices.get(session,
        CampaignCriterionServiceInterface.class);
    
    ProductScope productScope = new ProductScope();

    // This set of dimensions is for demonstration purposes only. It would be
    // extremely unlikely that you want to include so many dimensions in your
    // product scope.
    ProductBrand productBrand = new ProductBrand();
    productBrand.setValue("Nexus");

    ProductCanonicalCondition productCanonicalCondition = new ProductCanonicalCondition();
    productCanonicalCondition.setCondition(ProductCanonicalConditionCondition.NEW);

    ProductCustomAttribute productCustomAttribute = new ProductCustomAttribute();
    productCustomAttribute.setType(ProductDimensionType.CUSTOM_ATTRIBUTE_0);
    productCustomAttribute.setValue("my attribute value");

    ProductOfferId productOfferId = new ProductOfferId();
    productOfferId.setValue("book1");

    ProductType productTypeLevel1Media = new ProductType();
    productTypeLevel1Media.setType(ProductDimensionType.PRODUCT_TYPE_L1);
    productTypeLevel1Media.setValue("Media");

    ProductType productTypeLevel2Books = new ProductType();
    productTypeLevel2Books.setType(ProductDimensionType.PRODUCT_TYPE_L2);
    productTypeLevel2Books.setValue("Books");

    // The value for the bidding category is a fixed ID for the 'Luggage & Bags'
    // category. You can retrieve IDs for categories from the ConstantDataService.
    // See the 'GetProductCategoryTaxonomy' example for more details.
    ProductBiddingCategory productBiddingCategory = new ProductBiddingCategory();
    productBiddingCategory.setType(ProductDimensionType.BIDDING_CATEGORY_L1);
    productBiddingCategory.setValue(-5914235892932915235L);
    
    productScope.setDimensions(new ProductDimension[]{ productBrand, productCanonicalCondition,
        productCustomAttribute, productOfferId, productTypeLevel1Media, productTypeLevel2Books,
        productBiddingCategory});

    CampaignCriterion campaignCriterion = new CampaignCriterion();
    campaignCriterion.setCampaignId(campaignId);
    campaignCriterion.setCriterion(productScope);
    
    // Create operation.
    CampaignCriterionOperation criterionOperation = new CampaignCriterionOperation();
    criterionOperation.setOperand(campaignCriterion);
    criterionOperation.setOperator(Operator.ADD);
    
    // Make the mutate request.
    CampaignCriterionReturnValue result =
        campaignCriterionService.mutate(new CampaignCriterionOperation[] {criterionOperation});

    // Display the result.
    System.out.printf("Created a ProductScope criterion with ID %d.%n",
        result.getValue(0).getCriterion().getId());
  }
}

Add Shopping campaign

// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.

package adwords.axis.v201705.shoppingcampaigns;

import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.utils.v201705.shopping.ProductPartitionTree;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroup;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupAd;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupAdOperation;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupAdReturnValue;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupAdServiceInterface;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupCriterion;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupCriterionOperation;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupCriterionReturnValue;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupCriterionServiceInterface;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupOperation;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupReturnValue;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupServiceInterface;
import com.google.api.ads.adwords.axis.v201705.cm.AdvertisingChannelType;
import com.google.api.ads.adwords.axis.v201705.cm.BiddingStrategyConfiguration;
import com.google.api.ads.adwords.axis.v201705.cm.BiddingStrategyType;
import com.google.api.ads.adwords.axis.v201705.cm.Budget;
import com.google.api.ads.adwords.axis.v201705.cm.Campaign;
import com.google.api.ads.adwords.axis.v201705.cm.CampaignOperation;
import com.google.api.ads.adwords.axis.v201705.cm.CampaignReturnValue;
import com.google.api.ads.adwords.axis.v201705.cm.CampaignServiceInterface;
import com.google.api.ads.adwords.axis.v201705.cm.CampaignStatus;
import com.google.api.ads.adwords.axis.v201705.cm.Operator;
import com.google.api.ads.adwords.axis.v201705.cm.ProductAd;
import com.google.api.ads.adwords.axis.v201705.cm.Setting;
import com.google.api.ads.adwords.axis.v201705.cm.ShoppingSetting;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.client.auth.oauth2.Credential;
import java.util.List;

/**
 * This example adds a shopping campaign.
 *
 * <p>Credentials and properties in {@code fromFile()} are pulled from the
 * "ads.properties" file. See README for more info.
 */
public class AddShoppingCampaign {
  public static void main(String[] args) throws Exception {
    // Generate a refreshable OAuth2 credential.
    Credential oAuth2Credential = new OfflineCredentials.Builder()
        .forApi(Api.ADWORDS)
        .fromFile()
        .build()
        .generateCredential();

    // Construct an AdWordsSession.
    AdWordsSession session = new AdWordsSession.Builder()
        .fromFile()
        .withOAuth2Credential(oAuth2Credential)
        .build();

    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();

    Long budgetId = Long.valueOf("INSERT_BUDGET_ID_HERE");
    Long merchantId = Long.valueOf("INSERT_MERCHANT_CENTER_ID_HERE");
    // If set to true, a default partition will be created. If running the
    // AddProductPartitionTree.java example right after this example, make sure this stays set to
    // false.
    boolean createDefaultPartition = false;
    
    runExample(adWordsServices, session, budgetId, merchantId, createDefaultPartition);
  }

  public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session,
      Long budgetId, Long merchantId, boolean createDefaultPartition) throws Exception {
    // Get the CampaignService
    CampaignServiceInterface campaignService =
        adWordsServices.get(session, CampaignServiceInterface.class);

    // Create campaign.
    Campaign campaign = new Campaign();
    campaign.setName("Shopping campaign #" + System.currentTimeMillis());
    // The advertisingChannelType is what makes this a Shopping campaign
    campaign.setAdvertisingChannelType(AdvertisingChannelType.SHOPPING);

    // Recommendation: Set the campaign to PAUSED when creating it to prevent
    // the ads from immediately serving. Set to ENABLED once you've added
    // targeting and the ads are ready to serve.
    campaign.setStatus(CampaignStatus.PAUSED);

    // Set shared budget (required).
    Budget budget = new Budget();
    budget.setBudgetId(budgetId);
    campaign.setBudget(budget);

    // Set bidding strategy (required).
    BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration();
    biddingStrategyConfiguration.setBiddingStrategyType(BiddingStrategyType.MANUAL_CPC);
    campaign.setBiddingStrategyConfiguration(biddingStrategyConfiguration);

    // All Shopping campaigns need a ShoppingSetting.
    ShoppingSetting shoppingSetting = new ShoppingSetting();
    shoppingSetting.setSalesCountry("US");
    shoppingSetting.setCampaignPriority(0);
    shoppingSetting.setMerchantId(merchantId);
    
    // Set to 'true' to enable Local Inventory Ads in your campaign.
    shoppingSetting.setEnableLocal(true);
    
    campaign.setSettings(new Setting[] {shoppingSetting});

    // Create operation.
    CampaignOperation campaignOperation = new CampaignOperation();
    campaignOperation.setOperand(campaign);
    campaignOperation.setOperator(Operator.ADD);

    // Make the mutate request.
    CampaignReturnValue campaignAddResult =
        campaignService.mutate(new CampaignOperation[] {campaignOperation});

    // Display result.
    campaign = campaignAddResult.getValue(0);

    System.out.printf("Campaign with name '%s' and ID %d was added.%n", campaign.getName(),
        campaign.getId());

    // Get the AdGroupService.
    AdGroupServiceInterface adGroupService =
        adWordsServices.get(session, AdGroupServiceInterface.class);

    // Create ad group.
    AdGroup adGroup = new AdGroup();
    adGroup.setCampaignId(campaign.getId());
    adGroup.setName("Ad Group #" + System.currentTimeMillis());

    // Create operation.
    AdGroupOperation adGroupOperation = new AdGroupOperation();
    adGroupOperation.setOperand(adGroup);
    adGroupOperation.setOperator(Operator.ADD);

    // Make the mutate request.
    AdGroupReturnValue adGroupAddResult =
        adGroupService.mutate(new AdGroupOperation[] {adGroupOperation});

    // Display result.
    adGroup = adGroupAddResult.getValue(0);
    System.out.printf("Ad group with name '%s' and ID %d was added.%n", adGroup.getName(),
        adGroup.getId());

    // Create product ad.
    AdGroupAdServiceInterface adGroupAdService =
        adWordsServices.get(session, AdGroupAdServiceInterface.class);
    ProductAd productAd = new ProductAd();

    // Create ad group ad.
    AdGroupAd adGroupAd = new AdGroupAd();
    adGroupAd.setAdGroupId(adGroup.getId());
    adGroupAd.setAd(productAd);

    // Create operation.
    AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation();
    adGroupAdOperation.setOperand(adGroupAd);
    adGroupAdOperation.setOperator(Operator.ADD);

    // Make the mutate request.
    AdGroupAdReturnValue adGroupAdAddResult =
        adGroupAdService.mutate(new AdGroupAdOperation[] {adGroupAdOperation});

    // Display result.
    adGroupAd = adGroupAdAddResult.getValue(0);
    
    System.out.printf("Product ad with ID %d was added.%n", adGroupAd.getAd().getId());

    if (createDefaultPartition) {
      // Create an ad group criterion for 'All products' using the ProductPartitionTree utility.
      ProductPartitionTree productPartitionTree =
          ProductPartitionTree.createAdGroupTree(adWordsServices, session, adGroup.getId());
      productPartitionTree
          .getRoot()
          .asBiddableUnit()
          .setBid(500000L);
      List<AdGroupCriterionOperation> mutateOperations = productPartitionTree.getMutateOperations();

      // Make the mutate request.
      AdGroupCriterionServiceInterface adGroupCriterionService =
          adWordsServices.get(session, AdGroupCriterionServiceInterface.class);
      AdGroupCriterionReturnValue adGroupCriterionResult =
          adGroupCriterionService.mutate(
              mutateOperations.toArray(new AdGroupCriterionOperation[0]));

      // Display result.
      for (AdGroupCriterion adGroupCriterion : adGroupCriterionResult.getValue()) {
        System.out.printf(
            "Ad group criterion with ID %d in ad group with ID %d was added.%n",
            adGroupCriterion.getCriterion().getId(), adGroupCriterion.getAdGroupId());
      }
    }
  }
}

Add campaign for Showcase Shopping ads

// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.

package adwords.axis.v201705.shoppingcampaigns;

import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.utils.v201705.shopping.ProductDimensions;
import com.google.api.ads.adwords.axis.utils.v201705.shopping.ProductPartitionNode;
import com.google.api.ads.adwords.axis.utils.v201705.shopping.ProductPartitionTree;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroup;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupAd;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupAdOperation;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupAdReturnValue;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupAdServiceInterface;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupCriterionOperation;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupCriterionServiceInterface;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupOperation;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupReturnValue;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupServiceInterface;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupType;
import com.google.api.ads.adwords.axis.v201705.cm.AdvertisingChannelType;
import com.google.api.ads.adwords.axis.v201705.cm.ApiException;
import com.google.api.ads.adwords.axis.v201705.cm.BiddingStrategyConfiguration;
import com.google.api.ads.adwords.axis.v201705.cm.BiddingStrategyType;
import com.google.api.ads.adwords.axis.v201705.cm.Bids;
import com.google.api.ads.adwords.axis.v201705.cm.Budget;
import com.google.api.ads.adwords.axis.v201705.cm.Campaign;
import com.google.api.ads.adwords.axis.v201705.cm.CampaignOperation;
import com.google.api.ads.adwords.axis.v201705.cm.CampaignReturnValue;
import com.google.api.ads.adwords.axis.v201705.cm.CampaignServiceInterface;
import com.google.api.ads.adwords.axis.v201705.cm.CampaignStatus;
import com.google.api.ads.adwords.axis.v201705.cm.CpcBid;
import com.google.api.ads.adwords.axis.v201705.cm.Image;
import com.google.api.ads.adwords.axis.v201705.cm.Media;
import com.google.api.ads.adwords.axis.v201705.cm.MediaMediaType;
import com.google.api.ads.adwords.axis.v201705.cm.MediaServiceInterface;
import com.google.api.ads.adwords.axis.v201705.cm.Money;
import com.google.api.ads.adwords.axis.v201705.cm.Operator;
import com.google.api.ads.adwords.axis.v201705.cm.ProductCanonicalConditionCondition;
import com.google.api.ads.adwords.axis.v201705.cm.Setting;
import com.google.api.ads.adwords.axis.v201705.cm.ShoppingSetting;
import com.google.api.ads.adwords.axis.v201705.cm.ShowcaseAd;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.client.auth.oauth2.Credential;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.List;

/**
 * This example adds a Shopping campaign for Showcase ads.
 *
 * <p>Credentials and properties in {@code fromFile()} are pulled from the "ads.properties" file.
 * See README for more info.
 */
public class AddShoppingCampaignForShowcaseAds {
  public static void main(String[] args) throws Exception {
    // Generate a refreshable OAuth2 credential.
    Credential oAuth2Credential =
        new OfflineCredentials.Builder()
            .forApi(Api.ADWORDS)
            .fromFile()
            .build()
            .generateCredential();

    // Construct an AdWordsSession.
    AdWordsSession session =
        new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build();

    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();

    Long budgetId = Long.valueOf("INSERT_BUDGET_ID_HERE");
    Long merchantId = Long.valueOf("INSERT_MERCHANT_CENTER_ID_HERE");

    runExample(adWordsServices, session, budgetId, merchantId);
  }

  public static void runExample(
      AdWordsServicesInterface adWordsServices,
      AdWordsSession session,
      Long budgetId,
      Long merchantId)
      throws Exception {
    Campaign campaign = createCampaign(adWordsServices, session, budgetId, merchantId);
    System.out.printf(
        "Campaign with name '%s' and ID %d was added.%n", campaign.getName(), campaign.getId());

    AdGroup adGroup = createAdGroup(adWordsServices, session, campaign);
    System.out.printf(
        "Ad group with name '%s' and ID %d was added.%n", adGroup.getName(), adGroup.getId());

    AdGroupAd adGroupAd = createShowcaseAd(adWordsServices, session, adGroup);
    System.out.printf("Showcase ad with ID %d was added.%n", adGroupAd.getAd().getId());

    ProductPartitionTree partitionTree =
        createProductPartitions(adWordsServices, session, adGroup.getId());
    System.out.printf("Final tree: %s%n", partitionTree);
  }

  /** Creates a Shopping campaign. */
  private static Campaign createCampaign(
      AdWordsServicesInterface adWordsServices,
      AdWordsSession session,
      Long budgetId,
      Long merchantId)
      throws RemoteException, ApiException {
    // Get the CampaignService
    CampaignServiceInterface campaignService =
        adWordsServices.get(session, CampaignServiceInterface.class);

    // Create campaign.
    Campaign campaign = new Campaign();
    campaign.setName("Shopping campaign #" + System.currentTimeMillis());
    // The advertisingChannelType is what makes this a Shopping campaign
    campaign.setAdvertisingChannelType(AdvertisingChannelType.SHOPPING);

    // Recommendation: Set the campaign to PAUSED when creating it to prevent
    // the ads from immediately serving. Set to ENABLED once you've added
    // targeting and the ads are ready to serve.
    campaign.setStatus(CampaignStatus.PAUSED);

    // Set shared budget (required).
    Budget budget = new Budget();
    budget.setBudgetId(budgetId);
    campaign.setBudget(budget);

    // Set bidding strategy (required).
    BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration();
    biddingStrategyConfiguration.setBiddingStrategyType(BiddingStrategyType.MANUAL_CPC);
    campaign.setBiddingStrategyConfiguration(biddingStrategyConfiguration);

    // All Shopping campaigns need a ShoppingSetting.
    ShoppingSetting shoppingSetting = new ShoppingSetting();
    shoppingSetting.setSalesCountry("US");
    shoppingSetting.setCampaignPriority(0);
    shoppingSetting.setMerchantId(merchantId);

    // Set to 'true' to enable Local Inventory Ads in your campaign.
    shoppingSetting.setEnableLocal(true);

    campaign.setSettings(new Setting[] {shoppingSetting});

    // Create operation.
    CampaignOperation campaignOperation = new CampaignOperation();
    campaignOperation.setOperand(campaign);
    campaignOperation.setOperator(Operator.ADD);

    // Make the mutate request.
    CampaignReturnValue campaignAddResult =
        campaignService.mutate(new CampaignOperation[] {campaignOperation});

    return campaignAddResult.getValue(0);
  }

  /** Creates an ad group in the Shopping campaign. */
  private static AdGroup createAdGroup(
      AdWordsServicesInterface adWordsServices, AdWordsSession session, Campaign campaign)
      throws RemoteException, ApiException {
    // Get the AdGroupService.
    AdGroupServiceInterface adGroupService =
        adWordsServices.get(session, AdGroupServiceInterface.class);

    // Create ad group.
    AdGroup adGroup = new AdGroup();
    adGroup.setCampaignId(campaign.getId());
    adGroup.setName("Ad Group #" + System.currentTimeMillis());

    // Required: Set the ad group type to SHOPPING_SHOWCASE_ADS.
    adGroup.setAdGroupType(AdGroupType.SHOPPING_SHOWCASE_ADS);

    // Required: Set the ad group's bidding strategy configuration.
    BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration();

    // Optional: Set the bids.
    Money bidAmount = new Money();
    bidAmount.setMicroAmount(100000L);
    CpcBid cpcBid = new CpcBid();
    cpcBid.setBid(bidAmount);
    biddingStrategyConfiguration.setBids(new Bids[] {cpcBid});

    adGroup.setBiddingStrategyConfiguration(biddingStrategyConfiguration);

    // Create operation.
    AdGroupOperation adGroupOperation = new AdGroupOperation();
    adGroupOperation.setOperand(adGroup);
    adGroupOperation.setOperator(Operator.ADD);

    // Make the mutate request.
    AdGroupReturnValue adGroupAddResult =
        adGroupService.mutate(new AdGroupOperation[] {adGroupOperation});

    return adGroupAddResult.getValue(0);
  }

  /** Creates a Showcase ad. */
  private static AdGroupAd createShowcaseAd(
      AdWordsServicesInterface adWordsServices, AdWordsSession session, AdGroup adGroup)
      throws IOException, RemoteException, ApiException {
    // Create the Showcase ad.
    AdGroupAdServiceInterface adGroupAdService =
        adWordsServices.get(session, AdGroupAdServiceInterface.class);
    ShowcaseAd showcaseAd = new ShowcaseAd();
    showcaseAd.setName("Showcase ad #" + System.currentTimeMillis());
    showcaseAd.setFinalUrls(new String[] {"http://example.com/showcase"});
    showcaseAd.setDisplayUrl("example.com");

    // Required: Set the ad's expanded image.
    Image expandedImage = new Image();
    expandedImage.setMediaId(uploadImage(adWordsServices, session, "https://goo.gl/IfVlpF"));
    showcaseAd.setExpandedImage(expandedImage);

    // Optional: Set the collapsed image.
    Image collapsedImage = new Image();
    collapsedImage.setMediaId(uploadImage(adWordsServices, session, "https://goo.gl/NqTxAE"));
    showcaseAd.setCollapsedImage(collapsedImage);

    // Create ad group ad.
    AdGroupAd adGroupAd = new AdGroupAd();
    adGroupAd.setAdGroupId(adGroup.getId());
    adGroupAd.setAd(showcaseAd);

    // Create operation.
    AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation();
    adGroupAdOperation.setOperand(adGroupAd);
    adGroupAdOperation.setOperator(Operator.ADD);

    // Make the mutate request.
    AdGroupAdReturnValue adGroupAdAddResult =
        adGroupAdService.mutate(new AdGroupAdOperation[] {adGroupAdOperation});

    return adGroupAdAddResult.getValue(0);
  }

  /** Creates the product partition tree for the ad group. */
  private static ProductPartitionTree createProductPartitions(
      AdWordsServicesInterface adWordsServices, AdWordsSession session, Long adGroupId)
      throws ApiException, RemoteException {
    AdGroupCriterionServiceInterface adGroupCriterionService =
        adWordsServices.get(session, AdGroupCriterionServiceInterface.class);

    ProductPartitionTree partitionTree =
        ProductPartitionTree.createAdGroupTree(adWordsServices, session, adGroupId);
    System.out.printf("Original tree: %s%n", partitionTree);

    // Clear out any existing criteria.
    ProductPartitionNode rootNode = partitionTree.getRoot().removeAllChildren();

    // Make the root node a subdivision.
    rootNode = rootNode.asSubdivision();

    // Add a unit node for condition = NEW to include it.
    rootNode
        .addChild(
            ProductDimensions.createCanonicalCondition(ProductCanonicalConditionCondition.NEW))
        .asBiddableUnit();

    // Add a unit node for condition = USED to include it.
    rootNode
        .addChild(
            ProductDimensions.createCanonicalCondition(ProductCanonicalConditionCondition.USED))
        .asBiddableUnit();

    // Exclude everything else.
    rootNode.addChild(ProductDimensions.createCanonicalCondition(null)).asExcludedUnit();

    // Make the mutate request, using the operations returned by the ProductPartitionTree.
    List<AdGroupCriterionOperation> mutateOperations = partitionTree.getMutateOperations();
    if (mutateOperations.isEmpty()) {
      System.out.println(
          "Skipping the mutate call because the original tree and the current "
              + "tree are logically identical.");
    } else {
      adGroupCriterionService.mutate(
          mutateOperations.toArray(new AdGroupCriterionOperation[mutateOperations.size()]));
    }

    // The request was successful, so create a new ProductPartitionTree based on the updated
    // state of the ad group.
    return ProductPartitionTree.createAdGroupTree(adWordsServices, session, adGroupId);
  }

  /** Uploads an image. */
  private static long uploadImage(
      AdWordsServicesInterface adWordsServices, AdWordsSession session, String url)
      throws IOException {
    MediaServiceInterface mediaService = adWordsServices.get(session, MediaServiceInterface.class);

    // Create image.
    Image image = new Image();
    image.setData(com.google.api.ads.common.lib.utils.Media.getMediaDataFromUrl(url));
    image.setType(MediaMediaType.IMAGE);

    Media[] media = new Media[] {image};

    // Upload image.
    Media[] result = mediaService.upload(media);

    return result[0].getMediaId();
  }
}

Get product category taxonomy

// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.

package adwords.axis.v201705.shoppingcampaigns;

import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.utils.v201705.SelectorBuilder;
import com.google.api.ads.adwords.axis.v201705.cm.ConstantDataServiceInterface;
import com.google.api.ads.adwords.axis.v201705.cm.ProductBiddingCategoryData;
import com.google.api.ads.adwords.axis.v201705.cm.Selector;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface;
import com.google.api.ads.adwords.lib.selectorfields.v201705.cm.ConstantDataField;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.client.auth.oauth2.Credential;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * This example fetches the set of valid ProductBiddingCategories.
 *
 * <p>Credentials and properties in {@code fromFile()} are pulled from the
 * "ads.properties" file. See README for more info.
 */
public class GetProductCategoryTaxonomy {

  public static void main(String[] args) throws Exception {
    // Generate a refreshable OAuth2 credential.
    Credential oAuth2Credential = new OfflineCredentials.Builder()
        .forApi(Api.ADWORDS)
        .fromFile()
        .build()
        .generateCredential();

    // Construct an AdWordsSession.
    AdWordsSession session = new AdWordsSession.Builder()
        .fromFile()
        .withOAuth2Credential(oAuth2Credential)
        .build();

    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();

    runExample(adWordsServices, session);
  }

  public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session)
      throws Exception {
    // Get the constant data service.
    ConstantDataServiceInterface constantDataService =
        adWordsServices.get(session, ConstantDataServiceInterface.class);
    
    Selector selector = new SelectorBuilder()
      .equals(ConstantDataField.Country, "US")
      .build();
    
    ProductBiddingCategoryData[] results =
        constantDataService.getProductBiddingCategoryData(selector);
    
    // List of top level category nodes.
    List<CategoryNode> rootCategories = new ArrayList<>();
    // Map of category ID to category node for all categories found in the results.
    Map<Long, CategoryNode> biddingCategories = Maps.newHashMap();
    
    for (ProductBiddingCategoryData productBiddingCategoryData : results) {
      Long id = productBiddingCategoryData.getDimensionValue().getValue();
      String name = productBiddingCategoryData.getDisplayValue(0).getValue();
      CategoryNode node = biddingCategories.get(id);
      if (node == null) {
        node = new CategoryNode(id, name);
        biddingCategories.put(id, node);
      } else if (node.name == null) {
        // Ensure that the name attribute for the node is set. Name will be null for nodes added
        // to biddingCategories as a result of being a parentNode below.
        node.name = name;
      }

      if (productBiddingCategoryData.getParentDimensionValue() != null
          && productBiddingCategoryData.getParentDimensionValue().getValue() != null) {
        Long parentId = productBiddingCategoryData.getParentDimensionValue().getValue();
        CategoryNode parentNode = biddingCategories.get(parentId);
        if (parentNode == null) {
          parentNode = new CategoryNode(parentId);
          biddingCategories.put(parentId, parentNode);
        }
        parentNode.children.add(node);
      } else {
        rootCategories.add(node);
      }
    }
    displayCategories(rootCategories, "");
  }

  /**
   * Recursively prints out each category node and its children.
   *
   * @param categories the categories to print.
   * @param prefix the string to print at the beginning of each line of output.
   */
  private static void displayCategories(List<CategoryNode> categories, String prefix) {
    for (CategoryNode category : categories) {
      System.out.printf("%s%s [%s]%n", prefix, category.name, category.id);
      displayCategories(category.children, String.format("%s%s > ", prefix, category.name));
    }
  }

  /**
   * Node that tracks a product bidding category's id, name, and child nodes.
   */
  private static class CategoryNode {
    final Long id;
    String name;
    final List<CategoryNode> children;

    /**
     * Constructor for categories first encountered as non-parent elements in the results.
     *
     * @param id the ID of the category
     * @param name the name of the category
     */
    CategoryNode(Long id, String name) {
      this.children = new ArrayList<>();
      this.id = Preconditions.checkNotNull(id);
      this.name = name;
    }

    /**
     * Constructor for categories first encountered as a parent category, in which case only the ID
     * is available.
     *
     * @param id the ID of the category
     */
    CategoryNode(Long id) {
      this(id, null);
    }
  }
}

Send feedback about...

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