Hide

Making Your First Request

This tutorial demonstrates how to connect to CampaignService and add a new campaign in different languages. Client libraries for other popular programming languages are also available, each bundled with installation instructions and a variety of code examples.

Java

Here is a basic example showing how to add a campaign in Java.

  1. Set up your credentials.

    First, you need to set up your configuration file ads.properties properly. See the OAuth2 wiki page for details. Your ads.properties file will look like this:

    [...]
    api.adwords.developerToken=123axxxxxxxxxxxxxxxxxx
    api.adwords.clientId=xxxxxxxxxx.apps.googleusercontent.com
    api.adwords.clientSecret=zZxxxxxTxxxxxxxxxxx
    api.adwords.refreshToken=1/dyOIp7ki-xxxxxxxxxxxxxxxxxxxxxxxx
    [...]
    

    All calls to the API require an access token, which you specify using the Authorization HTTP header. An access token is valid for one hour only. When it expires, you need to refresh the access token by retrieving a new one. However, to make it simple for the developer to use the API, our client libraries automatically refresh expired access tokens using a utility class like in this code snippet:

    // Construct an OAuth2 credential.
    Credential oAuth2Credential = new OfflineCredentials.Builder()
        .forApi(Api.ADWORDS)
        .fromFile()
        .build()
        .generateCredential();
    

    You can then create your AdWordsSession using the Builder pattern:

    // Construct an AdWordsSession.
    AdWordsSession session = new AdWordsSession.Builder()
        .fromFile()
        .withOAuth2Credential(oAuth2Credential)
        .build();
    

    Credentials and properties in fromFile() are pulled from the ads.properties file. See the README for more information.

  2. Create a CampaignService.

    You will need a SOAP Client Stub to make calls to the API. The AdWordsServices class handles this logic. This object is expensive to construct so instantiate it once and reuse as much as possible within a thread.

    // Construct a AdWords service factory, which can only be used once per thread,
    // but should be reused as much as possible.
    AdWordsServices adWordsServices = new AdWordsServices();

    You can then obtain a reference to the service class like so:

    // Get the CampaignService.
    CampaignServiceInterface campaignService =
         adWordsServices.get(session, CampaignServiceInterface.class);
  3. Add a Budget.

    You must supply a budget ID to the campaign, so let's create and add a new budget.

    // Get the BudgetService.
    BudgetServiceInterface budgetService =
        adWordsServices.get(session, BudgetServiceInterface.class);
    
    // Create a budget, which can be shared by multiple campaigns.
    Budget sharedBudget = new Budget();
    sharedBudget.setName("Interplanetary Cruise #" + System.currentTimeMillis());
    Money budgetAmount = new Money();
    budgetAmount.setMicroAmount(50000000L);
    sharedBudget.setAmount(budgetAmount);
    sharedBudget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD);
    sharedBudget.setPeriod(BudgetBudgetPeriod.DAILY);
    
    BudgetOperation budgetOperation = new BudgetOperation();
    budgetOperation.setOperand(sharedBudget);
    budgetOperation.setOperator(Operator.ADD);
    
    // Execute the new budget operation and save the assigned budget ID.
    Long budgetId =
        budgetService.mutate(new BudgetOperation[] {budgetOperation}).getValue(0).getBudgetId();
  4. Create a Campaign.

    Once you are ready to create the Campaign object, you can specify the campaign name, status, advertising channel type, bidding strategy configuration, and budget ID.

    Campaign campaign = new Campaign();
    campaign.setName("Interplanetary Cruise #" + System.currentTimeMillis());
    campaign.setStatus(CampaignStatus.PAUSED);
    campaign.setAdvertisingChannelType(AdvertisingChannelType.SEARCH);
    
    // Set the bidding strategy configuration.
    BiddingStrategyConfiguration biddingStrategyConfiguration =
        new BiddingStrategyConfiguration();
    biddingStrategyConfiguration.setBiddingStrategyType(BiddingStrategyType.MANUAL_CPC);
    campaign.setBiddingStrategyConfiguration(biddingStrategyConfiguration);
    
    // Only the budgetId should be sent.
    Budget budget = new Budget();
    budget.setBudgetId(budgetId);
    campaign.setBudget(budget);
  5. Create an operation.

    Next, create a campaign operation which encapsulates the operator (ADD) and operand (your new campaign), and then an operations[] array containing this element. As the array implies, you can send multiple operations in a single request.

    CampaignOperation operation = new CampaignOperation();
    operation.setOperand(campaign);
    operation.setOperator(Operator.ADD);
    CampaignOperation[] operations = new CampaignOperation[] {operation};
  6. Send the request.

    Finally, you are ready to send the campaign to the server using the mutate method:

    CampaignReturnValue result = campaignService.mutate(operations);

    You can view the results of the campaign operation with the following code:

    if (result != null && result.getValue() != null) {
      for (Campaign campaignResult : result.getValue()) {
        System.out.println("Campaign with name \""
            + campaignResult.getName() + "\" and id \""
            + campaignResult.getId() + "\" was added.");
      }
    } else {
      System.out.println("No campaigns were added.");
    }
