Register for one of our Google Ads API Migration Workshops (October 5, 2021 - October 14, 2021)

Create ad group and ad group ad

Create an ad group

Similar to the Campaign created in previous steps, this ad group requires minimal configuration because it is optimized automatically.

Key requirements for Smart campaign ad groups:

Below we set the campaign field to the temporary resource name used to create a campaign in earlier steps.

Java

private MutateOperation createAdGroupOperation(long customerId) {
  MutateOperation.Builder builder = MutateOperation.newBuilder();
  builder
      .getAdGroupOperationBuilder()
      .getCreateBuilder()
      .setResourceName(ResourceNames.adGroup(customerId, AD_GROUP_TEMPORARY_ID))
      .setName("Smart campaign ad group " + CodeSampleHelper.getShortPrintableDateTime())
      .setCampaign(ResourceNames.campaign(customerId, SMART_CAMPAIGN_TEMPORARY_ID))
      .setType(AdGroupType.SMART_CAMPAIGN_ADS);
  return builder.build();
}
      
      

C#

/// <summary>
/// Creates a MutateOperation that creates a new ad group.
/// A temporary ID will be used in the campaign resource name for this ad group to associate
/// it with the Smart campaign created in earlier steps. A temporary ID will also be used
/// for its own resource name so that we can associate an ad group ad with it later in the
/// process.
/// Only one ad group can be created for a given Smart campaign.
/// </summary>
/// <param name="customerId">The Google Ads customer ID.</param>
/// <returns>A MutateOperation that creates a new ad group.</returns>
private MutateOperation CreateAdGroupOperation(long customerId)
{
    return new MutateOperation
    {
        AdGroupOperation = new AdGroupOperation
        {
            Create = new AdGroup
            {
                // Set the ad group ID to a temporary ID.
                ResourceName = ResourceNames.AdGroup(customerId, AD_GROUP_TEMPORARY_ID),
                Name = $"Smart campaign ad group #{ExampleUtilities.GetRandomString()}",
                // Set the campaign ID to a temporary ID.
                Campaign = ResourceNames.Campaign(customerId, SMART_CAMPAIGN_TEMPORARY_ID),
                // The ad group type must be SmartCampaignAds.
                Type = AdGroupType.SmartCampaignAds
            }
        }
    };
}
      
      

PHP

private static function createAdGroupOperation(int $customerId): MutateOperation
{
    // Creates the ad group object.
    $adGroup = new AdGroup([
        // Sets the ad group ID to a temporary ID.
        'resource_name' => ResourceNames::forAdGroup($customerId, self::AD_GROUP_TEMPORARY_ID),
        'name' => "Smart campaign ad group #" . Helper::getPrintableDatetime(),
        // Sets the campaign ID to a temporary ID.
        'campaign' =>
            ResourceNames::forCampaign($customerId, self::SMART_CAMPAIGN_TEMPORARY_ID),
        // The ad group type must be set to SMART_CAMPAIGN_ADS.
        'type' => AdGroupType::SMART_CAMPAIGN_ADS
    ]);

    // Creates the MutateOperation that creates the ad group.
    return new MutateOperation([
        'ad_group_operation' => new AdGroupOperation(['create' => $adGroup])
    ]);
}
      
      

Python

def _create_ad_group_operation(client, customer_id):
    """Creates a MutateOperation that creates a new ad group.

    A temporary ID will be used in the campaign resource name for this
    ad group to associate it with the Smart campaign created in earlier steps.
    A temporary ID will also be used for its own resource name so that we can
    associate an ad group ad with it later in the process.

    Only one ad group can be created for a given Smart campaign.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.

    Returns:
        a MutateOperation that creates a new ad group.
    """
    mutate_operation = client.get_type("MutateOperation")
    ad_group = mutate_operation.ad_group_operation.create
    # Set the ad group ID to a temporary ID.
    ad_group.resource_name = client.get_service("AdGroupService").ad_group_path(
        customer_id, _AD_GROUP_TEMPORARY_ID
    )
    ad_group.name = f"Smart campaign ad group #{uuid4()}"
    # Set the campaign ID to a temporary ID.
    ad_group.campaign = client.get_service("CampaignService").campaign_path(
        customer_id, _SMART_CAMPAIGN_TEMPORARY_ID
    )
    # The ad group type must be set to SMART_CAMPAIGN_ADS.
    ad_group.type_ = client.enums.AdGroupTypeEnum.SMART_CAMPAIGN_ADS

    return mutate_operation
      
      

