Creating Responsive Search Ads

Below you can see code examples showing how to create responsive search ads. As with other ads, ad creation is accomplished using AdGroupAdService.MutateAdGroupAds . A ResponsiveSearchAdInfo requires at least three headlines, at least two descriptions, and at least one final URL.

Java

// 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
//
//     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.basicoperations;

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.v3.common.AdTextAsset;
import com.google.ads.googleads.v3.common.ResponsiveSearchAdInfo;
import com.google.ads.googleads.v3.enums.AdGroupAdStatusEnum.AdGroupAdStatus;
import com.google.ads.googleads.v3.enums.ServedAssetFieldTypeEnum.ServedAssetFieldType;
import com.google.ads.googleads.v3.errors.GoogleAdsError;
import com.google.ads.googleads.v3.errors.GoogleAdsException;
import com.google.ads.googleads.v3.resources.Ad;
import com.google.ads.googleads.v3.resources.AdGroupAd;
import com.google.ads.googleads.v3.services.AdGroupAdOperation;
import com.google.ads.googleads.v3.services.AdGroupAdServiceClient;
import com.google.ads.googleads.v3.services.MutateAdGroupAdResult;
import com.google.ads.googleads.v3.services.MutateAdGroupAdsResponse;
import com.google.ads.googleads.v3.utils.ResourceNames;
import com.google.common.collect.ImmutableList;
import com.google.protobuf.StringValue;
import java.io.FileNotFoundException;
import java.io.IOException;

/** Adds a responsive search ad to a given ad group. To get ad groups, run GetAdGroups.java. */
public class AddResponsiveSearchAd {

  private static class AddResponsiveSearchAdParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    private Long customerId;

    @Parameter(names = ArgumentNames.AD_GROUP_ID, required = true)
    private Long adGroupId;
  }

  public static void main(String[] args) {
    AddResponsiveSearchAdParams params = new AddResponsiveSearchAdParams();
    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.adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE");
    }

    GoogleAdsClient googleAdsClient;
    try {
      googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
    } catch (FileNotFoundException fnfe) {
      System.err.printf(
          "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
      return;
    } catch (IOException ioe) {
      System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
      return;
    }

    try {
      new AddResponsiveSearchAd().runExample(googleAdsClient, params.customerId, params.adGroupId);
    } 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);
      }
    }
  }

  /**
   * Runs the example.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param adGroupId the ad group ID.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private void runExample(GoogleAdsClient googleAdsClient, long customerId, long adGroupId) {
    String adGroupResourceName = ResourceNames.adGroup(customerId, adGroupId);

    // Sets a pinning to always choose this asset for HEADLINE_1. Pinning is optional; if no
    // pinning is set, then headlines and descriptions will be rotated and the ones that
    // perform best will be used more often.
    AdTextAsset pinnedHeadline =
        AdTextAsset.newBuilder()
            .setText(StringValue.of("Cruise to Mars #" + System.currentTimeMillis()))
            .setPinnedField(ServedAssetFieldType.HEADLINE_1)
            .build();

    // Creates the responsive search ad info.
    ResponsiveSearchAdInfo responsiveSearchAdInfo =
        ResponsiveSearchAdInfo.newBuilder()
            .addHeadlines(pinnedHeadline)
            .addHeadlines(createAdTextAsset("Best Space Cruise Line"))
            .addHeadlines(createAdTextAsset("Experience the Stars"))
            .addDescriptions(createAdTextAsset("Buy your tickets now"))
            .addDescriptions(createAdTextAsset("Visit the Red Planet"))
            .setPath1(StringValue.of("all-inclusive"))
            .setPath2(StringValue.of("deals"))
            .build();

    // Wraps the info in an Ad object.
    Ad ad =
        Ad.newBuilder()
            .setResponsiveSearchAd(responsiveSearchAdInfo)
            .addFinalUrls(StringValue.of("http://www.example.com"))
            .build();

    // Builds the final ad group ad representation.
    AdGroupAd adGroupAd =
        AdGroupAd.newBuilder()
            .setAdGroup(StringValue.of(adGroupResourceName))
            .setStatus(AdGroupAdStatus.PAUSED)
            .setAd(ad)
            .build();

    // Creates the operation.
    AdGroupAdOperation operation = AdGroupAdOperation.newBuilder().setCreate(adGroupAd).build();

    // Creates the AdGroupAdServiceClient.
    try (AdGroupAdServiceClient adGroupAdServiceClient =
        googleAdsClient.getLatestVersion().createAdGroupAdServiceClient()) {
      // Adds the AdGroup.
      MutateAdGroupAdsResponse response =
          adGroupAdServiceClient.mutateAdGroupAds(
              Long.toString(customerId), ImmutableList.of(operation));
      for (MutateAdGroupAdResult result : response.getResultsList()) {
        System.out.printf(
            "Responsive search ad created with resource name: %s.%n", result.getResourceName());
      }
    }
  }

  /**
   * Creates an AdTextAsset from a given string.
   *
   * @param text the text string to insert in the AdTextAsset.
   * @return AdTextAsset.
   */
  private AdTextAsset createAdTextAsset(String text) {
    return AdTextAsset.newBuilder().setText(StringValue.of(text)).build();
  }
}

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2020 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 a responsive search ad to an ad group.

require 'optparse'
require 'google/ads/google_ads'

def add_responsive_search_ad(customer_id, ad_group_id)
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  responsive_ad_info = client.resource.responsive_search_ad_info do |responsive_ad|
    responsive_ad.headlines << client.resource.ad_text_asset do |ata|
      ata.text = "Best Space Cruise Line"
    end

    responsive_ad.headlines << client.resource.ad_text_asset do |ata|
      ata.text = "Experience the Stars"
    end

    responsive_ad.headlines << client.resource.ad_text_asset do |ata|
      ata.text = "Explore the Galaxy"
    end

    responsive_ad.descriptions << client.resource.ad_text_asset do |ata|
      ata.text = "Buy your tickets now"
    end

    responsive_ad.descriptions << client.resource.ad_text_asset do |ata|
      ata.text = "Visit the Red Planet"
    end

    responsive_ad.path1 = "all-inclusive"
    responsive_ad.path2 = "deals"
  end

  ad = client.resource.ad do |ad|
    ad.final_urls << "http://www.example.com"
    ad.responsive_search_ad = responsive_ad_info
  end

  ad_group_ad = client.resource.ad_group_ad do |aga|
    aga.ad = ad
    aga.status = :PAUSED
    aga.ad_group = client.path.ad_group(customer_id, ad_group_id)
  end

  op = client.operation.create_resource.ad_group_ad(ad_group_ad)

  response = client.service.ad_group_ad.mutate_ad_group_ads(customer_id, [op])
  puts "Created Responsive Search Ad with ID #{response.results.first.resource_name}."
end

if __FILE__ == $0
  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_CUSTOMER_ID_HERE'
  options[:ad_group_id] = 'INSERT_AD_GROUP_ID_HERE'

  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: %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('-A', '--ad-group-id AD-GROUP-ID', String, 'Ad Group ID') do |v|
      options[:ad_group_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_responsive_search_ad(
      options.fetch(:customer_id).tr("-", ""),
      options.fetch(:ad_group_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
  rescue Google::Gax::RetryError => e
    STDERR.printf("Error: '%s'\n\tCause: '%s'\n\tCode: %d\n\tDetails: '%s'\n" \
        "\tRequest-Id: '%s'\n", e.message, e.cause.message, e.cause.code,
                  e.cause.details, e.cause.metadata['request-id'])
    raise
  end
end