Perl

Here is a basic example showing how to add a campaign in Perl.

  1. Set up your credentials.

    First, you need to set up your configuration file adwords.properties properly in your home directory. See the OAuth2 wiki page for details. Your adwords.properties file will look like this:

    [...]
    developerToken=123axxxxxxxxxxxxxxxxxx
    oAuth2ClientId=xxxxxxxxxx.apps.googleusercontent.com
    oAuth2ClientSecret=zZxxxxxTxxxxxxxxxxx
    oAuth2RefreshToken=1/dyOIp7ki-xxxxxxxxxxxxxxxxxxxxxxxx
    [...]
    
  2. Initialize your Client.

    All calls to the API require an access token. An access token is valid for one hour only. When it expires, you need to refresh the access token by retrieving a new one. However, to make it simple for the developer, the Client object takes care of this automatically.

    # Create AdWords Client. Credentials will be read from ~/adwords.properties.
    my $client = Google::Ads::AdWords::Client->new();
    
  3. Create a CampaignService.

    You will need a SOAP Client Stub to make calls to the API. The Client object handles this logic.

    my $campaign_service = $client->CampaignService();
  4. Add a Budget.

    You must supply a budget ID to the campaign, so let's create and add a new budget.

    my $budget = Google::Ads::AdWords::v201409::Budget->new({
        # Required attributes.
        name => "Interplanetary budget #" . uniqid(),
        amount => Google::Ads::AdWords::v201409::Money->new({
            microAmount => 5000000
        }),
        deliveryMethod => "STANDARD",
        period => "DAILY"
    });
    
    my $budget_operation = Google::Ads::AdWords::v201409::BudgetOperation->new({
        operator => "ADD",
        operand => $budget
    });
    
    # Execute the new budget operation and save the assigned budget ID.
    my $budget_add_result = $client->BudgetService()->mutate({
        operations => ($budget_operation)
    });
    
    my $budgetId = $budget_add_result->get_value()->get_budgetId()->get_value();
  5. Create a Campaign.

    Once you are ready to create the Campaign object, you can specify the campaign name, status, advertising channel type, bidding strategy configuration, and budget ID.

    my $campaign = Google::Ads::AdWords::v201409::Campaign->new({
        name =>  "Interplanetary Cruise #" . uniqid(),
        # Bidding strategy (required).
        biddingStrategyConfiguration =>
            Google::Ads::AdWords::v201409::BiddingStrategyConfiguration->new({
                biddingStrategyType => "MANUAL_CPC",
            }),
        # Budget (required) - note only the budgetId is required.
        budget => Google::Ads::AdWords::v201409::Budget->new({
            budgetId => $budgetId
        }),
        # Advertising channel type (required).
        advertisingChannelType => "SEARCH",
        # Additional properties (non-required).
        status => "PAUSED"
    });
  6. Create an operation.

    Next, create a campaign operation which encapsulates the operator (ADD) and operand (your new campaign), and then an @operations array containing this element. As the array implies, you can send multiple operations in a single request.

    # Create operation.
    my $campaign_operation =
        Google::Ads::AdWords::v201409::CampaignOperation->new({
            operator => "ADD",
            operand => $campaign
        });
    my @operations = ($campaign_operation);
  7. Send the request.

    Finally, you are ready to send the campaign to the server using the mutate method:

    # Add campaigns.
    my $result = $campaign_service->mutate({
        operations => \@operations
    });

    You can view the results of the campaign operation with the following code:

    foreach my $campaign (@{$result->get_value()}) {
        printf "Campaign with name \"%s\" and id \"%s\" was added.\n",
            $campaign->get_name(), $campaign->get_id();
    }