Ruby

# Creates a mutate_operation that creates a new ad group.
# A temporary ID will be used in the campaign resource name for this
# ad group to associate it with the Smart campaign created in earlier steps.
# A temporary ID will also be used for its own resource name so that we can
# associate an ad group ad with it later in the process.
# Only one ad group can be created for a given Smart campaign.
def create_ad_group_operation(client, customer_id)
  mutate_operation = client.operation.mutate do |m|
    m.ad_group_operation = client.operation.create_resource.ad_group do |ag|
      # Set the ad group ID to a temporary ID.
      ag.resource_name = client.path.ad_group(customer_id, AD_GROUP_TEMPORARY_ID)
      ag.name = "Smart campaign ad group ##{(Time.new.to_f * 1000).to_i}"
      # Set the campaign ID to a temporary ID.
      ag.campaign = client.path.campaign(customer_id, SMART_CAMPAIGN_TEMPORARY_ID)
      # The ad group type must be set to SMART_CAMPAIGN_ADS.
      ag.type = :SMART_CAMPAIGN_ADS
    end
  end

  mutate_operation
end
      
      

Perl

# Creates a MutateOperation that creates a new ad group. A temporary ID will be
# used in the campaign resource name for this ad group to associate it with the
# Smart campaign created in earlier steps. A temporary ID will also be used for
# its own resource name so that we can associate an ad group ad with it later in
# the process. Only one ad group can be created for a given Smart campaign.
sub _create_ad_group_operation {
  my ($customer_id) = @_;

  return
    Google::Ads::GoogleAds::V8::Services::GoogleAdsService::MutateOperation->
    new({
      adGroupOperation =>
        Google::Ads::GoogleAds::V8::Services::AdGroupService::AdGroupOperation
        ->new({
          create => Google::Ads::GoogleAds::V8::Resources::AdGroup->new({
              # Set the ad group ID to a temporary ID.
              resourceName =>
                Google::Ads::GoogleAds::V8::Utils::ResourceNames::ad_group(
                $customer_id, AD_GROUP_TEMPORARY_ID
                ),
              name => "Smart campaign ad group #" . uniqid(),
              # Set the campaign ID to a temporary ID.
              campaign =>
                Google::Ads::GoogleAds::V8::Utils::ResourceNames::campaign(
                $customer_id, SMART_CAMPAIGN_TEMPORARY_ID
                ),
              # The ad group type must be SMART_CAMPAIGN_ADS.
              type => SMART_CAMPAIGN_ADS
            })})});
}
      
      

Create an ad group ad

Even though a Smart campaign can contain only a single ad group, that ad group can contain multiple ads. Since the ad text for Smart campaigns is selected dynamically, it's possible that the headlines and descriptions from multiple different ads could be combined.

Key requirements for Smart campaign ads:

Below we set the ad_group field to the temporary resource name used to create the ad group above.

Java

private MutateOperation createAdGroupAdOperation(
    long customerId, SmartCampaignAdInfo adSuggestions) {
  MutateOperation.Builder opBuilder = MutateOperation.newBuilder();

  // Constructs an Ad instance containing a SmartCampaignAd.
  Ad.Builder adBuilder = Ad.newBuilder();
  adBuilder
      .setType(AdType.SMART_CAMPAIGN_AD)
      // The SmartCampaignAdInfo object includes headlines and descriptions retrieved
      // from the suggestSmartCampaignAd method. It's recommended that users review and approve or
      // update these creatives before they're set on the ad. It's possible that some or all of
      // these assets may contain empty texts, which should not be set on the ad and instead
      // should be replaced with meaningful texts from the user. Below we just accept the
      // creatives that were suggested while filtering out empty assets, but individual workflows
      // will vary here.
      .getSmartCampaignAdBuilder()
      .addAllHeadlines(
          adSuggestions.getHeadlinesList().stream()
              .filter(h -> h.hasText())
              .collect(Collectors.toList()))
      .addAllDescriptions(
          adSuggestions.getDescriptionsList().stream()
              .filter(d -> d.hasText())
              .collect(Collectors.toList()));

  opBuilder
      .getAdGroupAdOperationBuilder()
      .getCreateBuilder()
      .setAdGroup(ResourceNames.adGroup(customerId, AD_GROUP_TEMPORARY_ID))
      .setAd(adBuilder);
  return opBuilder.build();
}
      
      

C#

