Part 7 - Create a Campaign

In this part we're going to rewrite the logic that creates a campaign with the AdWords API so that it uses the Google Ads API.

To migrate the _create_campaign method we'll follow the same steps as for creating a budget. First update the call to _create_campaign to pass in the Google Ads client and a budget, and to return a campaign entity:

7.0.0: Updating the Call to _create_campaign (Google Ads API)
campaign = _create_campaign(googleads_client, budget)
      

Next, update the method signature to rename the budget_id parameter to just budget:

7.0.1: Updating the _create_campaign Method Signature (Google Ads API)
def _create_campaign(client, budget):
      

Lastly, update the call to _create_ad_group so that it isn’t broken by the changes in this section:

7.0.2: Updating the Call to _create_ad_group (AdWords API)
ad_group_id = _create_ad_group(adwords_client, campaign.id)
      

Part 7.1 - Retrieve the necessary service client

The AdWords API client library uses the CampaignService, and using the map of AdWords services to Google Ads services we can see that the Google Ads API client library should use a service with the same name:

7.1.0: Retrieving the CampaignService (AdWords API)
campaign_service = client.GetService("CampaignService", version="v201809")
      

should be changed to:

7.1.1: Retrieving the CampaignService (Google Ads API)
campaign_service = client.get_service("CampaignService")
      

Part 7.2 - Create and configure a mutate operation

7.2.0: Initializing and Configuring a Campaign Operation (AdWords API)
campaign = {
    "name": "Interplanetary Cruise #{}".format(uuid.uuid4()),
    "advertisingChannelType": "SEARCH",
    # Recommendation: Set the campaign to PAUSED when creating it to stop the
    # ads from immediately serving. Set to ENABLED once you've added
    # targeting and the ads are ready to serve.
    "status": "PAUSED",
    "biddingStrategyConfiguration": {
        "biddingStrategyType": "MANUAL_CPC",
    },
    "startDate": (datetime.datetime.now() + datetime.timedelta(1)).strftime(
        "%Y%m%d"
    ),
    "endDate": (datetime.datetime.now() + datetime.timedelta(365)).strftime(
        "%Y%m%d"
    ),
    # Budget (required) - note only the budget ID is required.
    "budget": {"budgetId": budget_id},
    "networkSetting": {
        "targetGoogleSearch": "true",
        "targetSearchNetwork": "true",
    },
}
campaign_operations = [{"operator": "ADD", "operand": campaign}]
      

should be changed to:

7.2.1: Initializing and Configuring a CampaignOperation (Google Ads API)
operation = client.get_type("CampaignOperation")
campaign = operation.create
campaign_service = client.get_service("CampaignService")
campaign.name = f"Interplanetary Cruise#{uuid.uuid4()}"
campaign.advertising_channel_type = (
    client.enums.AdvertisingChannelTypeEnum.SEARCH
)
# Recommendation: Set the campaign to PAUSED when creating it to stop # the ads from immediately serving. Set to ENABLED once you've added
# targeting and the ads are ready to serve.
campaign.status = client.enums.CampaignStatusEnum.PAUSED
campaign.manual_cpc.enhanced_cpc_enabled = True
campaign.campaign_budget = budget.resource_name
campaign.network_settings.target_google_search = True
campaign.network_settings.target_search_network = True
campaign.network_settings.target_content_network = False
campaign.network_settings.target_partner_search_network = False
# The format used for the below dates evaluates to 2021-08-18.
campaign.start_date = (
    datetime.datetime.now() + datetime.timedelta(1)
).strftime("%Y-%m-%d")
campaign.end_date = (
    datetime.datetime.now() + datetime.timedelta(365)
).strftime("%Y-%m-%d")
      

Part 7.3 - Send the operation to the API in a mutate request

7.3.0: Submitting a Campaign Mutate Request (AdWords API)
results = campaign_service.mutate(campaign_operations)
      

should be changed to:

7.3.1: Submitting a Campaign Mutate Request (Google Ads API)
response = campaign_service.mutate_campaigns(
    customer_id=_CUSTOMER_ID, operations=[operation]
)
      

Part 7.4 - Get information about the object

Start by retrieving the campaign's resource name:

7.4.0: Parsing a Campaign Mutate Response (AdWords API)
created_campaign = results["value"][0]
      

should be changed to:

7.4.1: Parsing a Campaign Mutate Response (Google Ads API)
campaign_resource_name = response.results[0].resource_name
      

Then use the _search_google_ads method with the below query to retrieve and return the campaign:

7.4.2: Using Google Ads API Reporting to Retrieve the Full Campaign Object
query = f"""
    SELECT
      campaign.id,
      campaign.name,
      campaign.resource_name
    FROM campaign
    WHERE campaign.resource_name = '{resource_name}'"""

googleads_row = _search_google_ads(client, query)

return googleads_row.campaign
      

Part 7.5 - Finished _create_campaign method

7.5.0: Complete _create_campaign Method (Google Ads API)
def _create_campaign(client, budget):
    """Creates a new campaign and returns a subset of its fields.

    Only the fields selected in the below GAQL query will be present on
    the returned campaign.

    Args:
        client: An instance of the GoogleAdsClient class.
        budget: A CampaignBudget instance.

    Returns:
        (Campaign) The newly created campaign with a subset of its fields.
    """
    campaign_service = client.get_service("CampaignService")

    operation = client.get_type("CampaignOperation")
    campaign = operation.create
    campaign_service = client.get_service("CampaignService")
    campaign.name = f"Interplanetary Cruise#{uuid.uuid4()}"
    campaign.advertising_channel_type = (
        client.enums.AdvertisingChannelTypeEnum.SEARCH
    )
    # Recommendation: Set the campaign to PAUSED when creating it to stop
    # the ads from immediately serving. Set to ENABLED once you've added
    # targeting and the ads are ready to serve.
    campaign.status = client.enums.CampaignStatusEnum.PAUSED
    campaign.manual_cpc.enhanced_cpc_enabled = True
    campaign.campaign_budget = budget.resource_name
    campaign.network_settings.target_google_search = True
    campaign.network_settings.target_search_network = True
    campaign.network_settings.target_content_network = False
    campaign.network_settings.target_partner_search_network = False
    campaign.start_date = (
        datetime.datetime.now() + datetime.timedelta(1)
    ).strftime("%Y%m%d")
    campaign.end_date = (
        datetime.datetime.now() + datetime.timedelta(365)
    ).strftime("%Y%m%d")

    response = campaign_service.mutate_campaigns(
        customer_id=_CUSTOMER_ID, operations=[operation]
    )

    resource_name = response.results[0].resource_name

    query = f"""
        SELECT
          campaign.id,
          campaign.name,
          campaign.resource_name
        FROM campaign
        WHERE campaign.resource_name = '{resource_name}'"""

    googleads_row = _search_google_ads(client, query)

    return googleads_row.campaign
      

Run the script to ensure everything is still working as expected:

python create_complete_campaign_adwords_api_only.py