PHP

Here is a basic example showing how to add a campaign in PHP.

  1. Set up credentials.

    First, you need to set up your configuration file auth.ini properly. See the OAuth2 wiki page for details. Your auth.ini file will look like this:

    [...]
    developerToken = "INSERT_DEVELOPER_TOKEN_HERE"
    userAgent = "INSERT_COMPANY_NAME_HERE"
    clientCustomerId = "INSERT_CLIENT_CUSTOMER_ID_HERE"
    
    client_id = "INSERT_OAUTH2_CLIENT_ID_HERE"
    client_secret = "INSERT_OAUTH2_CLIENT_SECRET_HERE"
    refresh_token = "INSERT_OAUTH2_REFRESH_TOKEN_HERE"
    [...]
    
  2. Initialize AdWordsUser.

    All calls to the API require an access token. An access token is valid for one hour only. When it expires, you need to refresh the access token by retrieving a new one. However, to make it simple for the developer, the AdWordsUser object takes care of this automatically.

    $user = new AdWordsUser();
    
  3. Create CampaignService.

    You will need a SOAP Client Stub to make calls to the API. The AdWordsUser class handles this logic.

    // Get the CampaignService.
    $campaignService = $user->GetService('CampaignService');
    
  4. Create Budget.

    You must supply a budget ID to the campaign, so let's create and add a new budget.

    // Get the BudgetService, which loads the required classes.
    $budgetService = $user->GetService('BudgetService', ADWORDS_VERSION);
    
    // Create the shared budget (required).
    $budget = new Budget();
    $budget->name = 'Interplanetary Cruise Budget #' . uniqid();
    $budget->period = 'DAILY';
    $budget->amount = new Money(50000000);
    $budget->deliveryMethod = 'STANDARD';
    
    $operations = array();
    
    // Create operation.
    $operation = new BudgetOperation();
    $operation->operand = $budget;
    $operation->operator = 'ADD';
    $operations[] = $operation;
    
    // Make the mutate request.
    $result = $budgetService->mutate($operations);
    
    // The newly created budget that has the ID
    $budget = $result->value[0];
    
  5. Create Campaign.

    Once you are ready to create the Campaign object, you can specify the campaign name, status, bidding strategy, and budget ID.

    // Create campaign.
    $campaign = new Campaign();
    $campaign->name = 'Interplanetary Cruise #' . uniqid();
    $campaign->advertisingChannelType = 'SEARCH';
    
    // Set shared budget (required).
    $campaign->budget = new Budget();
    $campaign->budget->budgetId = $budget->budgetId;
    
    // Set bidding strategy (required).
    $biddingStrategyConfiguration = new BiddingStrategyConfiguration();
    $biddingStrategyConfiguration->biddingStrategyType = 'MANUAL_CPC';
    
    $campaign->biddingStrategyConfiguration = $biddingStrategyConfiguration;
    
  6. Create operation.

    Next, create a campaign operations, which encapsulates the operator (ADD) and the operand (your new campaign), and then an operations[] array containing this element. As the array implies, you can send multiple operations in a single request.

    $operations = array();
    
    // Create operation.
    $operation = new CampaignOperation();
    $operation->operand = $campaign;
    $operation->operator = 'ADD';
    $operations[] = $operation;
    
  7. Send request.

    Finally, you are ready to send the operation to the server using the mutate method:

    $result = $campaignService->mutate($operations);
    

    You can view the results of the campaign operation with the following code:

    // Display results.
    foreach ($result->value as $campaign) {
      printf("Campaign with name '%s' and ID '%s' was added.\n",
          $campaign->name, $campaign->id);
    }
    
Python

