Working with Assets

Creating assets

Most asset types must be created using the AssetService before they are used in an ad. TextAssets are the exception and are created inline during ad creation. But all other types must first be uploaded to an advertiser’s account before they can be used.

The following example shows how to create a new image asset from a URL of raw image data.

Java

private void runExample(GoogleAdsClient googleAdsClient, long customerId) throws IOException {
  byte[] imageData = ByteStreams.toByteArray(new URL(IMAGE_URL).openStream());

  // Create the image asset.
  ImageAsset imageAsset = ImageAsset.newBuilder().setData(ByteString.copyFrom(imageData)).build();

  // Creates an asset.
  Asset asset =
      Asset.newBuilder()
          // Optional: Provide a unique friendly name to identify your asset.
          // If you specify the name field, then both the asset name and the image being
          // uploaded should be unique, and should not match another ACTIVE asset in this
          // customer account.
          // .setName("Jupiter Trip # " + System.currentTimeMillis())
          .setType(AssetType.IMAGE)
          .setImageAsset(imageAsset)
          .build();

  // Creates the operation.
  AssetOperation operation = AssetOperation.newBuilder().setCreate(asset).build();

  // Creates the service client.
  try (AssetServiceClient assetServiceClient =
      googleAdsClient.getLatestVersion().createAssetServiceClient()) {
    // Issues a mutate request to add the asset.
    MutateAssetsResponse response =
        assetServiceClient.mutateAssets(Long.toString(customerId), ImmutableList.of(operation));
    // Prints the result.
    System.out.printf(
        "The image asset with resource name '%s' was created.%n",
        response.getResults(0).getResourceName());
  }
}

C#

public void Run(GoogleAdsClient client, long customerId)
{
    // Get the AssetServiceClient.
    AssetServiceClient assetService =
        client.GetService(Services.V6.AssetService);

    // Creates an image content.
    byte[] imageContent = MediaUtilities.GetAssetDataFromUrl(IMAGE_URL, client.Config);

    // Creates an image asset.
    ImageAsset imageAsset = new ImageAsset()
    {
        Data = ByteString.CopyFrom(imageContent),
        FileSize = imageContent.Length,
        MimeType = MimeType.ImageJpeg,
        FullSize = new ImageDimension()
        {
            HeightPixels = 315,
            WidthPixels = 600,
            Url = IMAGE_URL
        }
    };

    // Creates an asset.
    Asset asset = new Asset()
    {
        // Optional: Provide a unique friendly name to identify your asset.
        // If you specify the name field, then both the asset name and the image being
        // uploaded should be unique, and should not match another ACTIVE asset in this
        // customer account.
        // Name = 'Jupiter Trip #' + ExampleUtilities.GetRandomString(),
        Type = AssetType.Image,
        ImageAsset = imageAsset
    };

    // Creates an asset operation.
    AssetOperation operation = new AssetOperation()
    {
        Create = asset
    };

    try
    {
        // Issues a mutate request to add the asset.
        MutateAssetsResponse response =
            assetService.MutateAssets(customerId.ToString(), new[] { operation });

        // Displays the result.
        Console.WriteLine($"Image asset with resource name: " +
            $"'{response.Results.First().ResourceName}' is created.");
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
        throw;
    }
}

PHP

public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
{
    // Creates an image content.
    $imageContent = file_get_contents(self::IMAGE_URL);

    // Creates an asset.
    $asset = new Asset([
        // Optional: Provide a unique friendly name to identify your asset.
        // If you specify the name field, then both the asset name and the image being
        // uploaded should be unique, and should not match another ACTIVE asset in this
        // customer account.
        // 'name' => 'Jupiter Trip #' . uniqid(),
        'type' => AssetType::IMAGE,
        'image_asset' => new ImageAsset(['data' => $imageContent])
    ]);

    // Creates an asset operation.
    $assetOperation = new AssetOperation();
    $assetOperation->setCreate($asset);

    // Issues a mutate request to add the asset.
    $assetServiceClient = $googleAdsClient->getAssetServiceClient();
    $response = $assetServiceClient->mutateAssets(
        $customerId,
        [$assetOperation]
    );

    if (!empty($response->getResults())) {
        // Prints the resource name of the added image asset.
        /** @var MutateAssetResult $addedImageAsset */
        $addedImageAsset = $response->getResults()[0];
        printf(
            "The image asset with resource name '%s' was created.%s",
            $addedImageAsset->getResourceName(),
            PHP_EOL
        );
    } else {
        print 'No image asset was created.' . PHP_EOL;
    }
}