/// <summary>
/// Creates a MutateOperation that creates a new ad group ad.
/// A temporary ID will be used in the ad group resource name for this ad group ad to
/// associate it with the ad group created in earlier steps.
/// </summary>
/// <param name="customerId">The Google Ads customer ID.</param>
/// <param name="adSuggestions">SmartCampaignAdInfo with ad creative
/// suggestions.</param>
/// <returns>A MutateOperation that creates a new ad group ad.</returns>
private MutateOperation CreateAdGroupAdOperation(long customerId, SmartCampaignAdInfo
    adSuggestions)
{
    AdGroupAd adGroupAd = new AdGroupAd
    {
        AdGroup = ResourceNames.AdGroup(customerId, AD_GROUP_TEMPORARY_ID),
        Ad = new Ad
        {
            SmartCampaignAd = new SmartCampaignAdInfo(),
        },
    };

    SmartCampaignAdInfo ad = adGroupAd.Ad.SmartCampaignAd;

    // The SmartCampaignAdInfo object includes headlines and descriptions
    // retrieved from the SmartCampaignSuggestService.SuggestSmartCampaignAd
    // method. It's recommended that users review and approve or update these
    // creatives before they're set on the ad. It's possible that some or all of
    // these assets may contain empty texts, which should not be set on the ad
    // and instead should be replaced with meaninful texts from the user. Below
    // we just accept the creatives that were suggested while filtering out empty
    // assets, but individual workflows will vary here.
    ad.Headlines.Add(adSuggestions.Headlines);
    ad.Descriptions.Add(adSuggestions.Descriptions);

    return new MutateOperation
    {
        AdGroupAdOperation = new AdGroupAdOperation
        {
            Create = adGroupAd
        }
    };
}
      
      

PHP

private static function createAdGroupAdOperation(
    int $customerId,
    $adSuggestions
): MutateOperation {
    // Creates the ad group ad object.
    $adGroupAd = new AdGroupAd([
        // Sets the ad group ID to a temporary ID.
        'ad_group' => ResourceNames::forAdGroup($customerId, self::AD_GROUP_TEMPORARY_ID),
        'ad' => new Ad([
            // Sets the type to SMART_CAMPAIGN_AD.
            'type' => AdType::SMART_CAMPAIGN_AD,
            // The SmartCampaignAdInfo object includes headlines and descriptions retrieved
            // from the SmartCampaignSuggestService::SuggestSmartCampaignAd method. It's
            // recommended that users review and approve or update these creatives before
            // they're set on the ad. It's possible that some or all of these assets may
            // contain empty texts, which should not be set on the ad and instead should be
            // replaced with meaningful texts from the user. Below we just accept the creatives
            // that were suggested while filtering out empty assets, but individual workflows
            // will vary here.
            'smart_campaign_ad' => new SmartCampaignAdInfo([
                'headlines' => array_filter(
                    iterator_to_array($adSuggestions->getHeadlines()->getIterator()),
                    function ($value) {
                        return $value->getText();
                    }
                ),
                'descriptions' => array_filter(
                    iterator_to_array($adSuggestions->getDescriptions()->getIterator()),
                    function ($value) {
                        return $value->getText();
                    }
                )
            ])
        ])
    ]);

    // Creates the MutateOperation that creates the ad group ad.
    return new MutateOperation([
        'ad_group_ad_operation' => new AdGroupAdOperation(['create' => $adGroupAd])
    ]);
}
      
      

Python

def _create_ad_group_ad_operation(client, customer_id, ad_suggestions):
    """Creates a MutateOperation that creates a new ad group ad.

    A temporary ID will be used in the ad group resource name for this
    ad group ad to associate it with the ad group created in earlier steps.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        ad_suggestions: a SmartCampaignAdInfo object with ad creative
            suggestions.

    Returns:
        a MutateOperation that creates a new ad group ad.
    """
    mutate_operation = client.get_type("MutateOperation")
    ad_group_ad = mutate_operation.ad_group_ad_operation.create
    # Set the ad group ID to a temporary ID.
    ad_group_ad.ad_group = client.get_service("AdGroupService").ad_group_path(
        customer_id, _AD_GROUP_TEMPORARY_ID
    )
    # Set the type to SMART_CAMPAIGN_AD.
    ad_group_ad.ad.type_ = client.enums.AdTypeEnum.SMART_CAMPAIGN_AD
    ad = ad_group_ad.ad.smart_campaign_ad

    # The SmartCampaignAdInfo object includes headlines and descriptions
    # retrieved from the SmartCampaignSuggestService.SuggestSmartCampaignAd
    # method. It's recommended that users review and approve or update these
    # creatives before they're set on the ad. It's possible that some or all of
    # these assets may contain empty texts, which should not be set on the ad
    # and instead should be replaced with meaninful texts from the user. Below
    # we just accept the creatives that were suggested while filtering out empty
    # assets, but individual workflows will vary here.
    ad.headlines = [asset for asset in ad_suggestions.headlines if asset.text]
    ad.descriptions = [
        asset for asset in ad_suggestions.descriptions if asset.text
    ]

    return mutate_operation
      
      