Here is a basic example of how to add a campaign in Python.

  1. Set up your credentials.

    First, you need to populate the templated fields in the googleads.yaml file:

    adwords:
      developer_token: 123axxxxxxxxxxxxxxxxxx
      user_agent: Company_Name
      client_id: xxxxxxxxxx.apps.googleusercontent.com
      client_secret: zZxxxxxTxxxxxxxxxxx
      refresh_token: 1/dyOIp7ki-xxxxxxxxxxxxxxxxxxxxxxxx
    [...]
  2. Initialize the AdWordsClient object.

    You can retrieve a fully initialized AdWordsClient by calling the LoadFromStorage method, which will automatically pull your credentials stored in googleads.yaml. Alternatively, you could initialize AdWordsClient yourself and provide all of these credentials manually.

    from googleads.adwords import AdWordsClient
    client = AdWordsClient.LoadFromStorage()

    All calls to the API require an access token. An access token is valid for one hour only. When it expires, you need to refresh the access token by retrieving a new one. However, to make it simple for the developer, the AdWordsClient object takes care of this automatically.

  3. Set up the connection to CampaignService.

    Before sending any requests to the AdWords API, you must first establish a connection to the web service you plan to use. In this example, we connect to CampaignService.

    campaign_service = client.GetService('CampaignService', version=API_VERSION)

    After you've established a connection to CampaignService, you can start performing operations.

  4. Make a budget.

    You'll need to supply a budgetId when creating a campaign, so let's first create a budget:

    budget_service = client.GetService('BudgetService', version=API_VERSION)
    
    # Create a budget, which can be shared by multiple campaigns.
    budget = {
        'name': 'Interplanetary budget #%s' % uuid.uuid4(),
        'amount': {
            'microAmount': '50000000'
        },
        'deliveryMethod': 'STANDARD',
        'period': 'DAILY'
    }
    
    budget_operations = [{
        'operator': 'ADD',
        'operand': budget
    }]
    
    # Add the budget.
    budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId']
  5. Add a new campaign.

    Now it's time to construct an operation that adds a campaign:

    operations = [{
        'operator': 'ADD',
        'operand': {
            'name': 'Interplanetary Cruise #%s' % uuid.uuid4(),
            'status': 'PAUSED',
            'advertisingChannelType': 'SEARCH',
            'biddingStrategyConfiguration': {
                'biddingStrategyType': 'MANUAL_CPC',
            },
            'endDate': (datetime.datetime.now() +
                        datetime.timedelta(365)).strftime('%Y%m%d'),
            'budget': {
                'budgetId': budget_id
            },
            'networkSetting': {
                'targetGoogleSearch': 'true',
                'targetSearchNetwork': 'true',
                'targetContentNetwork': 'false',
                'targetPartnerSearchNetwork': 'false'
            }
        }
    }]

    Finally, send the request to CampaignService. The mutate operation returns the results of the operations performed on the specified campaigns.

    campaigns = campaign_service.mutate(operations)
    
    # Display results.
    for campaign in campaigns['value']:
      print ('Campaign with name \'%s\' and id \'%s\' was added.'
             % (campaign['name'], campaign['id']))
    
Ruby

