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(BytesValue.of(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(StringValue.of("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());
  }
}

.NET

public void Run(GoogleAdsClient client, long customerId)

PHP

public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)

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='v3')
    asset = asset_operation.create
    asset.type = client.get_type('AssetTypeEnum', version='v3').IMAGE
    asset.image_asset.data.value = image_content
    asset.image_asset.file_size.value = 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.value = 315
    asset.image_asset.full_size.width_pixels.value = 600
    asset.image_asset.full_size.url.value = 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='v3')

    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)

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::V3::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::V3::Common::ImageAsset->new({
          data => $image_content
        })});

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

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

  printf "The image asset with resource name '%s' was created.\n",
    $asset_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(StringValue.of(marketingImageResourceName))
                  .build())
          .addSquareMarketingImages(
              AdImageAsset.newBuilder()
                  .setAsset(StringValue.of(squareMarketingImageResourceName))
                  .build())
          .addHeadlines(AdTextAsset.newBuilder().setText(StringValue.of("Travel")).build())
          .setLongHeadline(
              AdTextAsset.newBuilder().setText(StringValue.of("Travel the World")).build())
          .addDescriptions(
              AdTextAsset.newBuilder().setText(StringValue.of("Take to the air!")).build())
          .setBusinessName(StringValue.of("Interplanetary Cruises"))
          // Optional: Call to action text.
          // Valid texts: https://support.google.com/adwords/answer/7005917
          .setCallToActionText(StringValue.of("Apply Now"))
          // Optional: Sets the ad colors.
          .setMainColor(StringValue.of("#0000ff"))
          .setAccentColor(StringValue.of("#ffff00"))
          // Optional: Sets to false to strictly render the ad using the colors.
          .setAllowFlexibleColor(BoolValue.of(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(StringValue.of("http://www.example.com/"))
          .build();

  // Creates the ad group ad.
  AdGroupAd adGroupAd =
      AdGroupAd.newBuilder().setAdGroup(StringValue.of(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());
  }
}