This page outlines how to perform some of the most common trafficking tasks using the DCM/DFA Reporting and Trafficking API.

## General coding tips

- **Required and optional properties and parameters** - See the [reference documentation](https://developers.google.com/doubleclick-advertisers/current) to find out whether a property or parameter is required for an API call.
- **Wildcard name searches** - You can use the asterisk (\*) wildcard when [searching on names for objects](https://developers.google.com/doubleclick-advertisers/trafficking_tasks#list). An asterisk matches zero or more of any character. The API also supports an implied substring search, so a search for "abc" will implicitly search for "\*abc\*".
- **Updating vs. patching** - To modify an existing object, you have two options:
  1. **Updating** - When updating an object, all fields will be overwritten on insert. It's important to load the object you'd like to update and make any changes to that object. Otherwise, any fields that are not present in the update request will be unset.
  2. **Patching** - When patching, only the fields specified will be overwritten on insert. In this case, you can create a new object, assign it the same ID as the object to update, set the fields to be updated, and execute the patch request.
- **Sizes** - Physical dimensions are represented by a `Size` object defined by the [sizes service](https://developers.google.com/doubleclick-advertisers/current/sizes). The account supplies a set of standard sizes, and you can add your own custom sizes to this list.
- **Dates and times** - You can save dates/times in [RFC 3339 format](https://www.ietf.org/rfc/rfc3339.txt) using local time zones; all values returned by the API are in UTC. This differs from the website where dates and times are shown in your configured timezone (America/New York time, by default).

## Create an advertiser

### C#

1. Create an `https://developers.google.com/doubleclick-advertisers/current/advertisers` object and set it's required [name](https://developers.google.com/doubleclick-advertisers/current/advertisers#name) and [status](https://developers.google.com/doubleclick-advertisers/current/advertisers#status) properties.

   ```c#
   // Create the advertiser structure.
   Advertiser advertiser = new Advertiser();
   advertiser.Name = advertiserName;
   advertiser.Status = "APPROVED";
   ```
2. Call `https://developers.google.com/doubleclick-advertisers/current/advertisers/insert` to save the advertiser.

   ```c#
   // Create the advertiser.
   Advertiser result = service.Advertisers.Insert(advertiser, profileId).Execute();
   ```

### Java

1. Create an `https://developers.google.com/doubleclick-advertisers/current/advertisers` object and set it's required [name](https://developers.google.com/doubleclick-advertisers/current/advertisers#name) and [status](https://developers.google.com/doubleclick-advertisers/current/advertisers#status) properties.

   ```java
   // Create the advertiser structure.
   Advertiser advertiser = new Advertiser();
   advertiser.setName(advertiserName);
   advertiser.setStatus("APPROVED");
   ```
2. Call `https://developers.google.com/doubleclick-advertisers/current/advertisers/insert` to save the advertiser.

   ```java
   // Create the advertiser.
   Advertiser result = reporting.advertisers().insert(profileId, advertiser).execute();
   ```

### PHP

1. Create an `https://developers.google.com/doubleclick-advertisers/current/advertisers` object and set it's required [name](https://developers.google.com/doubleclick-advertisers/current/advertisers#name) and [status](https://developers.google.com/doubleclick-advertisers/current/advertisers#status) properties.

   ```php
   $advertiser = new Google_Service_Dfareporting_Advertiser();
   $advertiser->setName($values['advertiser_name']);
   $advertiser->setStatus('APPROVED');
   ```
2. Call `https://developers.google.com/doubleclick-advertisers/current/advertisers/insert` to save the advertiser.

   ```php
   $result = $this->service->advertisers->insert(
       $values['user_profile_id'],
       $advertiser
   );
   ```

### Python

1. Create an `https://developers.google.com/doubleclick-advertisers/current/advertisers` object and set it's required [name](https://developers.google.com/doubleclick-advertisers/current/advertisers#name) and [status](https://developers.google.com/doubleclick-advertisers/current/advertisers#status) properties.

   ```python
   # Construct and save advertiser.
   advertiser = {
       'name': 'Test Advertiser',
       'status': 'APPROVED'
   }
   ```
2. Call `https://developers.google.com/doubleclick-advertisers/current/advertisers/insert` to save the advertiser.

   ```python
   request = service.advertisers().insert(
       profileId=str(profile_id), body=advertiser
   )

   # Execute request and print response.
   response = request.execute()
   ```

### Ruby

1. Create an `https://developers.google.com/doubleclick-advertisers/current/advertisers` object and set it's required [name](https://developers.google.com/doubleclick-advertisers/current/advertisers#name) and [status](https://developers.google.com/doubleclick-advertisers/current/advertisers#status) properties.

   ```ruby
   # Create a new advertiser resource to insert.
   advertiser = DfareportingUtils::API_NAMESPACE::Advertiser.new(
     name: format('Example Advertiser #%s', SecureRandom.hex(3)),
     status: 'APPROVED'
   )
   ```
2. Call `https://developers.google.com/doubleclick-advertisers/current/advertisers/insert` to save the advertiser.

   ```ruby
   # Insert the advertiser.
   result = service.insert_advertiser(profile_id, advertiser)
   ```

## Create a campaign

### C#

1.
   Create a `https://developers.google.com/doubleclick-advertisers/current/campaigns` object and set it's required properties:

   - `https://developers.google.com/doubleclick-advertisers/current/campaigns#advertiserId` - The advertiser with which to associate this campaign.
   - `https://developers.google.com/doubleclick-advertisers/current/campaigns#name` - This must be unique across all campaigns for this advertiser.
   - `https://developers.google.com/doubleclick-advertisers/current/campaigns#defaultLandingPageId` - A landing page to which users will be directed when they click on an ad in this campaign, if one isn't assigned to that ad. You can look up existing landing pages by calling `https://developers.google.com/doubleclick-advertisers/current/advertiserLandingPages/list` or create a new one by calling `https://developers.google.com/doubleclick-advertisers/current/advertiserLandingPages/insert`.
   - [Start](https://developers.google.com/doubleclick-advertisers/current/campaigns#startDate) and [end](https://developers.google.com/doubleclick-advertisers/current/campaigns#endDate) dates - These must be in the future, and can be accurate down to the day. See the dates and times bullet in [General coding information](https://developers.google.com/doubleclick-advertisers/trafficking_tasks#codingtips) for more details. Individual ad dates can exceed the end date, to enable a publisher to try to fulfill a contract for a specified number of actions, if it hasn't been filled by the given campaign end date.

   ```c#
   // Locate an advertiser landing page to use as a default.
   LandingPage defaultLandingPage = getAdvertiserLandingPage(service, profileId, advertiserId);

   // Create the campaign structure.
   Campaign campaign = new Campaign();
   campaign.Name = campaignName;
   campaign.AdvertiserId = advertiserId;
   campaign.Archived = false;
   campaign.DefaultLandingPageId = defaultLandingPage.Id;

   // Set the campaign start date. This example uses today's date.
   campaign.StartDate =
       DfaReportingDateConverterUtil.convertToDateString(DateTime.Now);

   // Set the campaign end date. This example uses one month from today's date.
   campaign.EndDate =
       DfaReportingDateConverterUtil.convertToDateString(DateTime.Now.AddMonths(1));

   campaign.EuPoliticalAdsDeclaration = "CONTAINS_EU_POLITICAL_ADS";
   ```
2.
   Call `https://developers.google.com/doubleclick-advertisers/current/campaigns/insert` to save the campaign.

   ```c#
   // Insert the campaign.
   Campaign result = service.Campaigns.Insert(campaign, profileId).Execute();
   ```

   <br />

### Java

1.
   Create a `https://developers.google.com/doubleclick-advertisers/current/campaigns` object and set it's required properties:

   - `https://developers.google.com/doubleclick-advertisers/current/campaigns#advertiserId` - The advertiser with which to associate this campaign.
   - `https://developers.google.com/doubleclick-advertisers/current/campaigns#name` - This must be unique across all campaigns for this advertiser.
   - `https://developers.google.com/doubleclick-advertisers/current/campaigns#defaultLandingPageId` - A landing page to which users will be directed when they click on an ad in this campaign, if one isn't assigned to that ad. You can look up existing landing pages by calling `https://developers.google.com/doubleclick-advertisers/current/advertiserLandingPages/list` or create a new one by calling `https://developers.google.com/doubleclick-advertisers/current/advertiserLandingPages/insert`.
   - [Start](https://developers.google.com/doubleclick-advertisers/current/campaigns#startDate) and [end](https://developers.google.com/doubleclick-advertisers/current/campaigns#endDate) dates - These must be in the future, and can be accurate down to the day. See the dates and times bullet in [General coding information](https://developers.google.com/doubleclick-advertisers/trafficking_tasks#codingtips) for more details. Individual ad dates can exceed the end date, to enable a publisher to try to fulfill a contract for a specified number of actions, if it hasn't been filled by the given campaign end date.

   ```java
   // Locate an advertiser landing page to use as a default.
   LandingPage defaultLandingPage = getAdvertiserLandingPage(reporting, profileId, advertiserId);

   // Create the campaign structure.
   Campaign campaign = new Campaign();
   campaign.setName(campaignName);
   campaign.setAdvertiserId(advertiserId);
   campaign.setArchived(false);
   campaign.setDefaultLandingPageId(defaultLandingPage.getId());
   campaign.setEuPoliticalAdsDeclaration("CONTAINS_EU_POLITICAL_ADS");

   // Set the campaign start date. This example uses today's date.
   Calendar today = Calendar.getInstance();
   DateTime startDate = new DateTime(true, today.getTimeInMillis(), null);
   campaign.setStartDate(startDate);

   // Set the campaign end date. This example uses one month from today's date.
   Calendar nextMonth = Calendar.getInstance();
   nextMonth.add(Calendar.MONTH, 1);
   DateTime endDate = new DateTime(true, nextMonth.getTimeInMillis(), null);
   campaign.setEndDate(endDate);
   ```
2.
   Call `https://developers.google.com/doubleclick-advertisers/current/campaigns/insert` to save the campaign.

   ```java
   // Insert the campaign.
   Campaign result = reporting.campaigns().insert(profileId, campaign).execute();
   ```

   <br />

### PHP

1.
   Create a `https://developers.google.com/doubleclick-advertisers/current/campaigns` object and set it's required properties:

   - `https://developers.google.com/doubleclick-advertisers/current/campaigns#advertiserId` - The advertiser with which to associate this campaign.
   - `https://developers.google.com/doubleclick-advertisers/current/campaigns#name` - This must be unique across all campaigns for this advertiser.
   - `https://developers.google.com/doubleclick-advertisers/current/campaigns#defaultLandingPageId` - A landing page to which users will be directed when they click on an ad in this campaign, if one isn't assigned to that ad. You can look up existing landing pages by calling `https://developers.google.com/doubleclick-advertisers/current/advertiserLandingPages/list` or create a new one by calling `https://developers.google.com/doubleclick-advertisers/current/advertiserLandingPages/insert`.
   - [Start](https://developers.google.com/doubleclick-advertisers/current/campaigns#startDate) and [end](https://developers.google.com/doubleclick-advertisers/current/campaigns#endDate) dates - These must be in the future, and can be accurate down to the day. See the dates and times bullet in [General coding information](https://developers.google.com/doubleclick-advertisers/trafficking_tasks#codingtips) for more details. Individual ad dates can exceed the end date, to enable a publisher to try to fulfill a contract for a specified number of actions, if it hasn't been filled by the given campaign end date.

   ```php
   $startDate = new DateTime('today');
   $endDate = new DateTime('+1 month');

   $campaign = new Google_Service_Dfareporting_Campaign();
   $campaign->setAdvertiserId($values['advertiser_id']);
   $campaign->setDefaultLandingPageId($values['default_landing_page_id']);
   $campaign->setName($values['campaign_name']);
   $campaign->setEuPoliticalAdsDeclaration($values['eu_political_ads_declaration']);
   $campaign->setStartDate($startDate->format('Y-m-d'));
   $campaign->setEndDate($endDate->format('Y-m-d'));
   ```
2.
   Call `https://developers.google.com/doubleclick-advertisers/current/campaigns/insert` to save the campaign.

   ```php
   $result = $this->service->campaigns->insert(
       $values['user_profile_id'],
       $campaign
   );
   ```

   <br />

### Python

1.
   Create a `https://developers.google.com/doubleclick-advertisers/current/campaigns` object and set it's required properties:

   - `https://developers.google.com/doubleclick-advertisers/current/campaigns#advertiserId` - The advertiser with which to associate this campaign.
   - `https://developers.google.com/doubleclick-advertisers/current/campaigns#name` - This must be unique across all campaigns for this advertiser.
   - `https://developers.google.com/doubleclick-advertisers/current/campaigns#defaultLandingPageId` - A landing page to which users will be directed when they click on an ad in this campaign, if one isn't assigned to that ad. You can look up existing landing pages by calling `https://developers.google.com/doubleclick-advertisers/current/advertiserLandingPages/list` or create a new one by calling `https://developers.google.com/doubleclick-advertisers/current/advertiserLandingPages/insert`.
   - [Start](https://developers.google.com/doubleclick-advertisers/current/campaigns#startDate) and [end](https://developers.google.com/doubleclick-advertisers/current/campaigns#endDate) dates - These must be in the future, and can be accurate down to the day. See the dates and times bullet in [General coding information](https://developers.google.com/doubleclick-advertisers/trafficking_tasks#codingtips) for more details. Individual ad dates can exceed the end date, to enable a publisher to try to fulfill a contract for a specified number of actions, if it hasn't been filled by the given campaign end date.

   ```python
   # Locate an advertiser landing page to use as a default.
   default_landing_page = get_advertiser_landing_page(service, profile_id,
                                                      advertiser_id)

   # Construct and save campaign.
   campaign = {
       'name': 'Test Campaign #%s' % uuid.uuid4(),
       'advertiserId': advertiser_id,
       'archived': 'false',
       'defaultLandingPageId': default_landing_page['id'],
       'startDate': '2025-11-01',
       'endDate': '2025-12-01',
       'euPoliticalAdsDeclaration': 'CONTAINS_EU_POLITICAL_ADS',
   }
   ```
2.
   Call `https://developers.google.com/doubleclick-advertisers/current/campaigns/insert` to save the campaign.

   ```python
   request = service.campaigns().insert(profileId=profile_id, body=campaign)

   # Execute request and print response.
   response = request.execute()
   ```

   <br />

### Ruby

1.
   Create a `https://developers.google.com/doubleclick-advertisers/current/campaigns` object and set it's required properties:

   - `https://developers.google.com/doubleclick-advertisers/current/campaigns#advertiserId` - The advertiser with which to associate this campaign.
   - `https://developers.google.com/doubleclick-advertisers/current/campaigns#name` - This must be unique across all campaigns for this advertiser.
   - `https://developers.google.com/doubleclick-advertisers/current/campaigns#defaultLandingPageId` - A landing page to which users will be directed when they click on an ad in this campaign, if one isn't assigned to that ad. You can look up existing landing pages by calling `https://developers.google.com/doubleclick-advertisers/current/advertiserLandingPages/list` or create a new one by calling `https://developers.google.com/doubleclick-advertisers/current/advertiserLandingPages/insert`.
   - [Start](https://developers.google.com/doubleclick-advertisers/current/campaigns#startDate) and [end](https://developers.google.com/doubleclick-advertisers/current/campaigns#endDate) dates - These must be in the future, and can be accurate down to the day. See the dates and times bullet in [General coding information](https://developers.google.com/doubleclick-advertisers/trafficking_tasks#codingtips) for more details. Individual ad dates can exceed the end date, to enable a publisher to try to fulfill a contract for a specified number of actions, if it hasn't been filled by the given campaign end date.

   ```ruby
   # Locate an advertiser landing page to use as a default.
   default_landing_page = get_advertiser_landing_page(service, profile_id,
     advertiser_id)

   # Create a new campaign resource to insert.
   campaign = DfareportingUtils::API_NAMESPACE::Campaign.new(
     advertiser_id: advertiser_id,
     archived: false,
     default_landing_page_id: default_landing_page.id,
     name: format('Example Campaign #%s', SecureRandom.hex(3)),
     start_date: '2025-11-01',
     end_date: '2025-12-01',
     eu_political_ads_declaration: 'CONTAINS_EU_POLITICAL_ADS'
   )
   ```
2.
   Call `https://developers.google.com/doubleclick-advertisers/current/campaigns/insert` to save the campaign.

   ```ruby
   # Insert the campaign.
   result = service.insert_campaign(profile_id, campaign)
   ```

   <br />

## Create a placement

### C#

1. Create a `https://developers.google.com/doubleclick-advertisers/current/placements` object and set the required placement properties (including `https://developers.google.com/doubleclick-advertisers/current/placements#campaignId` and `https://developers.google.com/doubleclick-advertisers/current/placements#siteId`). Also, be sure to set the placement type and size accurately for the placement that you have negotiated with your website.

   ```c#
   // Create the placement.
   Placement placement = new Placement();
   placement.Name = placementName;
   placement.CampaignId = campaignId;
   placement.Compatibility = "DISPLAY";
   placement.PaymentSource = "PLACEMENT_AGENCY_PAID";
   placement.SiteId = dfaSiteId;
   placement.TagFormats = new List<string>() { "PLACEMENT_TAG_STANDARD" };

   // Set the size of the placement.
   Size size = new Size();
   size.Id = sizeId;
   placement.Size = size;
   ```
2. Create a new `https://developers.google.com/doubleclick-advertisers/current/placements#pricingSchedule` object to assign to the placement.

   ```c#
   // Set the pricing schedule for the placement.
   PricingSchedule pricingSchedule = new PricingSchedule();
   pricingSchedule.EndDate = campaign.EndDate;
   pricingSchedule.PricingType = "PRICING_TYPE_CPM";
   pricingSchedule.StartDate = campaign.StartDate;
   placement.PricingSchedule = pricingSchedule;
   ```
3. Save the `Placement` object by calling `https://developers.google.com/doubleclick-advertisers/current/placements/insert`. Be sure to store the returned ID if you want to use it to assign to an Ad or Creative.

   ```c#
   // Insert the placement.
   Placement result = service.Placements.Insert(placement, profileId).Execute();
   ```

### Java

1. Create a `https://developers.google.com/doubleclick-advertisers/current/placements` object and set the required placement properties (including `https://developers.google.com/doubleclick-advertisers/current/placements#campaignId` and `https://developers.google.com/doubleclick-advertisers/current/placements#siteId`). Also, be sure to set the placement type and size accurately for the placement that you have negotiated with your website.

   ```java
   // Create the placement.
   Placement placement = new Placement();
   placement.setName(placementName);
   placement.setCampaignId(campaignId);
   placement.setCompatibility("DISPLAY");
   placement.setPaymentSource("PLACEMENT_AGENCY_PAID");
   placement.setSiteId(dfaSiteId);
   placement.setTagFormats(ImmutableList.of("PLACEMENT_TAG_STANDARD"));

   // Set the size of the placement.
   Size size = new Size();
   size.setId(sizeId);
   placement.setSize(size);
   ```
2. Create a new `https://developers.google.com/doubleclick-advertisers/current/placements#pricingSchedule` object to assign to the placement.

   ```java
   // Set the pricing schedule for the placement.
   PricingSchedule pricingSchedule = new PricingSchedule();
   pricingSchedule.setEndDate(campaign.getEndDate());
   pricingSchedule.setPricingType("PRICING_TYPE_CPM");
   pricingSchedule.setStartDate(campaign.getStartDate());
   placement.setPricingSchedule(pricingSchedule);
   ```
3. Save the `Placement` object by calling `https://developers.google.com/doubleclick-advertisers/current/placements/insert`. Be sure to store the returned ID if you want to use it to assign to an Ad or Creative.

   ```java
   // Insert the placement.
   Placement result = reporting.placements().insert(profileId, placement).execute();
   ```

### PHP

1. Create a `https://developers.google.com/doubleclick-advertisers/current/placements` object and set the required placement properties (including `https://developers.google.com/doubleclick-advertisers/current/placements#campaignId` and `https://developers.google.com/doubleclick-advertisers/current/placements#siteId`). Also, be sure to set the placement type and size accurately for the placement that you have negotiated with your website.

   ```php
   $placement = new Google_Service_Dfareporting_Placement();
   $placement->setCampaignId($values['campaign_id']);
   $placement->setCompatibility('DISPLAY');
   $placement->setName($values['placement_name']);
   $placement->setPaymentSource('PLACEMENT_AGENCY_PAID');
   $placement->setSiteId($values['site_id']);
   $placement->setTagFormats(['PLACEMENT_TAG_STANDARD']);

   // Set the size of the placement.
   $size = new Google_Service_Dfareporting_Size();
   $size->setId($values['size_id']);
   $placement->setSize($size);
   ```
2. Create a new `https://developers.google.com/doubleclick-advertisers/current/placements#pricingSchedule` object to assign to the placement.

   ```php
   // Set the pricing schedule for the placement.
   $pricingSchedule = new Google_Service_Dfareporting_PricingSchedule();
   $pricingSchedule->setEndDate($campaign->getEndDate());
   $pricingSchedule->setPricingType('PRICING_TYPE_CPM');
   $pricingSchedule->setStartDate($campaign->getStartDate());
   $placement->setPricingSchedule($pricingSchedule);
   ```
3. Save the `Placement` object by calling `https://developers.google.com/doubleclick-advertisers/current/placements/insert`. Be sure to store the returned ID if you want to use it to assign to an Ad or Creative.

   ```php
   // Insert the placement.
   $result = $this->service->placements->insert(
       $values['user_profile_id'],
       $placement
   );
   ```

### Python

1. Create a `https://developers.google.com/doubleclick-advertisers/current/placements` object and set the required placement properties (including `https://developers.google.com/doubleclick-advertisers/current/placements#campaignId` and `https://developers.google.com/doubleclick-advertisers/current/placements#siteId`). Also, be sure to set the placement type and size accurately for the placement that you have negotiated with your website.

   ```python
   # Construct and save placement.
   placement = {
       'name': 'Test Placement',
       'campaignId': campaign_id,
       'compatibility': 'DISPLAY',
       'siteId': site_id,
       'size': {
           'height': '1',
           'width': '1'
       },
       'paymentSource': 'PLACEMENT_AGENCY_PAID',
       'tagFormats': ['PLACEMENT_TAG_STANDARD']
   }
   ```
2. Create a new `https://developers.google.com/doubleclick-advertisers/current/placements#pricingSchedule` object to assign to the placement.

   ```python
   # Set the pricing schedule for the placement.
   placement['pricingSchedule'] = {
       'startDate': campaign['startDate'],
       'endDate': campaign['endDate'],
       'pricingType': 'PRICING_TYPE_CPM'
   }
   ```
3. Save the `Placement` object by calling `https://developers.google.com/doubleclick-advertisers/current/placements/insert`. Be sure to store the returned ID if you want to use it to assign to an Ad or Creative.

   ```python
   request = service.placements().insert(
       profileId=str(profile_id), body=placement
   )

   # Execute request and print response.
   response = request.execute()
   ```

### Ruby

1. Create a `https://developers.google.com/doubleclick-advertisers/current/placements` object and set the required placement properties (including `https://developers.google.com/doubleclick-advertisers/current/placements#campaignId` and `https://developers.google.com/doubleclick-advertisers/current/placements#siteId`). Also, be sure to set the placement type and size accurately for the placement that you have negotiated with your website.

   ```ruby
   # Create a new placement resource to insert.
   placement = DfareportingUtils::API_NAMESPACE::Placement.new(
     campaign_id: campaign_id,
     compatibility: 'DISPLAY',
     name: 'Example Placement',
     payment_source: 'PLACEMENT_AGENCY_PAID',
     site_id: site_id,
     size: DfareportingUtils::API_NAMESPACE::Size.new(
       height: 1,
       width: 1
     ),
     tag_formats: ['PLACEMENT_TAG_STANDARD']
   )
   ```
2. Create a new `https://developers.google.com/doubleclick-advertisers/current/placements#pricingSchedule` object to assign to the placement.

   ```ruby
   # Set the pricing schedule for the placement.
   placement.pricing_schedule =
     DfareportingUtils::API_NAMESPACE::PricingSchedule.new(
       end_date: campaign.end_date,
       pricing_type: 'PRICING_TYPE_CPM',
       start_date: campaign.start_date
     )
   ```
3. Save the `Placement` object by calling `https://developers.google.com/doubleclick-advertisers/current/placements/insert`. Be sure to store the returned ID if you want to use it to assign to an Ad or Creative.

   ```ruby
   # Insert the placement strategy.
   result = service.insert_placement(profile_id, placement)
   ```

## Upload assets

You can upload many types of asset via a process known as [media upload](https://developers.google.com/doubleclick-advertisers/upload). Although this process is similar for all creative types, some types may require specific properties to be passed as metadata, in order for them to be used properly.

### C#

1.
   Create an `https://developers.google.com/doubleclick-advertisers/current/creativeAssets#assetIdentifier`object and set the required properties. All assets, no matter what type or how used, are required to specify an `assetIdentifier`. When assigning the asset to a creative, this object will be used to refer back to the asset. The following properties are required:

   - The `https://developers.google.com/doubleclick-advertisers/current/creativeAssets#assetIdentifier.name` property, which will be the name of the asset on the server. The name must include an extension that indicates the file type such as .png, or .gif, and will be exposed to the browser as the asset name, but it does not have to be the same as the original file name. Note that this name might be changed by Campaign Manager 360 to make it unique on the server; check the return value to see if it has been changed.
   - The `https://developers.google.com/doubleclick-advertisers/current/creativeAssets#assetIdentifier.type` property, which identifies the type of asset. This property will dictate the types of creatives this asset can be associated with.

   ```c#
   // Create the creative asset ID and Metadata.
   CreativeAssetId assetId = new CreativeAssetId();
   assetId.Name = Path.GetFileName(assetFile);
   assetId.Type = assetType;
   ```
2.
   Upload the file by calling `https://developers.google.com/doubleclick-advertisers/current/creativeAssets/insert`. Perform a [multipart upload](https://developers.google.com/doubleclick-advertisers/upload#multipart), passing both the `assetIdentifier` and the file contents as part of the same request. If successful, a `https://developers.google.com/doubleclick-advertisers/current/creativeAssets` resource will be returned, with an `assetIdentifier` that you will use to assign this asset to a creative.

   ```c#
   // Prepare an input stream.
   FileStream assetContent = new FileStream(assetFile, FileMode.Open, FileAccess.Read);


   CreativeAssetMetadata metaData = new CreativeAssetMetadata();
   metaData.AssetIdentifier = assetId;

   // Insert the creative.
   String mimeType = determineMimeType(assetFile, assetType);
   CreativeAssetsResource.InsertMediaUpload request =
       Service.CreativeAssets.Insert(metaData, ProfileId, AdvertiserId, assetContent, mimeType);

   IUploadProgress progress = request.Upload();
   if (UploadStatus.Failed.Equals(progress.Status)) {
       throw progress.Exception;
   }
   ```

   <br />

### Java

1.
   Create an `https://developers.google.com/doubleclick-advertisers/current/creativeAssets#assetIdentifier`object and set the required properties. All assets, no matter what type or how used, are required to specify an `assetIdentifier`. When assigning the asset to a creative, this object will be used to refer back to the asset. The following properties are required:

   - The `https://developers.google.com/doubleclick-advertisers/current/creativeAssets#assetIdentifier.name` property, which will be the name of the asset on the server. The name must include an extension that indicates the file type such as .png, or .gif, and will be exposed to the browser as the asset name, but it does not have to be the same as the original file name. Note that this name might be changed by Campaign Manager 360 to make it unique on the server; check the return value to see if it has been changed.
   - The `https://developers.google.com/doubleclick-advertisers/current/creativeAssets#assetIdentifier.type` property, which identifies the type of asset. This property will dictate the types of creatives this asset can be associated with.

   ```java
   // Create the creative asset ID and Metadata.
   CreativeAssetId assetId = new CreativeAssetId();
   assetId.setName(assetName);
   assetId.setType(assetType);
   ```
2.
   Upload the file by calling `https://developers.google.com/doubleclick-advertisers/current/creativeAssets/insert`. Perform a [multipart upload](https://developers.google.com/doubleclick-advertisers/upload#multipart), passing both the `assetIdentifier` and the file contents as part of the same request. If successful, a `https://developers.google.com/doubleclick-advertisers/current/creativeAssets` resource will be returned, with an `assetIdentifier` that you will use to assign this asset to a creative.

   ```java
   // Open the asset file.
   File file = new File(assetFile);

   // Prepare an input stream.
   String contentType = getMimeType(assetFile);
   InputStreamContent assetContent =
       new InputStreamContent(contentType, new BufferedInputStream(new FileInputStream(file)));
   assetContent.setLength(file.length());


   CreativeAssetMetadata metaData = new CreativeAssetMetadata();
   metaData.setAssetIdentifier(assetId);

   // Insert the creative.
   CreativeAssetMetadata result = reporting.creativeAssets()
       .insert(profileId, advertiserId, metaData, assetContent).execute();
   ```

   <br />

### PHP

1.
   Create an `https://developers.google.com/doubleclick-advertisers/current/creativeAssets#assetIdentifier`object and set the required properties. All assets, no matter what type or how used, are required to specify an `assetIdentifier`. When assigning the asset to a creative, this object will be used to refer back to the asset. The following properties are required:

   - The `https://developers.google.com/doubleclick-advertisers/current/creativeAssets#assetIdentifier.name` property, which will be the name of the asset on the server. The name must include an extension that indicates the file type such as .png, or .gif, and will be exposed to the browser as the asset name, but it does not have to be the same as the original file name. Note that this name might be changed by Campaign Manager 360 to make it unique on the server; check the return value to see if it has been changed.
   - The `https://developers.google.com/doubleclick-advertisers/current/creativeAssets#assetIdentifier.type` property, which identifies the type of asset. This property will dictate the types of creatives this asset can be associated with.

   ```php
   $assetId = new Google_Service_Dfareporting_CreativeAssetId();
   $assetId->setName($asset['name']);
   $assetId->setType($type);
   ```
2.
   Upload the file by calling `https://developers.google.com/doubleclick-advertisers/current/creativeAssets/insert`. Perform a [multipart upload](https://developers.google.com/doubleclick-advertisers/upload#multipart), passing both the `assetIdentifier` and the file contents as part of the same request. If successful, a `https://developers.google.com/doubleclick-advertisers/current/creativeAssets` resource will be returned, with an `assetIdentifier` that you will use to assign this asset to a creative.

   ```php
   $metadata = new Google_Service_Dfareporting_CreativeAssetMetadata();
   $metadata->setAssetIdentifier($assetId);

   $result = $service->creativeAssets->insert(
       $userProfileId,
       $advertiserId,
       $metadata,
       ['data' => file_get_contents($asset['tmp_name']),
        'mimeType' => $asset['type'],
        'uploadType' => 'multipart']
   );
   ```

   <br />

### Python

1.
   Create an `https://developers.google.com/doubleclick-advertisers/current/creativeAssets#assetIdentifier`object and set the required properties. All assets, no matter what type or how used, are required to specify an `assetIdentifier`. When assigning the asset to a creative, this object will be used to refer back to the asset. The following properties are required:

   - The `https://developers.google.com/doubleclick-advertisers/current/creativeAssets#assetIdentifier.name` property, which will be the name of the asset on the server. The name must include an extension that indicates the file type such as .png, or .gif, and will be exposed to the browser as the asset name, but it does not have to be the same as the original file name. Note that this name might be changed by Campaign Manager 360 to make it unique on the server; check the return value to see if it has been changed.
   - The `https://developers.google.com/doubleclick-advertisers/current/creativeAssets#assetIdentifier.type` property, which identifies the type of asset. This property will dictate the types of creatives this asset can be associated with.

   ```python
   # Construct the creative asset metadata
   creative_asset = {'assetIdentifier': {'name': asset_name, 'type': asset_type}}
   ```
2.
   Upload the file by calling `https://developers.google.com/doubleclick-advertisers/current/creativeAssets/insert`. Perform a [multipart upload](https://developers.google.com/doubleclick-advertisers/upload#multipart), passing both the `assetIdentifier` and the file contents as part of the same request. If successful, a `https://developers.google.com/doubleclick-advertisers/current/creativeAssets` resource will be returned, with an `assetIdentifier` that you will use to assign this asset to a creative.

   ```python
   media = MediaFileUpload(path_to_asset_file)
   if not media.mimetype():
     media = MediaFileUpload(path_to_asset_file, 'application/octet-stream')

   response = (
       service.creativeAssets()
       .insert(
           advertiserId=str(advertiser_id),
           profileId=str(profile_id),
           media_body=media,
           body=creative_asset,
       )
       .execute()
   )
   ```

   <br />

### Ruby

1.
   Create an `https://developers.google.com/doubleclick-advertisers/current/creativeAssets#assetIdentifier`object and set the required properties. All assets, no matter what type or how used, are required to specify an `assetIdentifier`. When assigning the asset to a creative, this object will be used to refer back to the asset. The following properties are required:

   - The `https://developers.google.com/doubleclick-advertisers/current/creativeAssets#assetIdentifier.name` property, which will be the name of the asset on the server. The name must include an extension that indicates the file type such as .png, or .gif, and will be exposed to the browser as the asset name, but it does not have to be the same as the original file name. Note that this name might be changed by Campaign Manager 360 to make it unique on the server; check the return value to see if it has been changed.
   - The `https://developers.google.com/doubleclick-advertisers/current/creativeAssets#assetIdentifier.type` property, which identifies the type of asset. This property will dictate the types of creatives this asset can be associated with.

   ```ruby
   # Construct the creative asset metadata
   creative_asset = DfareportingUtils::API_NAMESPACE::CreativeAsset.new(
     asset_identifier: DfareportingUtils::API_NAMESPACE::CreativeAssetId.new(
       name: asset_name,
       type: asset_type
     )
   )
   ```
2.
   Upload the file by calling `https://developers.google.com/doubleclick-advertisers/current/creativeAssets/insert`. Perform a [multipart upload](https://developers.google.com/doubleclick-advertisers/upload#multipart), passing both the `assetIdentifier` and the file contents as part of the same request. If successful, a `https://developers.google.com/doubleclick-advertisers/current/creativeAssets` resource will be returned, with an `assetIdentifier` that you will use to assign this asset to a creative.

   ```ruby
   # Upload the asset.
   mime_type = determine_mime_type(path_to_asset_file, asset_type)

   result = @service.insert_creative_asset(
     @profile_id,
     advertiser_id,
     creative_asset,
     content_type: mime_type,
     upload_source: path_to_asset_file
   )
   ```

   <br />

## Create a creative

A `https://developers.google.com/doubleclick-advertisers/current/creatives` object wraps an existing asset. Depending on how you will use the creatives on the host page, you can create `Creative` objects of different creative types. See the [reference documentation](https://developers.google.com/doubleclick-advertisers/current/creatives#type) to determine which type is appropriate for you.

> [!NOTE]
> **Note:** See [Support for AI Content
> Labeling](https://developers.google.com/doubleclick-advertisers/guides/ai_content_labeling) for information on how to set the AI content attestation for creatives.

The following example demonstrates how to create a new HTML5 display creative.

### C#

1. Upload the assets. Different creatives require different types and quantities of assets; see [Upload Assets](https://developers.google.com/doubleclick-advertisers/trafficking_tasks#uploadassets) for details. Each time you successfully upload an asset, you will get an `assetIdenfitier` in the response; you will use the stored file name and type to reference these assets in your creative, rather than a traditional ID.
2. Create a creative and assign appropriate values. Instantiate a `Creative` and set the proper `https://developers.google.com/doubleclick-advertisers/current/creatives#type`; you cannot change a `Creative` object's type after you save it. Specify the assets by their `AssetIdentifier` and their `https://developers.google.com/doubleclick-advertisers/current/creatives#creativeAssets.role`.

   ```c#
   // Locate an advertiser landing page to use as a default.
   LandingPage defaultLandingPage = getAdvertiserLandingPage(service, profileId, advertiserId);

   // Create the creative structure.
   Creative creative = new Creative();
   creative.AdvertiserId = advertiserId;
   creative.Name = "Test HTML5 display creative";
   creative.Size = new Size() { Id = sizeId };
   creative.Type = "DISPLAY";

   // Upload the HTML5 asset.
   CreativeAssetUtils assetUtils = new CreativeAssetUtils(service, profileId, advertiserId);
   CreativeAssetId html5AssetId =
       assetUtils.uploadAsset(pathToHtml5AssetFile, "HTML").AssetIdentifier;

   CreativeAsset html5Asset = new CreativeAsset();
   html5Asset.AssetIdentifier = html5AssetId;
   html5Asset.Role = "PRIMARY";

   // Upload the backup image asset.
   CreativeAssetId imageAssetId =
       assetUtils.uploadAsset(pathToImageAssetFile, "HTML_IMAGE").AssetIdentifier;

   CreativeAsset imageAsset = new CreativeAsset();
   imageAsset.AssetIdentifier = imageAssetId;
   imageAsset.Role = "BACKUP_IMAGE";

   // Add the creative assets.
   creative.CreativeAssets = new List<CreativeAsset>() { html5Asset, imageAsset };

   // Configure the bacup image.
   creative.BackupImageClickThroughUrl = new CreativeClickThroughUrl() {
     LandingPageId = defaultLandingPage.Id
   };
   creative.BackupImageReportingLabel = "backup";
   creative.BackupImageTargetWindow = new TargetWindow() { TargetWindowOption = "NEW_WINDOW" };

   // Add a click tag.
   ClickTag clickTag = new ClickTag();
   clickTag.Name = "clickTag";
   clickTag.EventName = "exit";
   clickTag.ClickThroughUrl = new CreativeClickThroughUrl() {
     LandingPageId = defaultLandingPage.Id
   };
   creative.ClickTags = new List<ClickTag>() { clickTag };
   ```
3. Save the creative. Do this by calling `https://developers.google.com/doubleclick-advertisers/current/creatives/insert`. It is required to specify an advertiser ID with which to associate this creative.

   ```c#
   Creative result = service.Creatives.Insert(creative, profileId).Execute();
   ```
4. (Optional) Associate the creative with a campaign. This can be done by calling `https://developers.google.com/doubleclick-advertisers/current/campaignCreativeAssociations/insert`, passing in the campaign and creative IDs.

   ```c#
   // Create the campaign creative association structure.
   CampaignCreativeAssociation association = new CampaignCreativeAssociation();
   association.CreativeId = creativeId;

   // Insert the association.
   CampaignCreativeAssociation result =
       service.CampaignCreativeAssociations.Insert(association, profileId, campaignId).Execute();
   ```

### Java

1. Upload the assets. Different creatives require different types and quantities of assets; see [Upload Assets](https://developers.google.com/doubleclick-advertisers/trafficking_tasks#uploadassets) for details. Each time you successfully upload an asset, you will get an `assetIdenfitier` in the response; you will use the stored file name and type to reference these assets in your creative, rather than a traditional ID.
2. Create a creative and assign appropriate values. Instantiate a `Creative` and set the proper `https://developers.google.com/doubleclick-advertisers/current/creatives#type`; you cannot change a `Creative` object's type after you save it. Specify the assets by their `AssetIdentifier` and their `https://developers.google.com/doubleclick-advertisers/current/creatives#creativeAssets.role`.

   ```java
   // Locate an advertiser landing page to use as a default.
   LandingPage defaultLandingPage = getAdvertiserLandingPage(reporting, profileId, advertiserId);

   // Create the creative structure.
   Creative creative = new Creative();
   creative.setAdvertiserId(advertiserId);
   creative.setName("Test HTML5 display creative");
   creative.setSize(new Size().setId(sizeId));
   creative.setType("DISPLAY");

   // Upload the HTML5 asset.
   CreativeAssetId html5AssetId = CreativeAssetUtils.uploadAsset(reporting, profileId,
       advertiserId, HTML5_ASSET_NAME, PATH_TO_HTML5_ASSET_FILE, "HTML").getAssetIdentifier();

   CreativeAsset html5Asset =
       new CreativeAsset().setAssetIdentifier(html5AssetId).setRole("PRIMARY");

   // Upload the backup image asset (note: asset type must be set to HTML_IMAGE).
   CreativeAssetId imageAssetId = CreativeAssetUtils.uploadAsset(reporting, profileId,
       advertiserId, IMAGE_ASSET_NAME, PATH_TO_IMAGE_ASSET_FILE, "HTML_IMAGE")
       .getAssetIdentifier();

   CreativeAsset backupImageAsset =
       new CreativeAsset().setAssetIdentifier(imageAssetId).setRole("BACKUP_IMAGE");

   // Add the creative assets.
   creative.setCreativeAssets(ImmutableList.of(html5Asset, backupImageAsset));

   // Configure the backup image.
   creative.setBackupImageClickThroughUrl(
       new CreativeClickThroughUrl().setLandingPageId(defaultLandingPage.getId()));
   creative.setBackupImageReportingLabel("backup");
   creative.setBackupImageTargetWindow(new TargetWindow().setTargetWindowOption("NEW_WINDOW"));

   // Add a click tag.
   ClickTag clickTag =
       new ClickTag().setName("clickTag").setEventName("exit").setClickThroughUrl(
           new CreativeClickThroughUrl().setLandingPageId(defaultLandingPage.getId()));
   creative.setClickTags(ImmutableList.of(clickTag));
   ```
3. Save the creative. Do this by calling `https://developers.google.com/doubleclick-advertisers/current/creatives/insert`. It is required to specify an advertiser ID with which to associate this creative.

   ```java
   Creative result = reporting.creatives().insert(profileId, creative).execute();
   ```
4. (Optional) Associate the creative with a campaign. This can be done by calling `https://developers.google.com/doubleclick-advertisers/current/campaignCreativeAssociations/insert`, passing in the campaign and creative IDs.

   ```java
   // Create the campaign creative association structure.
   CampaignCreativeAssociation association = new CampaignCreativeAssociation();
   association.setCreativeId(creativeId);

   // Insert the association.
   CampaignCreativeAssociation result = reporting
       .campaignCreativeAssociations().insert(profileId, campaignId, association)
       .execute();
   ```

### PHP

1. Upload the assets. Different creatives require different types and quantities of assets; see [Upload Assets](https://developers.google.com/doubleclick-advertisers/trafficking_tasks#uploadassets) for details. Each time you successfully upload an asset, you will get an `assetIdenfitier` in the response; you will use the stored file name and type to reference these assets in your creative, rather than a traditional ID.
2. Create a creative and assign appropriate values. Instantiate a `Creative` and set the proper `https://developers.google.com/doubleclick-advertisers/current/creatives#type`; you cannot change a `Creative` object's type after you save it. Specify the assets by their `AssetIdentifier` and their `https://developers.google.com/doubleclick-advertisers/current/creatives#creativeAssets.role`.

   ```php
   $creative = new Google_Service_Dfareporting_Creative();
   $creative->setAdvertiserId($values['advertiser_id']);
   $creative->setAutoAdvanceImages(true);
   $creative->setName('Test HTML5 display creative');
   $creative->setType('DISPLAY');

   $size = new Google_Service_Dfareporting_Size();
   $size->setId($values['size_id']);
   $creative->setSize($size);

   // Upload the HTML5 asset.
   $html = uploadAsset(
       $this->service,
       $values['user_profile_id'],
       $values['advertiser_id'],
       $values['html_asset_file'],
       'HTML'
   );

   $htmlAsset = new Google_Service_Dfareporting_CreativeAsset();
   $htmlAsset->setAssetIdentifier($html->getAssetIdentifier());
   $htmlAsset->setRole('PRIMARY');

   // Upload the backup image asset.
   $image = uploadAsset(
       $this->service,
       $values['user_profile_id'],
       $values['advertiser_id'],
       $values['image_asset_file'],
       'HTML_IMAGE'
   );

   $imageAsset = new Google_Service_Dfareporting_CreativeAsset();
   $imageAsset->setAssetIdentifier($image->getAssetIdentifier());
   $imageAsset->setRole('BACKUP_IMAGE');

   // Add the creative assets.
   $creative->setCreativeAssets([$htmlAsset, $imageAsset]);

   // Configure the default click-through URL.
   $clickThroughUrl =
       new Google_Service_Dfareporting_CreativeClickThroughUrl();
   $clickThroughUrl->setLandingPageId($values['landing_page_id']);

   // Configure the backup image.
   $creative->setBackupImageClickThroughUrl($clickThroughUrl);
   $creative->setBackupImageReportingLabel('backup');

   $targetWindow = new Google_Service_Dfareporting_TargetWindow();
   $targetWindow->setTargetWindowOption('NEW_WINDOW');
   $creative->setBackupImageTargetWindow($targetWindow);

   // Add a click tag.
   $clickTag = new Google_Service_Dfareporting_ClickTag();
   $clickTag->setName('clickTag');
   $clickTag->setEventName('exit');
   $clickTag->setClickThroughUrl($clickThroughUrl);
   $creative->setClickTags([$clickTag]);
   ```
3. Save the creative. Do this by calling `https://developers.google.com/doubleclick-advertisers/current/creatives/insert`. It is required to specify an advertiser ID with which to associate this creative.

   ```php
   $result = $this->service->creatives->insert(
       $values['user_profile_id'],
       $creative
   );
   ```
4. (Optional) Associate the creative with a campaign. This can be done by calling `https://developers.google.com/doubleclick-advertisers/current/campaignCreativeAssociations/insert`, passing in the campaign and creative IDs.

   ```php
   $association =
       new Google_Service_Dfareporting_CampaignCreativeAssociation();
   $association->setCreativeId($values['creative_id']);

   $result = $this->service->campaignCreativeAssociations->insert(
       $values['user_profile_id'],
       $values['campaign_id'],
       $association
   );
   ```

### Python

1. Upload the assets. Different creatives require different types and quantities of assets; see [Upload Assets](https://developers.google.com/doubleclick-advertisers/trafficking_tasks#uploadassets) for details. Each time you successfully upload an asset, you will get an `assetIdenfitier` in the response; you will use the stored file name and type to reference these assets in your creative, rather than a traditional ID.
2. Create a creative and assign appropriate values. Instantiate a `Creative` and set the proper `https://developers.google.com/doubleclick-advertisers/current/creatives#type`; you cannot change a `Creative` object's type after you save it. Specify the assets by their `AssetIdentifier` and their `https://developers.google.com/doubleclick-advertisers/current/creatives#creativeAssets.role`.

   ```python
   # Locate an advertiser landing page to use as a default.
   default_landing_page = get_advertiser_landing_page(service, profile_id,
                                                      advertiser_id)

   # Upload the HTML5 asset
   html5_asset_id = upload_creative_asset(service, profile_id, advertiser_id,
                                          html5_asset_name,
                                          path_to_html5_asset_file, 'HTML')

   # Upload the backup image asset
   backup_image_asset_id = upload_creative_asset(
       service, profile_id, advertiser_id, backup_image_name,
       path_to_backup_image_file, 'HTML_IMAGE')

   # Construct the creative structure.
   creative = {
       'advertiserId': advertiser_id,
       'backupImageClickThroughUrl': {
           'landingPageId': default_landing_page['id']
       },
       'backupImageReportingLabel': 'backup_image_exit',
       'backupImageTargetWindow': {'targetWindowOption': 'NEW_WINDOW'},
       'clickTags': [{
           'eventName': 'exit',
           'name': 'click_tag',
           'clickThroughUrl': {'landingPageId': default_landing_page['id']}
       }],
       'creativeAssets': [
           {'assetIdentifier': html5_asset_id, 'role': 'PRIMARY'},
           {'assetIdentifier': backup_image_asset_id, 'role': 'BACKUP_IMAGE'}
       ],
       'name': 'Test HTML5 display creative',
       'size': {'id': size_id},
       'type': 'DISPLAY'
   }
   ```
3. Save the creative. Do this by calling `https://developers.google.com/doubleclick-advertisers/current/creatives/insert`. It is required to specify an advertiser ID with which to associate this creative.

   ```python
   request = service.creatives().insert(
       profileId=str(profile_id), body=creative
   )

   # Execute request and print response.
   response = request.execute()
   ```
4. (Optional) Associate the creative with a campaign. This can be done by calling `https://developers.google.com/doubleclick-advertisers/current/campaignCreativeAssociations/insert`, passing in the campaign and creative IDs.

   ```python
   # Construct the request.
   association = {
       'creativeId': creative_id
   }

   request = service.campaignCreativeAssociations().insert(
       profileId=str(profile_id), campaignId=str(campaign_id), body=association
   )

   # Execute request and print response.
   response = request.execute()
   ```

### Ruby

1. Upload the assets. Different creatives require different types and quantities of assets; see [Upload Assets](https://developers.google.com/doubleclick-advertisers/trafficking_tasks#uploadassets) for details. Each time you successfully upload an asset, you will get an `assetIdenfitier` in the response; you will use the stored file name and type to reference these assets in your creative, rather than a traditional ID.
2. Create a creative and assign appropriate values. Instantiate a `Creative` and set the proper `https://developers.google.com/doubleclick-advertisers/current/creatives#type`; you cannot change a `Creative` object's type after you save it. Specify the assets by their `AssetIdentifier` and their `https://developers.google.com/doubleclick-advertisers/current/creatives#creativeAssets.role`.

   ```ruby
   # Locate an advertiser landing page to use as a default.
   default_landing_page = get_advertiser_landing_page(service, profile_id,
     advertiser_id)

   # Upload the HTML5 asset.
   html5_asset_id = util.upload_asset(advertiser_id, path_to_html5_asset_file,
     'HTML').asset_identifier

   # Upload the backup image asset.
   backup_image_asset_id = util.upload_asset(advertiser_id,
     path_to_backup_image_file, 'HTML_IMAGE').asset_identifier

   # Construct the creative structure.
   creative = DfareportingUtils::API_NAMESPACE::Creative.new(
     advertiser_id: advertiser_id,
     backup_image_click_through_url:
       DfareportingUtils::API_NAMESPACE::CreativeClickThroughUrl.new(
         landing_page_id: default_landing_page.id
       ),
     backup_image_reporting_label: 'backup',
     backup_image_target_window:
       DfareportingUtils::API_NAMESPACE::TargetWindow.new(
         target_window_option: 'NEW_WINDOW'
       ),
     click_tags: [
       DfareportingUtils::API_NAMESPACE::ClickTag.new(
         event_name: 'exit',
         name: 'click_tag',
         click_through_url:
           DfareportingUtils::API_NAMESPACE::CreativeClickThroughUrl.new(
             landing_page_id: default_landing_page.id
           )
       )
     ],
     creative_assets: [
       DfareportingUtils::API_NAMESPACE::CreativeAsset.new(
         asset_identifier: html5_asset_id,
         role: 'PRIMARY'
       ),
       DfareportingUtils::API_NAMESPACE::CreativeAsset.new(
         asset_identifier: backup_image_asset_id,
         role: 'BACKUP_IMAGE'
       )
     ],
     name: 'Example HTML5 display creative',
     size: DfareportingUtils::API_NAMESPACE::Size.new(id: size_id),
     type: 'DISPLAY'
   )
   ```
3. Save the creative. Do this by calling `https://developers.google.com/doubleclick-advertisers/current/creatives/insert`. It is required to specify an advertiser ID with which to associate this creative.

   ```ruby
   # Insert the creative.
   result = service.insert_creative(profile_id, creative)
   ```
4. (Optional) Associate the creative with a campaign. This can be done by calling `https://developers.google.com/doubleclick-advertisers/current/campaignCreativeAssociations/insert`, passing in the campaign and creative IDs.

   ```ruby
   # Create a new creative-campaign association to insert
   association =
     DfareportingUtils::API_NAMESPACE::CampaignCreativeAssociation.new(
       creative_id: creative_id
     )

   # Insert the advertiser group.
   result = service.insert_campaign_creative_association(profile_id, campaign_id,
     association)
   ```

## Create an ad

An `https://developers.google.com/doubleclick-advertisers/current/ads` is the link between a `Creative` and a `Placement`. An `Ad` can be linked to one or more placements, and holds one or more creatives.

You can create an `Ad` explicitly or implicitly.

### Explicitly

### C#

1. Create a `CreativeAssignment` object for each creative with which this ad should be associated. Be sure to set the `https://developers.google.com/doubleclick-advertisers/current/ads#creativeRotation.creativeAssignments.active` field to true.

   ```c#
   // Create a click-through URL.
   ClickThroughUrl clickThroughUrl = new ClickThroughUrl();
   clickThroughUrl.DefaultLandingPage = true;

   // Create a creative assignment.
   CreativeAssignment creativeAssignment = new CreativeAssignment();
   creativeAssignment.Active = true;
   creativeAssignment.CreativeId = creativeId;
   creativeAssignment.ClickThroughUrl = clickThroughUrl;
   ```
2. Create a `CreativeRotation` object to store the `CreativeAssignment`s. If creating a rotation group, be sure to set the other required creative rotation fields.

   ```c#
   // Create a creative rotation.
   CreativeRotation creativeRotation = new CreativeRotation();
   creativeRotation.CreativeAssignments = new List<CreativeAssignment>() {
       creativeAssignment
   };
   ```
3. Create a `PlacementAssignment` object for each placement with which this ad should be associated. Be sure to set the `https://developers.google.com/doubleclick-advertisers/current/ads#placementAssignments.active` field to true.

   ```c#
   // Create a placement assignment.
   PlacementAssignment placementAssignment = new PlacementAssignment();
   placementAssignment.Active = true;
   placementAssignment.PlacementId = placementId;
   ```
4. Create an `Ad` object. Set the creativeRotation into the `Ad` object's `https://developers.google.com/doubleclick-advertisers/current/ads#creativeRotation` field and the placementAssignments into the `Ad` object's `https://developers.google.com/doubleclick-advertisers/current/ads#placementAssignments` array.

   ```c#
   // Create a delivery schedule.
   DeliverySchedule deliverySchedule = new DeliverySchedule();
   deliverySchedule.ImpressionRatio = 1;
   deliverySchedule.Priority = "AD_PRIORITY_01";

   DateTimeOffset startDate = DateTimeOffset.Now;
   DateTimeOffset endDate = DateTimeOffset.Parse(campaign.EndDate);

   // Create a rotation group.
   Ad rotationGroup = new Ad();
   rotationGroup.Active = true;
   rotationGroup.CampaignId = campaignId;
   rotationGroup.CreativeRotation = creativeRotation;
   rotationGroup.DeliverySchedule = deliverySchedule;
   rotationGroup.StartTimeDateTimeOffset = startDate;
   rotationGroup.EndTimeDateTimeOffset = endDate;
   rotationGroup.Name = adName;
   rotationGroup.PlacementAssignments = new List<PlacementAssignment>() {
       placementAssignment
   };
   rotationGroup.Type = "AD_SERVING_STANDARD_AD";
   ```
5. Save the ad by calling `https://developers.google.com/doubleclick-advertisers/current/ads/insert`.

   ```c#
   // Insert the rotation group.
   Ad result = service.Ads.Insert(rotationGroup, profileId).Execute();
   ```

### Java

1. Create a `CreativeAssignment` object for each creative with which this ad should be associated. Be sure to set the `https://developers.google.com/doubleclick-advertisers/current/ads#creativeRotation.creativeAssignments.active` field to true.

   ```java
   // Create a click-through URL.
   ClickThroughUrl clickThroughUrl = new ClickThroughUrl();
   clickThroughUrl.setDefaultLandingPage(true);

   // Create a creative assignment.
   CreativeAssignment creativeAssignment = new CreativeAssignment();
   creativeAssignment.setActive(true);
   creativeAssignment.setCreativeId(creativeId);
   creativeAssignment.setClickThroughUrl(clickThroughUrl);
   ```
2. Create a `CreativeRotation` object to store the `CreativeAssignment`s. If creating a rotation group, be sure to set the other required creative rotation fields.

   ```java
   // Create a creative rotation.
   CreativeRotation creativeRotation = new CreativeRotation();
   creativeRotation.setCreativeAssignments(ImmutableList.of(creativeAssignment));
   ```
3. Create a `PlacementAssignment` object for each placement with which this ad should be associated. Be sure to set the `https://developers.google.com/doubleclick-advertisers/current/ads#placementAssignments.active` field to true.

   ```java
   // Create a placement assignment.
   PlacementAssignment placementAssignment = new PlacementAssignment();
   placementAssignment.setActive(true);
   placementAssignment.setPlacementId(placementId);
   ```
4. Create an `Ad` object. Set the creativeRotation into the `Ad` object's `https://developers.google.com/doubleclick-advertisers/current/ads#creativeRotation` field and the placementAssignments into the `Ad` object's `https://developers.google.com/doubleclick-advertisers/current/ads#placementAssignments` array.

   ```java
   // Create a delivery schedule.
   DeliverySchedule deliverySchedule = new DeliverySchedule();
   deliverySchedule.setImpressionRatio(1L);
   deliverySchedule.setPriority("AD_PRIORITY_01");

   DateTime startDate = new DateTime(new Date());
   DateTime endDate = new DateTime(campaign.getEndDate().getValue());

   // Create a rotation group.
   Ad rotationGroup = new Ad();
   rotationGroup.setActive(true);
   rotationGroup.setCampaignId(campaignId);
   rotationGroup.setCreativeRotation(creativeRotation);
   rotationGroup.setDeliverySchedule(deliverySchedule);
   rotationGroup.setStartTime(startDate);
   rotationGroup.setEndTime(endDate);
   rotationGroup.setName(adName);
   rotationGroup.setPlacementAssignments(ImmutableList.of(placementAssignment));
   rotationGroup.setType("AD_SERVING_STANDARD_AD");
   ```
5. Save the ad by calling `https://developers.google.com/doubleclick-advertisers/current/ads/insert`.

   ```java
   // Insert the rotation group.
   Ad result = reporting.ads().insert(profileId, rotationGroup).execute();
   ```

### PHP

1. Create a `CreativeAssignment` object for each creative with which this ad should be associated. Be sure to set the `https://developers.google.com/doubleclick-advertisers/current/ads#creativeRotation.creativeAssignments.active` field to true.

   ```php
   // Create a click-through URL.
   $url = new Google_Service_Dfareporting_ClickThroughUrl();
   $url->setDefaultLandingPage(true);

   // Create a creative assignment.
   $creativeAssignment =
       new Google_Service_Dfareporting_CreativeAssignment();
   $creativeAssignment->setActive(true);
   $creativeAssignment->setCreativeId($values['creative_id']);
   $creativeAssignment->setClickThroughUrl($url);
   ```
2. Create a `CreativeRotation` object to store the `CreativeAssignment`s. If creating a rotation group, be sure to set the other required creative rotation fields.

   ```php
   // Create a creative rotation.
   $creativeRotation = new Google_Service_Dfareporting_CreativeRotation();
   $creativeRotation->setCreativeAssignments([$creativeAssignment]);
   ```
3. Create a `PlacementAssignment` object for each placement with which this ad should be associated. Be sure to set the `https://developers.google.com/doubleclick-advertisers/current/ads#placementAssignments.active` field to true.

   ```php
   // Create a placement assignment.
   $placementAssignment =
       new Google_Service_Dfareporting_PlacementAssignment();
   $placementAssignment->setActive(true);
   $placementAssignment->setPlacementId($values['placement_id']);
   ```
4. Create an `Ad` object. Set the creativeRotation into the `Ad` object's `https://developers.google.com/doubleclick-advertisers/current/ads#creativeRotation` field and the placementAssignments into the `Ad` object's `https://developers.google.com/doubleclick-advertisers/current/ads#placementAssignments` array.

   ```php
   // Create a delivery schedule.
   $deliverySchedule = new Google_Service_Dfareporting_DeliverySchedule();
   $deliverySchedule->setImpressionRatio(1);
   $deliverySchedule->SetPriority('AD_PRIORITY_01');

   $startDate = new DateTime('today');
   $endDate = new DateTime($campaign->getEndDate());

   // Create a rotation group.
   $ad = new Google_Service_Dfareporting_Ad();
   $ad->setActive(true);
   $ad->setCampaignId($values['campaign_id']);
   $ad->setCreativeRotation($creativeRotation);
   $ad->setDeliverySchedule($deliverySchedule);
   $ad->setStartTime($startDate->format('Y-m-d') . 'T23:59:59Z');
   $ad->setEndTime($endDate->format('Y-m-d') . 'T00:00:00Z');
   $ad->setName($values['ad_name']);
   $ad->setPlacementAssignments([$placementAssignment]);
   $ad->setType('AD_SERVING_STANDARD_AD');
   ```
5. Save the ad by calling `https://developers.google.com/doubleclick-advertisers/current/ads/insert`.

   ```php
   $result = $this->service->ads->insert($values['user_profile_id'], $ad);
   ```

### Python

1. Create a `CreativeAssignment` object for each creative with which this ad should be associated. Be sure to set the `https://developers.google.com/doubleclick-advertisers/current/ads#creativeRotation.creativeAssignments.active` field to true.

   ```python
   # Construct creative assignment.
   creative_assignment = {
       'active': 'true',
       'creativeId': creative_id,
       'clickThroughUrl': {
           'defaultLandingPage': 'true'
       }
   }
   ```
2. Create a `CreativeRotation` object to store the `CreativeAssignment`s. If creating a rotation group, be sure to set the other required creative rotation fields.

   ```python
   # Construct creative rotation.
   creative_rotation = {
       'creativeAssignments': [creative_assignment],
       'type': 'CREATIVE_ROTATION_TYPE_RANDOM',
       'weightCalculationStrategy': 'WEIGHT_STRATEGY_OPTIMIZED'
   }
   ```
3. Create a `PlacementAssignment` object for each placement with which this ad should be associated. Be sure to set the `https://developers.google.com/doubleclick-advertisers/current/ads#placementAssignments.active` field to true.

   ```python
   # Construct placement assignment.
   placement_assignment = {
       'active': 'true',
       'placementId': placement_id,
   }
   ```
4. Create an `Ad` object. Set the creativeRotation into the `Ad` object's `https://developers.google.com/doubleclick-advertisers/current/ads#creativeRotation` field and the placementAssignments into the `Ad` object's `https://developers.google.com/doubleclick-advertisers/current/ads#placementAssignments` array.

   ```python
   # Construct delivery schedule.
   delivery_schedule = {
       'impressionRatio': '1',
       'priority': 'AD_PRIORITY_01'
   }

   # Construct and save ad.
   ad = {
       'active': 'true',
       'campaignId': campaign_id,
       'creativeRotation': creative_rotation,
       'deliverySchedule': delivery_schedule,
       'endTime': '%sT00:00:00Z' % campaign['endDate'],
       'name': 'Test Rotation Group',
       'placementAssignments': [placement_assignment],
       'startTime': '%sT23:59:59Z' % time.strftime('%Y-%m-%d'),
       'type': 'AD_SERVING_STANDARD_AD'
   }
   ```
5. Save the ad by calling `https://developers.google.com/doubleclick-advertisers/current/ads/insert`.

   ```python
   request = service.ads().insert(profileId=str(profile_id), body=ad)

   # Execute request and print response.
   response = request.execute()
   ```

### Ruby

1. Create a `CreativeAssignment` object for each creative with which this ad should be associated. Be sure to set the `https://developers.google.com/doubleclick-advertisers/current/ads#creativeRotation.creativeAssignments.active` field to true.

   ```ruby
   # Construct creative assignment.
   creative_assignment =
     DfareportingUtils::API_NAMESPACE::CreativeAssignment.new(
       active: true,
       creative_id: creative_id,
       click_through_url: DfareportingUtils::API_NAMESPACE::ClickThroughUrl.new(
         default_landing_page: true
       )
     )
   ```
2. Create a `CreativeRotation` object to store the `CreativeAssignment`s. If creating a rotation group, be sure to set the other required creative rotation fields.

   ```ruby
   # Construct creative rotation.
   creative_rotation = DfareportingUtils::API_NAMESPACE::CreativeRotation.new(
     creative_assignments: [creative_assignment],
     type: 'CREATIVE_ROTATION_TYPE_RANDOM',
     weight_calculation_strategy: 'WEIGHT_STRATEGY_OPTIMIZED'
   )
   ```
3. Create a `PlacementAssignment` object for each placement with which this ad should be associated. Be sure to set the `https://developers.google.com/doubleclick-advertisers/current/ads#placementAssignments.active` field to true.

   ```ruby
   # Construct placement assignment.
   placement_assignment =
     DfareportingUtils::API_NAMESPACE::PlacementAssignment.new(
       active: true,
       placement_id: placement_id
     )
   ```
4. Create an `Ad` object. Set the creativeRotation into the `Ad` object's `https://developers.google.com/doubleclick-advertisers/current/ads#creativeRotation` field and the placementAssignments into the `Ad` object's `https://developers.google.com/doubleclick-advertisers/current/ads#placementAssignments` array.

   ```ruby
   # Construct delivery schedule.
   delivery_schedule = DfareportingUtils::API_NAMESPACE::DeliverySchedule.new(
     impression_ratio: 1,
     priority: 'AD_PRIORITY_01'
   )

   # Construct and save ad.
   ad = DfareportingUtils::API_NAMESPACE::Ad.new(
     active: true,
     campaign_id: campaign_id,
     creative_rotation: creative_rotation,
     delivery_schedule: delivery_schedule,
     end_time: format('%sT00:00:00Z', campaign.end_date),
     name: 'Example Rotation Group',
     placement_assignments: [placement_assignment],
     start_time: format('%sT23:59:59Z', Time.now.strftime('%Y-%m-%d')),
     type: 'AD_SERVING_STANDARD_AD'
   )
   ```
5. Save the ad by calling `https://developers.google.com/doubleclick-advertisers/current/ads/insert`.

   ```ruby
   result = service.insert_ad(profile_id, ad)
   ```

### Implicitly

### C#

1. Create and save a `https://developers.google.com/doubleclick-advertisers/trafficking_tasks#createplacement`.
2. Create and save a `https://developers.google.com/doubleclick-advertisers/trafficking_tasks#createcreative`.
3. Associate the `Creative` with the same `Campaign` used for the `Placement` by calling `https://developers.google.com/doubleclick-advertisers/current/campaignCreativeAssociations/insert` (see step 4 in the [Creating a creative](https://developers.google.com/doubleclick-advertisers/trafficking_tasks#createcreative) section). This will create a [default ad](https://support.google.com/dcm/answer/2826145) associated with both the creative and placement.

   ```c#
   // Create the campaign creative association structure.
   CampaignCreativeAssociation association = new CampaignCreativeAssociation();
   association.CreativeId = creativeId;

   // Insert the association.
   CampaignCreativeAssociation result =
       service.CampaignCreativeAssociations.Insert(association, profileId, campaignId).Execute();
   ```

### Java

1. Create and save a `https://developers.google.com/doubleclick-advertisers/trafficking_tasks#createplacement`.
2. Create and save a `https://developers.google.com/doubleclick-advertisers/trafficking_tasks#createcreative`.
3. Associate the `Creative` with the same `Campaign` used for the `Placement` by calling `https://developers.google.com/doubleclick-advertisers/current/campaignCreativeAssociations/insert` (see step 4 in the [Creating a creative](https://developers.google.com/doubleclick-advertisers/trafficking_tasks#createcreative) section). This will create a [default ad](https://support.google.com/dcm/answer/2826145) associated with both the creative and placement.

   ```java
   // Create the campaign creative association structure.
   CampaignCreativeAssociation association = new CampaignCreativeAssociation();
   association.setCreativeId(creativeId);

   // Insert the association.
   CampaignCreativeAssociation result = reporting
       .campaignCreativeAssociations().insert(profileId, campaignId, association)
       .execute();
   ```

### PHP

1. Create and save a `https://developers.google.com/doubleclick-advertisers/trafficking_tasks#createplacement`.
2. Create and save a `https://developers.google.com/doubleclick-advertisers/trafficking_tasks#createcreative`.
3. Associate the `Creative` with the same `Campaign` used for the `Placement` by calling `https://developers.google.com/doubleclick-advertisers/current/campaignCreativeAssociations/insert` (see step 4 in the [Creating a creative](https://developers.google.com/doubleclick-advertisers/trafficking_tasks#createcreative) section). This will create a [default ad](https://support.google.com/dcm/answer/2826145) associated with both the creative and placement.

   ```php
   $association =
       new Google_Service_Dfareporting_CampaignCreativeAssociation();
   $association->setCreativeId($values['creative_id']);

   $result = $this->service->campaignCreativeAssociations->insert(
       $values['user_profile_id'],
       $values['campaign_id'],
       $association
   );
   ```

### Python

1. Create and save a `https://developers.google.com/doubleclick-advertisers/trafficking_tasks#createplacement`.
2. Create and save a `https://developers.google.com/doubleclick-advertisers/trafficking_tasks#createcreative`.
3. Associate the `Creative` with the same `Campaign` used for the `Placement` by calling `https://developers.google.com/doubleclick-advertisers/current/campaignCreativeAssociations/insert` (see step 4 in the [Creating a creative](https://developers.google.com/doubleclick-advertisers/trafficking_tasks#createcreative) section). This will create a [default ad](https://support.google.com/dcm/answer/2826145) associated with both the creative and placement.

   ```python
   # Construct the request.
   association = {
       'creativeId': creative_id
   }

   request = service.campaignCreativeAssociations().insert(
       profileId=str(profile_id), campaignId=str(campaign_id), body=association
   )

   # Execute request and print response.
   response = request.execute()
   ```

### Ruby

1. Create and save a `https://developers.google.com/doubleclick-advertisers/trafficking_tasks#createplacement`.
2. Create and save a `https://developers.google.com/doubleclick-advertisers/trafficking_tasks#createcreative`.
3. Associate the `Creative` with the same `Campaign` used for the `Placement` by calling `https://developers.google.com/doubleclick-advertisers/current/campaignCreativeAssociations/insert` (see step 4 in the [Creating a creative](https://developers.google.com/doubleclick-advertisers/trafficking_tasks#createcreative) section). This will create a [default ad](https://support.google.com/dcm/answer/2826145) associated with both the creative and placement.

   ```ruby
   # Create a new creative-campaign association to insert
   association =
     DfareportingUtils::API_NAMESPACE::CampaignCreativeAssociation.new(
       creative_id: creative_id
     )

   # Insert the advertiser group.
   result = service.insert_campaign_creative_association(profile_id, campaign_id,
     association)
   ```

Creating an ad implicitly saves the extra step of creating an `Ad`. Note that this can only be done if no default ad of the specified size already exists within your campaign.

## Search for objects

You can search for objects by calling the `list()` operation exposed by the service that defines the object to find, specifying optional criteria appropriate for that object type. So, for example, to search for Ad objects, you would call `https://developers.google.com/doubleclick-advertisers/current/ads/list`. The optional criteria expose a set of properties appropriate for that object; fill out as many properties as you want to search on. The search will return only objects that fulfill *all* of your criteria; you cannot do a search that matches any criteria. Strings support the \* wildcard, are not case-sensitive, and match within larger strings.

To improve performance, partial responses can be requested using the `fields` parameter. This instructs the server to return only the fields you specify, rather than the full resource representation. More info on this topic can be found in the [Performance Tips](https://developers.google.com/doubleclick-advertisers/performance#partial-response) guide.

### Paging

Sometimes it's not desirable to retrieve all of the results for a `list()` request. For example, you may only be interested in the 10 newest Ads from a pool of thousands. To help with this, many `list()` methods allow you to request fewer results via a process known as **paging**.

Methods that support paging return subsets of results in groups called *pages* . The maximum number of results per page is 1,000 (the default). You can change the number of results per page by setting the `maxResults`, and you can iterate through pages using the `nextPageToken` returned in the response:

### C#

```c#
// Limit the fields returned.
String fields = "nextPageToken,ads(advertiserId,id,name)";

AdsListResponse result;
String nextPageToken = null;

do {
  // Create and execute the ad list request.
  AdsResource.ListRequest request = service.Ads.List(profileId);
  request.Active = true;
  request.Fields = fields;
  request.PageToken = nextPageToken;
  result = request.Execute();

  foreach (Ad ad in result.Ads) {
    Console.WriteLine(
        "Ad with ID {0} and name \"{1}\" is associated with advertiser" +
        " ID {2}.", ad.Id, ad.Name, ad.AdvertiserId);
  }

  // Update the next page token.
  nextPageToken = result.NextPageToken;
} while (result.Ads.Any() && !String.IsNullOrEmpty(nextPageToken));
```

### Java

```java
// Limit the fields returned.
String fields = "nextPageToken,ads(advertiserId,id,name)";

AdsListResponse result;
String nextPageToken = null;

do {
  // Create and execute the ad list request.
  result = reporting.ads().list(profileId).setActive(true).setFields(fields)
      .setPageToken(nextPageToken).execute();

  for (Ad ad : result.getAds()) {
    System.out.printf(
        "Ad with ID %d and name \"%s\" is associated with advertiser ID %d.%n", ad.getId(),
        ad.getName(), ad.getAdvertiserId());
  }

  // Update the next page token.
  nextPageToken = result.getNextPageToken();
} while (!result.getAds().isEmpty() && !Strings.isNullOrEmpty(nextPageToken));
```

### PHP

```php
$response = null;
$pageToken = null;

do {
    // Create and execute the ads list request.
    $response = $this->service->ads->listAds(
        $values['user_profile_id'],
        ['active' => true, 'pageToken' => $pageToken]
    );

    foreach ($response->getAds() as $ads) {
        $this->printResultsTableRow($ads);
    }

    // Update the next page token.
    $pageToken = $response->getNextPageToken();
} while (!empty($response->getAds()) && !empty($pageToken));
```

### Python

```python
# Construct the request.
request = service.ads().list(profileId=str(profile_id), active=True)

while True:
  # Execute request and print response.
  response = request.execute()

  for ad in response['ads']:
    print('Found ad with ID %s and name "%s".' % (ad['id'], ad['name']))

  if response['ads'] and response['nextPageToken']:
    request = service.ads().list_next(request, response)
  else:
    break
```

### Ruby

```ruby
token = nil
loop do
  result = service.list_ads(profile_id,
    page_token: token,
    fields: 'nextPageToken,ads(id,name)')

  # Display results.
  if result.ads.any?
    result.ads.each do |ad|
      puts format('Found ad with ID %d and name "%s".', ad.id, ad.name)
    end

    token = result.next_page_token
  else
    # Stop paging if there are no more results.
    token = nil
  end

  break if token.to_s.empty?
end
```

## Generate floodlight tags

Floodlight tags are HTML tags embedded in a page, which are used to track user actions (e.g., purchases) within a site. To generate floodlight tags, you need a `FloodlightActivity`
that belongs to a `FloodlightActivityGroup`:

### C#

1. Create a new floodlight activity group, passing in values for `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups#name`, `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups#type`, and `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups#floodlightConfigurationId`.

   ```c#
   // Create the floodlight activity group.
   FloodlightActivityGroup floodlightActivityGroup = new FloodlightActivityGroup();
   floodlightActivityGroup.Name = groupName;
   floodlightActivityGroup.FloodlightConfigurationId = floodlightConfigurationId;
   floodlightActivityGroup.Type = "COUNTER";
   ```
2. Save the floodlight activity group by calling `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups/insert`, which will return the ID of the new group.

   ```c#
   // Insert the activity group.
   FloodlightActivityGroup result =
       service.FloodlightActivityGroups.Insert(floodlightActivityGroup, profileId).Execute();
   ```
3. Create a new floodlight activity, and assign it the ID of the floodlight activity group that you just created, as well as all other required fields.

   ```c#
   // Set floodlight activity structure.
   FloodlightActivity activity = new FloodlightActivity();
   activity.CountingMethod = "STANDARD_COUNTING";
   activity.Name = activityName;
   activity.FloodlightActivityGroupId = activityGroupId;
   activity.FloodlightTagType = "GLOBAL_SITE_TAG";
   activity.ExpectedUrl = url;
   activity.ConversionCategory = "CONVERSION_CATEGORY_PAGE_VIEW";
   ```
4. Save the new activity by calling `https://developers.google.com/doubleclick-advertisers/current/floodlightActivities/insert`, which will return the ID of the new activity.

   ```c#
   // Create the floodlight tag activity.
   FloodlightActivity result =
       service.FloodlightActivities.Insert(activity, profileId).Execute();
   ```
5. Generate the tags by calling `https://developers.google.com/doubleclick-advertisers/current/floodlightActivities/generatetag` with the `floodlightActivityId` of your new activity. Send the tags to the webmaster at the advertiser's website.

   ```c#
   // Generate the floodlight activity tag.
   FloodlightActivitiesResource.GeneratetagRequest request =
       service.FloodlightActivities.Generatetag(profileId);
   request.FloodlightActivityId = activityId;

   FloodlightActivitiesGenerateTagResponse response = request.Execute();
   ```

### Java

1. Create a new floodlight activity group, passing in values for `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups#name`, `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups#type`, and `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups#floodlightConfigurationId`.

   ```java
   // Create the floodlight activity group.
   FloodlightActivityGroup floodlightActivityGroup = new FloodlightActivityGroup();
   floodlightActivityGroup.setName(groupName);
   floodlightActivityGroup.setFloodlightConfigurationId(floodlightConfigurationId);
   floodlightActivityGroup.setType("COUNTER");
   ```
2. Save the floodlight activity group by calling `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups/insert`, which will return the ID of the new group.

   ```java
   // Insert the activity group.
   FloodlightActivityGroup result =
       reporting.floodlightActivityGroups().insert(profileId, floodlightActivityGroup).execute();
   ```
3. Create a new floodlight activity, and assign it the ID of the floodlight activity group that you just created, as well as all other required fields.

   ```java
   // Set floodlight activity structure.
   FloodlightActivity activity = new FloodlightActivity();
   activity.setName(activityName);
   activity.setCountingMethod("STANDARD_COUNTING");
   activity.setExpectedUrl(url);
   activity.setFloodlightActivityGroupId(activityGroupId);
   activity.setFloodlightTagType("GLOBAL_SITE_TAG");
   ```
4. Save the new activity by calling `https://developers.google.com/doubleclick-advertisers/current/floodlightActivities/insert`, which will return the ID of the new activity.

   ```java
   // Create the floodlight tag activity.
   FloodlightActivity result =
       reporting.floodlightActivities().insert(profileId, activity).execute();
   ```
5. Generate the tags by calling `https://developers.google.com/doubleclick-advertisers/current/floodlightActivities/generatetag` with the `floodlightActivityId` of your new activity. Send the tags to the webmaster at the advertiser's website.

   ```java
   // Generate the floodlight activity tag.
   Generatetag request = reporting.floodlightActivities().generatetag(profileId);
   request.setFloodlightActivityId(activityId);

   FloodlightActivitiesGenerateTagResponse response = request.execute();
   ```

### PHP

1. Create a new floodlight activity group, passing in values for `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups#name`, `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups#type`, and `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups#floodlightConfigurationId`.

   ```php
   $group = new Google_Service_Dfareporting_FloodlightActivityGroup();
   $group->setFloodlightConfigurationId($values['configuration_id']);
   $group->setName($values['group_name']);
   $group->setType('COUNTER');
   ```
2. Save the floodlight activity group by calling `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups/insert`, which will return the ID of the new group.

   ```php
   $result = $this->service->floodlightActivityGroups->insert(
       $values['user_profile_id'],
       $group
   );
   ```
3. Create a new floodlight activity, and assign it the ID of the floodlight activity group that you just created, as well as all other required fields.

   ```php
   $activity = new Google_Service_Dfareporting_FloodlightActivity();
   $activity->setCountingMethod('STANDARD_COUNTING');
   $activity->setExpectedUrl($values['url']);
   $activity->setConversionCategory($values['conversion_category']);
   $activity->setFloodlightActivityGroupId($values['activity_group_id']);
   $activity->setFloodlightTagType('GLOBAL_SITE_TAG');
   $activity->setName($values['activity_name']);
   ```
4. Save the new activity by calling `https://developers.google.com/doubleclick-advertisers/current/floodlightActivities/insert`, which will return the ID of the new activity.

   ```php
   $result = $this->service->floodlightActivities->insert(
       $values['user_profile_id'],
       $activity
   );
   ```
5. Generate the tags by calling `https://developers.google.com/doubleclick-advertisers/current/floodlightActivities/generatetag` with the `floodlightActivityId` of your new activity. Send the tags to the webmaster at the advertiser's website.

   ```php
   $result = $this->service->floodlightActivities->generatetag(
       $values['user_profile_id'],
       ['floodlightActivityId' => $values['activity_id']]
   );
   ```

### Python

1. Create a new floodlight activity group, passing in values for `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups#name`, `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups#type`, and `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups#floodlightConfigurationId`.

   ```python
   # Construct and save floodlight activity group.
   activity_group = {
       'name': 'Test Floodlight Activity Group',
       'floodlightConfigurationId': floodlight_config_id,
       'type': 'COUNTER'
   }
   ```
2. Save the floodlight activity group by calling `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups/insert`, which will return the ID of the new group.

   ```python
   request = service.floodlightActivityGroups().insert(
       profileId=str(profile_id), body=activity_group
   )
   ```
3. Create a new floodlight activity, and assign it the ID of the floodlight activity group that you just created, as well as all other required fields.

   ```python
   # Construct and save floodlight activity.
   floodlight_activity = {
       'countingMethod': 'STANDARD_COUNTING',
       'expectedUrl': 'http://www.google.com',
       'floodlightActivityGroupId': activity_group_id,
       'floodlightTagType': 'GLOBAL_SITE_TAG',
       'name': 'Test Floodlight Activity',
       'conversionCategory': 'CONVERSION_CATEGORY_PAGE_VIEW',
   }
   ```
4. Save the new activity by calling `https://developers.google.com/doubleclick-advertisers/current/floodlightActivities/insert`, which will return the ID of the new activity.

   ```python
   request = service.floodlightActivities().insert(
       profileId=str(profile_id), body=floodlight_activity
   )
   ```
5. Generate the tags by calling `https://developers.google.com/doubleclick-advertisers/current/floodlightActivities/generatetag` with the `floodlightActivityId` of your new activity. Send the tags to the webmaster at the advertiser's website.

   ```python
   # Construct the request.
   request = service.floodlightActivities().generatetag(
       profileId=str(profile_id), floodlightActivityId=str(activity_id)
   )

   # Execute request and print response.
   response = request.execute()
   ```

### Ruby

1. Create a new floodlight activity group, passing in values for `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups#name`, `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups#type`, and `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups#floodlightConfigurationId`.

   ```ruby
   # Create a new floodlight activity group resource to insert.
   activity_group =
     DfareportingUtils::API_NAMESPACE::FloodlightActivityGroup.new(
       floodlight_configuration_id: floodlight_config_id,
       name:
         format('Example Floodlight Activity Group #%s', SecureRandom.hex(3)),
       type: 'COUNTER'
     )
   ```
2. Save the floodlight activity group by calling `https://developers.google.com/doubleclick-advertisers/current/floodlightActivityGroups/insert`, which will return the ID of the new group.

   ```ruby
   # Insert the floodlight activity group.
   result = service.insert_floodlight_activity_group(profile_id, activity_group)
   ```
3. Create a new floodlight activity, and assign it the ID of the floodlight activity group that you just created, as well as all other required fields.

   ```ruby
   # Create a new floodlight activity resource to insert.
   activity = DfareportingUtils::API_NAMESPACE::FloodlightActivity.new(
     counting_method: 'STANDARD_COUNTING',
     expected_url: 'http://www.google.com',
     floodlight_activity_group_id: activity_group_id,
     floodlight_tag_type: 'GLOBAL_SITE_TAG',
     name: format('Example Floodlight Activity #%s', SecureRandom.hex(3)),
     conversion_category: 'CONVERSION_CATEGORY_PAGE_VIEW'
   )
   ```
4. Save the new activity by calling `https://developers.google.com/doubleclick-advertisers/current/floodlightActivities/insert`, which will return the ID of the new activity.

   ```ruby
   # Insert the floodlight activity.
   result = service.insert_floodlight_activity(profile_id, activity)
   ```
5. Generate the tags by calling `https://developers.google.com/doubleclick-advertisers/current/floodlightActivities/generatetag` with the `floodlightActivityId` of your new activity. Send the tags to the webmaster at the advertiser's website.

   ```ruby
   # Construct the request.
   result = service.generatetag_floodlight_activity(profile_id,
     floodlight_activity_id: activity_id)
   ```

## Generate placement tags

The last step is generating HTML tags to send to the publisher in order to display your ads. To generate the tags via the API, make a request to `https://developers.google.com/doubleclick-advertisers/current/placements/generatetags`, specifying a set of `placementIds` and `tagFormats`.

### C#

```c#
// Generate the placement activity tags.
PlacementsResource.GeneratetagsRequest request =
    service.Placements.Generatetags(profileId);
request.CampaignId = campaignId;
request.TagFormats =
    PlacementsResource.GeneratetagsRequest.TagFormatsEnum.PLACEMENTTAGIFRAMEJAVASCRIPT;
request.PlacementIds = placementId.ToString();

PlacementsGenerateTagsResponse response = request.Execute();
```

### Java

```java
// Generate the placement activity tags.
Generatetags request = reporting.placements().generatetags(profileId);
request.setCampaignId(campaignId);
request.setTagFormats(tagFormats);
request.setPlacementIds(ImmutableList.of(placementId));

PlacementsGenerateTagsResponse response = request.execute();
```

### PHP

```php
$placementTags = $this->service->placements->generatetags(
    $values['user_profile_id'],
    ['campaignId' => $values['campaign_id'],
     'placementIds' => [$values['placement_id']],
     'tagFormats' => ['PLACEMENT_TAG_STANDARD',
                      'PLACEMENT_TAG_IFRAME_JAVASCRIPT',
                      'PLACEMENT_TAG_INTERNAL_REDIRECT']
    ]
);
```

### Python

```python
# Construct the request.
request = service.placements().generatetags(
    profileId=str(profile_id),
    campaignId=str(campaign_id),
    placementIds=[placement_id],
)

# Execute request and print response.
response = request.execute()
```

### Ruby

```ruby
# Construct the request.
result = service.generate_placement_tags(profile_id,
  campaign_id: campaign_id,
  placement_ids: [placement_id])
```