Here is a basic example showing how to add a campaign in Ruby.

  1. Set up your credentials.

    First you need to set up your configuration file adwords_api.yml properly. See the README wiki page for details. Your adwords_api.yml file will look like this:

    [...]
    :oauth2_client_id: xxxxxxxxxx.apps.googleusercontent.com
    :oauth2_client_secret: zZxxxxxTxxxxxxxxxxx
    :oauth2_token:
      :refresh_token: 1/dyOIp7ki-xxxxxxxxxxxxxxxxxxxxxxxx
    [...]
    

    All calls to the API require an access token, which you specify using the Authorization HTTP header. An access token is valid for one hour only. When it expires, you need to refresh the access token by retrieving a new one. However, to make it simple for the developer to use the API, our client libraries automatically refresh expired access tokens like in this code snippet:

    require 'adwords_api'
    
    adwords = AdwordsApi::Api.new
    token = adwords.authorize()
    

    By default, the client library code will look for the adwords_api.yml file in the home directory. See the README for more details.

  2. Create a CampaignService.

    You will need a SOAP Client Stub to make calls to the API. The AdwordsApi::Api class handles this logic. You can then obtain a reference to the service class like so:

    // Get the CampaignService.
    campaign_srv = adwords.service(:CampaignService, API_VERSION)

    API_VERSION would be a symbol like :v201506.

  3. Add a Budget.

    You must supply a budget ID to the campaign, so let's create and add a new budget.

    # Create a budget, which can be shared by multiple campaigns.
    budget = {
      :name => 'Interplanetary budget #%d' % (Time.new.to_f * 1000).to_i,
      :amount => {:micro_amount => 50000000},
      :delivery_method => 'STANDARD',
      :period => 'DAILY'
    }
    budget_operation = {:operator => 'ADD', :operand => budget}
    
    # Execute the new budget operation and save the assigned budget ID.
    return_budget = budget_srv.mutate([budget_operation])
    budget_id = return_budget[:value].first[:budget_id]
  4. Create a Campaign.

    Once you are ready to create the Campaign object, you can specify the campaign name, status, bidding strategy, and budget ID.

    campaign = {
      :name => "Interplanetary Cruise #%d" % (Time.new.to_f * 1000).to_i,
      :status => 'PAUSED',
      :bidding_strategy_configuration => {
        :bidding_strategy_type => 'MANUAL_CPC'
      },
      :budget => {:budget_id => budget_id}
    }
  5. Create an operation request.

    Next, create a campaign operations, which encapsulates the operator (ADD) and the operand (your new campaign), and then an operations array containing this element. As the array implies, you can send multiple operations in a single request.

    operations = [
      {:operator => 'ADD', :operand => campaign}
    ]
  6. Send the request.

    Finally, you are ready to send the campaign to the server using the mutate method:

    response = campaign_srv.mutate(operations)

    You can view the results of the campaign operation with the following code:

    if response and response[:value]
      response[:value].each do |campaign|
        puts "Campaign with name '%s' and ID %d was added." %
            [campaign[:name], campaign[:id]]
      end
    else
      raise new StandardError, 'No campaigns were added.'
    end
.NET