Python

def main(client, customer_id):
    """Main method, to run this code example as a standalone application."""

    # Download image from URL
    URL = "https://goo.gl/3b9Wfh"
    image_content = requests.get(URL).content

    asset_operation = client.get_type("AssetOperation", version="v6")
    asset = asset_operation.create
    asset.type = client.get_type("AssetTypeEnum", version="v6").IMAGE
    asset.image_asset.data = image_content
    asset.image_asset.file_size = len(image_content)
    asset.image_asset.mime_type = client.get_type("MimeTypeEnum").IMAGE_JPEG
    # Use your favorite image library to determine dimensions
    asset.image_asset.full_size.height_pixels = 315
    asset.image_asset.full_size.width_pixels = 600
    asset.image_asset.full_size.url = URL
    # Optional: Provide a unique friendly name to identify your asset.
    # If you specify the name field, then both the asset name and the image
    # being uploaded should be unique, and should not match another ACTIVE
    # asset in this customer account.
    # asset.name = 'Jupiter Trip #' + uuid.uuid4()

    asset_service = client.get_service("AssetService", version="v6")

    try:
        mutate_asset_response = asset_service.mutate_assets(
            customer_id, [asset_operation]
        )
        print("Uploaded file(s):")
        for row in mutate_asset_response.results:
            print(f"\tResource name: {row.resource_name}")

    except GoogleAdsException as ex:
        print(
            f'Request with ID "{ex.request_id}" failed with status '
            f'"{ex.error.code().name}" and includes the following errors:'
        )
        for error in ex.failure.errors:
            print(f'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)

Ruby

def upload_image_asset(customer_id)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  url = 'https://goo.gl/3b9Wfh'
  image_data = open(url) { |f| f.read }

  # Create the operation for uploading the image asset.
  asset_operation = client.operation.create_resource.asset do |asset|
    asset.type = :IMAGE
    asset.image_asset = client.resource.image_asset do |image_asset|
      image_asset.data = image_data
      image_asset.file_size = image_data.length()
      image_asset.mime_type = :IMAGE_JPEG
      image_asset.full_size = client.resource.image_dimension do |dimension|
        dimension.height_pixels = 315
        dimension.width_pixels = 600
        dimension.url = url
      end
      # Optional: Provide a unique friendly name to identify your asset.
      # If you specify the name field, then both the asset name and the image
      # being uploaded should be unique, and should not match another ACTIVE
      # asset in this customer account.
      # image_asset.name = 'Jupiter Trip #' + SecureRandom.uuid
    end
  end

  # Upload the image asset.
  response = client.service.asset.mutate_assets(
    customer_id: customer_id,
    operations: [asset_operation],
  )

  puts "Uploaded image asset #{response.results.first.resource_name}."
end

Perl

sub upload_image_asset {
  my ($api_client, $customer_id) = @_;

  # Create an image content.
  my $image_content = get_base64_data_from_url(IMAGE_URL);

  # Create an asset.
  my $asset = Google::Ads::GoogleAds::V6::Resources::Asset->new({
      # Optional: Provide a unique friendly name to identify your asset.
      # If you specify the name field, then both the asset name and the image being
      # uploaded should be unique, and should not match another ACTIVE asset in this
      # customer account.
      # name       => "Jupiter Trip #" . uniqid(),
      type       => IMAGE,
      imageAsset => Google::Ads::GoogleAds::V6::Common::ImageAsset->new({
          data => $image_content
        })});

  # Create an asset operation.
  my $asset_operation =
    Google::Ads::GoogleAds::V6::Services::AssetService::AssetOperation->new({
      create => $asset
    });

  # Issue a mutate request to add the asset.
  my $assets_response = $api_client->AssetService()->mutate({
      customerId => $customer_id,
      operations => [$asset_operation]});

  printf "The image asset with resource name '%s' was created.\n",
    $assets_response->{results}[0]{resourceName};

  return 1;
}

After the asset has been created, the API returns a MutateAssetResult object that contains the resource name of the new ImageAsset. This resource name is used to reference the ImageAsset when creating an asset-based ad.

You can retrieve a list existing assets and their resource names by querying the GoogleAdsService. See the Fetching Asset Attribute and Metrics section for more details.

Using assets in ads

Assets are supported by the following ad types, according to the table below.

Ads types and the asset types they support:
AppAd
TextAsset
ImageAsset
VideoAsset
MediaBundleAsset
AppEngagementAd TextAsset
ImageAsset
VideoAsset
DisplayUploadAd MediaBundleAsset
ResponsiveDisplayAd TextAsset
ImageAsset
VideoAsset
ResponsiveSearchAd TextAsset

Each of the above ad types has fields for setting the various asset types that it supports. For TextAsset types, a new string asset is created inline within the Ad. For all other types, existing asset are added to the Ad by referencing their resource names.

The example below demonstrates adding TextAssets and ImageAssets to create a ResponsiveDisplayAd. The TextAssets are created inline as the ad’s headlines and description. The ImageAsset are specified by resource name as the ad’s logo images.

Java

private void createAd(
    GoogleAdsClient googleAdsClient, long customerId, String adGroupResourceName)
    throws IOException {
  String marketingImageUrl = "https://goo.gl/3b9Wfh";
  String marketingImageName = "Marketing Image";
  String marketingImageResourceName =
      uploadAsset(googleAdsClient, customerId, marketingImageUrl, marketingImageName);
  String squareMarketingImageName = "Square Marketing Image";
  String squareMarketingImageUrl = "https://goo.gl/mtt54n";
  String squareMarketingImageResourceName =
      uploadAsset(googleAdsClient, customerId, squareMarketingImageUrl, squareMarketingImageName);

  // Creates the responsive display ad info object.
  ResponsiveDisplayAdInfo responsiveDisplayAdInfo =
      ResponsiveDisplayAdInfo.newBuilder()
          .addMarketingImages(
              AdImageAsset.newBuilder().setAsset(marketingImageResourceName).build())
          .addSquareMarketingImages(
              AdImageAsset.newBuilder().setAsset(squareMarketingImageResourceName).build())
          .addHeadlines(AdTextAsset.newBuilder().setText("Travel").build())
          .setLongHeadline(AdTextAsset.newBuilder().setText("Travel the World").build())
          .addDescriptions(AdTextAsset.newBuilder().setText("Take to the air!").build())
          .setBusinessName("Interplanetary Cruises")
          // Optional: Call to action text.
          // Valid texts: https://support.google.com/adwords/answer/7005917
          .setCallToActionText("Apply Now")
          // Optional: Sets the ad colors.
          .setMainColor("#0000ff")
          .setAccentColor("#ffff00")
          // Optional: Sets to false to strictly render the ad using the colors.
          .setAllowFlexibleColor(false)
          // Optional: Sets the format setting that the ad will be served in.
          .setFormatSetting(DisplayAdFormatSetting.NON_NATIVE)
          // Optional: Creates a logo image and sets it to the ad.
          /*
          .addLogoImages(
              AdImageAsset.newBuilder()
                  .setAsset(StringValue.of("INSERT_LOGO_IMAGE_RESOURCE_NAME_HERE"))
                  .build())
          */
          // Optional: Creates a square logo image and sets it to the ad.
          /*
          .addSquareLogoImages(
              AdImageAsset.newBuilder()
                  .setAsset(StringValue.of("INSERT_SQUARE_LOGO_IMAGE_RESOURCE_NAME_HERE"))
                  .build())
          */
          .build();

  // Creates the ad.
  Ad ad =
      Ad.newBuilder()
          .setResponsiveDisplayAd(responsiveDisplayAdInfo)
          .addFinalUrls("http://www.example.com/")
          .build();

  // Creates the ad group ad.
  AdGroupAd adGroupAd = AdGroupAd.newBuilder().setAdGroup(adGroupResourceName).setAd(ad).build();

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

  // Creates the ad group ad service client.
  try (AdGroupAdServiceClient adGroupAdServiceClient =
      googleAdsClient.getLatestVersion().createAdGroupAdServiceClient()) {
    // Adds the ad group ad.
    MutateAdGroupAdsResponse response =
        adGroupAdServiceClient.mutateAdGroupAds(
            Long.toString(customerId), ImmutableList.of(operation));
    System.out.printf(
        "Created ad group ad with resource name '%s'.%n",
        response.getResults(0).getResourceName());
  }
}

C#

public void Run(GoogleAdsClient client, long customerId, long merchantCenterAccountId,
    long campaignBudgetId, long userListId)
{
    try
    {
        // Creates a shopping campaign associated with a given Merchant Center account.
        string campaignResourceName = CreateCampaign(client, customerId,
            merchantCenterAccountId, campaignBudgetId);

        // Creates an ad group for the campaign.
        string adGroupResourceName = CreateAdGroup(client, customerId,
            campaignResourceName);

        // Creates a responsive display ad in the ad group.
        CreateAd(client, customerId, adGroupResourceName);

        // Targets a specific user list for remarketing.
        AttachUserList(client, customerId, adGroupResourceName, userListId);
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
        throw;
    }
}

PHP

public static function runExample(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    int $merchantCenterAccountId,
    int $campaignBudgetId,
    int $userListId
) {
    // Creates a shopping campaign associated with a given merchant center account.
    $campaignResourceName = self::createCampaign(
        $googleAdsClient,
        $customerId,
        $merchantCenterAccountId,
        $campaignBudgetId
    );

    // Creates an ad group for the campaign.
    $adGroupResourceName =
        self::createAdGroup($googleAdsClient, $customerId, $campaignResourceName);

    // Creates a dynamic display ad in the ad group.
    self::createAd($googleAdsClient, $customerId, $adGroupResourceName);

    // Targets a specific user list for remarketing.
    self::attachUserList($googleAdsClient, $customerId, $adGroupResourceName, $userListId);
}

Python

def main(
    client,
    customer_id,
    merchant_center_account_id,
    campaign_budget_id,
    user_list_id,

Ruby

def add_merchant_center_dynamic_remarketing_campaign(
  customer_id,
  merchant_center_id,
  campaign_budget_id,
  user_list_id
)
  # GoogleAdsClient will read a config file from
  # ENV["HOME"]/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  # Creates a shopping campaign associated with a given merchant center account.
  campaign_resource_name = create_campaign(
    client,
    customer_id,
    merchant_center_id,
    campaign_budget_id
  )

  # Creates an ad group for the campaign.
  ad_group_resource_name = create_ad_group(client, customer_id,
                                           campaign_resource_name)

  # Creates a dynamic display ad in the ad group.
  create_ad(client, customer_id, ad_group_resource_name)

  # Targets a specific user list for remarketing.
  attach_user_list(client, customer_id, ad_group_resource_name, user_list_id)
end

Perl

sub add_merchant_center_dynamic_remarketing_campaign {
  my ($api_client, $customer_id, $merchant_center_account_id,
    $campaign_budget_id, $user_list_id)
    = @_;

  # Create a shopping campaign associated with a given Merchant Center account.
  my $campaign_resource_name =
    create_campaign($api_client, $customer_id, $merchant_center_account_id,
    $campaign_budget_id);

  # Create an ad group for the campaign.
  my $ad_group_resource_name =
    create_ad_group($api_client, $customer_id, $campaign_resource_name);

  # Create a dynamic display ad in the ad group.
  create_ad($api_client, $customer_id, $ad_group_resource_name);

  # Target a specific user list for remarketing.
  attach_user_list($api_client, $customer_id, $ad_group_resource_name,
    $user_list_id);

  return 1;
}