AdWords API

Making Your First Request

This tutorial demonstrates how to connect to CampaignService and add a new campaign in both Java and Python. 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.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 AdWordsSession from 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.

    // 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);
    
    // Add the budget
    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, bidding strategy, keyword match setting, and budget ID.

    Campaign campaign = new Campaign();
    campaign.setName("Interplanetary Cruise #" + System.currentTimeMillis());
    campaign.setStatus(CampaignStatus.PAUSED);
    campaign.setBiddingStrategy(new ManualCPC());
    
    // Set required keyword match setting.
    KeywordMatchSetting keywordMatch = new KeywordMatchSetting();
    keywordMatch.setOptIn(Boolean.FALSE);
    campaign.setSettings(new Setting[] {keywordMatch});
    
    // Only the budgetId should be sent.
    Budget budget = new Budget();
    budget.setBudgetId(budgetId);
    campaign.setBudget(budget);
  5. Create the operation to perform.

    Next, create a campaign operations, which encapsulates the operator (ADD) and the operand (your new campaign), and then an operations[] array containing this element.

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

    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.");
    }
Python

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

  1. Initialize the AdWordsClient object.

    The AdWordsClient is initialized with the path to the data file containing your authentication information and developer token. Alternatively, you can provide this info as part of the headers parameter to the Client.

    from googleads.adwords import AdWordsClient
    import googleads.common
    client = AdWordsClient(path=os.path.join('..', '..', '..', '..'))
  2. 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.GetCampaignService(version='[latest_version]')

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

  3. Make a budget.

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

    budget_service = client.GetBudgetService(version='[latest_version]')
    
    # Create a budget, which can be shared by multiple campaigns.
    budget = {
        'name': 'Interplanetary budget #%s' % Utils.GetUniqueName(),
        'amount': {
            'microAmount': '50000000'
        },
        'deliveryMethod': 'STANDARD',
        'period': 'DAILY'
    }
    
    budget_operations = [{
        'operator': 'ADD',
        'operand': budget
    }]
    
    # Add the budget.
    budget_id = budget_service.Mutate(budget_operations)[0]['value'][0]['budgetId']
  4. Add a new campaign.

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

    operations = [{
        'operator': 'ADD',
        'operand': {
            'name': 'Interplanetary Cruise #%s' % Utils.GetUniqueName(),
            'status': 'PAUSED',
            'biddingStrategyConfiguration': {
                'biddingStrategyType': 'MANUAL_CPC'
            },
            'endDate': '20180101',
            'budget': {
                'budgetId': budget_id
            },
            'settings': [{
                'xsi_type': 'KeywordMatchSetting',
                'optIn': '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)[0]
    
    # Display results.
    for campaign in campaigns['value']:
      print ('Campaign with name \'%s\' and id \'%s\' was added.'
             % (campaign['name'], campaign['id']))
    
    print
    print ('Operations: %s operations' % (client.GetOperations()))

Congratulations on making your first request!

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.