Ruby

# Creates a mutate_operation that creates a new ad group ad.
# A temporary ID will be used in the ad group resource name for this
# ad group ad to associate it with the ad group created in earlier steps.
def create_ad_group_ad_operation(client, customer_id, ad_suggestions)
  mutate_operation = client.operation.mutate do |m|
    m.ad_group_ad_operation = client.operation.create_resource.ad_group_ad do |aga|
      # Set the ad group ID to a temporary ID.
      aga.ad_group = client.path.ad_group(customer_id, AD_GROUP_TEMPORARY_ID)
      aga.ad = client.resource.ad do |ad|
        # Set the type to SMART_CAMPAIGN_AD.
        ad.type = :SMART_CAMPAIGN_AD
        ad.smart_campaign_ad = client.resource.smart_campaign_ad_info do |sca|
          # The SmartCampaignAdInfo object includes headlines and descriptions
          # retrieved from the SmartCampaignSuggestService.SuggestSmartCampaignAd
          # method. It's recommended that users review and approve or update these
          # creatives before they're set on the ad. It's possible that some or all of
          # these assets may contain empty texts, which should not be set on the ad
          # and instead should be replaced with meaninful texts from the user. Below
          # we just accept the creatives that were suggested while filtering out empty
          # assets, but individual workflows will vary here.
          sca.headlines += ad_suggestions.headlines.filter(&:text)
          sca.descriptions += ad_suggestions.descriptions.filter(&:text)
        end
      end
    end
  end

  mutate_operation
end
      
      

Perl

# Creates a MutateOperation that creates a new ad group ad.
# A temporary ID will be used in the ad group resource name for this ad group
# ad to associate it with the ad group created in earlier steps.
sub _create_ad_group_ad_operation {
  my ($customer_id, $ad_suggestions) = @_;

  my $mutate_operation =
    Google::Ads::GoogleAds::V8::Services::GoogleAdsService::MutateOperation->
    new({
      adGroupAdOperation =>
        Google::Ads::GoogleAds::V8::Services::AdGroupAdService::AdGroupAdOperation
        ->new({
          create => Google::Ads::GoogleAds::V8::Resources::AdGroupAd->new({
              adGroup =>
                # Set the ad group ID to a temporary ID.
                Google::Ads::GoogleAds::V8::Utils::ResourceNames::ad_group(
                $customer_id, AD_GROUP_TEMPORARY_ID
                ),
              ad => Google::Ads::GoogleAds::V8::Resources::Ad->new({
                  # Set the type to SMART_CAMPAIGN_AD.
                  type            => SMART_CAMPAIGN_AD,
                  smartCampaignAd =>
                    Google::Ads::GoogleAds::V8::Common::SmartCampaignAdInfo->
                    new(
                    )})})})});

  # The SmartCampaignAdInfo object includes headlines and descriptions
  # retrieved from the SmartCampaignSuggestService.SuggestSmartCampaignAd
  # method. It's recommended that users review and approve or update these
  # creatives before they're set on the ad. It's possible that some or all of
  # these assets may contain empty texts, which should not be set on the ad
  # and instead should be replaced with meaninful texts from the user. Below
  # we just accept the creatives that were suggested while filtering out empty
  # assets, but individual workflows will vary here.
  foreach my $asset (@{$ad_suggestions->{headlines}}) {
    push @{$mutate_operation->{adGroupAdOperation}{create}{ad}{smartCampaignAd}
        {headlines}}, $asset
      if defined $asset->{text};
  }
  foreach my $asset (@{$ad_suggestions->{descriptions}}) {
    push @{$mutate_operation->{adGroupAdOperation}{create}{ad}{smartCampaignAd}
        {descriptions}}, $asset
      if defined $asset->{text};
  }

  return $mutate_operation;
}