Here is a basic example showing how to add a campaign in C#.

  1. Set up App.config

    The AdWords API .NET client library reads its configuration from your application’s App.config / Web.config by default.

    1. Set your OAuth2 credentials

      First, you need to obtain an OAuth2 client ID and secret. See this wiki article on how to obtain one.

      Next, you need to generate a refresh token using those credentials. The AdWords API .NET client library distribution provides a utility application named OAuthTokenGenerator.exe to help you generate a refresh token. See this wiki article for details on how to use this application.

    2. Set your AdWords API settings in App.config

      You need to set your developer token, a user agent string for your application, and client customer Id in your application’s App.config. If you don’t have a developer token, see this guide on how to sign up for the AdWords API and get one.

      Once you have configured App.config, it would look like this:

      <?xml version="1.0" encoding="utf-8" ?>
      <configuration>
        <configSections>
          <section name="AdWordsApi"
              type="System.Configuration.DictionarySectionHandler"/>
        </configSections>
        <AdWordsApi>
          <!-- Settings specific to AdWords API.-->
          <add key="UserAgent" value="My AdWords API application"/>
          <add key="DeveloperToken" value="xxxxxxxxxxxxxxxxxxxxxx"/>
          <add key="ClientCustomerId" value="123-456-7890"/>
      
          <!-- OAuth2 configuration -->
          <add key="AuthorizationMethod" value="OAuth2" />
          <add key="OAuth2ClientId" value="xxxxxxxxxx.apps.googleusercontent.com" />
          <add key="OAuth2ClientSecret" value="zZxxxxxTxxxxxxxxxxx" />
          <add key="OAuth2Mode" value="APPLICATION" />
          <add key="OAuth2RefreshToken" value="1/dyOIp7ki-xxxxxxxxxxxxxxxxxxxxx" />
        </AdWordsApi>
      </configuration>
      
  2. Create an AdWordsUser

    You need to create an AdWordsUser object, as follows:

    AdWordsUser user = new AdWordsUser();
    

    The user object now represents the AdWords account you want to make API calls to. You should reuse this object in a single thread when possible. Avoid sharing AdWordsUser instances among multiple threads since settings changes you make in one thread can inadvertently affect settings in other threads.

  3. Create a CampaignService

    You will need a SOAP client stub to make calls to the API. This is constructed using the AdWordsUser class:

    // Get the CampaignService.
    CampaignService campaignService =
        (CampaignService) user.GetService(AdWordsService.v201506.CampaignService);
    
  4. Add a budget

    You must supply a budget ID to the campaign, so let's create and add a new budget:

    // Get the BudgetService.
    BudgetService budgetService =
         (BudgetService) user.GetService(AdWordsService.v201506.BudgetService);
    
    // Create the campaign budget.
    Budget budget = new Budget();
    budget.name = "My first campaign budget";
    budget.period = BudgetBudgetPeriod.DAILY;
    budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD;
    budget.amount = new Money();
    budget.amount.microAmount = 500000;
    
    BudgetOperation budgetOperation = new BudgetOperation();
    budgetOperation.@operator = Operator.ADD;
    budgetOperation.operand = budget;
    
    BudgetReturnValue budgetRetval = budgetService.mutate(
        new BudgetOperation[] {budgetOperation});
    budget = budgetRetval.value[0];
    
  5. Create a campaign

    Once you are ready to create the Campaign object, you can specify the campaign name, status, bidding strategy, and budget ID.

    // Create the campaign.
    Campaign campaign = new Campaign();
    campaign.name = "My first campaign";
    campaign.status = CampaignStatus.PAUSED;
    campaign.advertisingChannelType = AdvertisingChannelType.SEARCH;
    
    BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
    biddingConfig.biddingStrategyType = BiddingStrategyType.MANUAL_CPC;
    campaign.biddingStrategyConfiguration = biddingConfig;
    
    campaign.budget = new Budget();
    campaign.budget.budgetId = budget.budgetId;
    
    // Set the campaign network options.
    campaign.networkSetting = new NetworkSetting();
    campaign.networkSetting.targetGoogleSearch = true;
    campaign.networkSetting.targetSearchNetwork = true;
    campaign.networkSetting.targetContentNetwork = false;
    campaign.networkSetting.targetPartnerSearchNetwork = false;
    
    // Set the campaign settings for Advanced location options.
    GeoTargetTypeSetting geoSetting = new GeoTargetTypeSetting();
    geoSetting.positiveGeoTargetType = GeoTargetTypeSettingPositiveGeoTargetType.DONT_CARE;
    geoSetting.negativeGeoTargetType = GeoTargetTypeSettingNegativeGeoTargetType.DONT_CARE;
    
    campaign.settings = new Setting[] {geoSetting, keywordSetting};
    
    // Optional: Set the start date.
    campaign.startDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd");
    
    // Optional: Set the end date.
    campaign.endDate = DateTime.Now.AddYears(1).ToString("yyyyMMdd");
    
    // Optional: Set the campaign ad serving optimization status.
    campaign.adServingOptimizationStatus = AdServingOptimizationStatus.ROTATE;
    
    // Optional: Set the frequency cap.
    FrequencyCap frequencyCap = new FrequencyCap();
    frequencyCap.impressions = 5;
    frequencyCap.level = Level.ADGROUP;
    frequencyCap.timeUnit = TimeUnit.DAY;
    campaign.frequencyCap = frequencyCap;
    
  6. Construct the operation

    Next, create a campaign operation, which encapsulates the operator (ADD) and the operand (your new Campaign), and then a CampaignOperation array containing this element.

    // Create the operation.
    CampaignOperation operation = new CampaignOperation();
    operation.@operator = Operator.ADD;
    operation.operand = campaign;
    CampaignOperation[] operations = new CampaignOperation[] {operation};
    
  7. Add the campaign

    Finally, you are ready to send the campaign to the server using the mutate method:

    // Add the campaign.
    CampaignReturnValue retVal = campaignService.mutate(operations);
    

    You can view the results of the campaign operation with the following code:

    // Display the results.
    if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
      foreach (Campaign newCampaign in retVal.value) {
        Console.WriteLine("Campaign with name = '{0}' and id = '{1}' was added.",
            newCampaign.name, newCampaign.id);
      }
    } else {
      Console.WriteLine("No campaigns were added.");
    }
    

Congratulations on making your first request!

Send feedback about...

AdWords API