The goal of this tutorial is to help you create a real, working AdWords API program. The program will be basic, but will use the same building blocks found in the most advanced implementations. Afterwards, you'll be able to turn your program into a full-fledged implementation of your own.
We're going to start by creating a campaign, an ad group, a creative, and a keyword — the essentials of an AdWords campaign. Then, we'll retrieve information about each of those objects. Later, we'll touch on some more advanced functionality, like generating a report of the sort you might run to find out how your account is performing.
Before You Start
We've designed the tutorial to accommodate as many programming environments as possible. In the upper-right corner, you'll find a drop-down menu with a number of programming languages. Go ahead and pick the langauge you'd like to use. We'll display all the examples that follow in that language.
You may also need to configure your machine to work with our examples. To simplify things, we rely on SOAP toolkits — code libraries that know how to interpret WSDL files and encode and decode XML request and response messages — and AdWords API client libraries — additional helper code written specifically for our services. The table below lists what's needed for each langauge. We've also packaged stubs and full source code for all of our listings into starter projects, which you can download if you'd rather not start from scratch.
The AdWords API Sandbox is a development environment for the AdWords API. It's just like the production API, except you work with dummy AdWords accounts whose ads don't really run and you aren't charged for the calls you make. Both of these things come in handy when you're writing and testing a new application.
Depending on the language you're using, you may have to do some initial setup to make sure the required libraries are imported and you're otherwise fully configured to talk to the API. This and the subsequent code snippets should be added incrementally to the same source file as you build your program.
No language selected! Choose one above.Ensure that the adwords-api JAR file is available in your CLASSPATH.
import java.util.Hashtable;
import com.google.api.adwords.lib.AdWordsServiceLogger;
import com.google.api.adwords.lib.AdWordsUser;
import com.google.api.adwords.v11.*;
public class EmptySample {
public static void main(String[] args) throws Exception {
// Your code here.
}
}From your Visual Studio project, add a reference
to the standard System.Web.Services assembly.
Add a reference to the compiled client library assembly, google-api-adwords-dotnet.
Add a reference to the ICSharpCode.ShapZipLib assembly, available here.
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using com.google.api.adwords.lib;
using com.google.api.adwords.v11;
namespace Sample_Application {
class EmptySample {
static void Main(string[] args) {
// Your code here.
}
}
}LIB_HOME = '.' # The path to the client library lib/ directory.
import sys
sys.path.append(LIB_HOME)
import time
from lib.AccountService import AccountService
from lib.CampaignService import CampaignService
from lib.AdGroupService import AdGroupService
from lib.AdService import AdService
from lib.CriterionService import CriterionService
from lib.Client import Client
# Your code here.Modify the settings.ini file to enable the following:
Use_Sandbox = yes
Exchange_Rate = 1
Display_Error_Style = XML
Ensure that the apility.php library is in a location readable by your code,
such as the same directory. In your PHP code, require the library:
<?php
require_once("apility.php");
# Your code here.
?>
To log into the sandbox, you provide some credentials in the form of SOAP headers. (When you're ready to log into the production environment, you do the same, only you pass in an AdWords username and password — which you can obtain here — and a real developer and application token — which you can obtain here.) Once you've set your login info, invoking any old method, like getClientAccounts, prompts the sandbox to create 5 dummy AdWords accounts for you.
Now, we'll add some elements that make up an AdWords campaign. The top-level container of an AdWords campaign is called, naturally enough, a campaign. A campaign describes budget and targeting information, such as what web properties to run on, for a set of ads.
All monetary values in the API, for instance the daily budget below, are specified in what we term micros. One million micros is equal to one fundamental unit of the local currency for the AdWords account. For example, if the currency is US Dollars, 1,000,000 micros is equal to 1 USD and 10,000 micros is equal to 0.01 USD, or 1 cent.
The second-level container of an AdWords campaign is called an ad group. An ad group bundles a related set of keywords and creatives that will run together. To create an ad group, you call addAdGroup.
No language selected! Choose one above....
AdGroupInterface adGroupService =
(AdGroupInterface)adWordsUser.getService(AdWordsUser.AD_GROUP_SERVICE);
AdGroup newAdGroup = new AdGroup();
newAdGroup.setName("Sample Ad Group");
newAdGroup.setStatus(AdGroupStatus.Enabled);
newAdGroup.setKeywordMaxCpc(25 * 10000L);
newAdGroup = adGroupService.addAdGroup(campaignId, newAdGroup);
int adGroupId = newAdGroup.getId();
AdGroup[] adGroups = adGroupService.getAllAdGroups(campaignId);
for(AdGroup adGroup : adGroups) {
System.out.println("Ad group: " + adGroup.getName());
}
......
AdGroupService adGroupService =
(AdGroupService)adWordsUser.getService("AdGroupService");
AdGroup newAdGroup = new AdGroup();
newAdGroup.name = "Sample Ad Group";
newAdGroup.keywordMaxCpc = 25 * 10000L;
newAdGroup.keywordMaxCpcSpecified = true;
newAdGroup = adGroupService.addAdGroup(campaignId, newAdGroup);
int adGroupId = newAdGroup.id;
AdGroup[] adGroups = adGroupService.getAllAdGroups(campaignId);
foreach (AdGroup adGroup in adGroups) {
Console.Out.WriteLine("Ad group: " + adGroup.name);
}
......
ad_group_service = user.GetAdGroupService('https://sandbox.google.com')
new_ad_group = {
'name': 'Sample Ad Group',
'status': 'Enabled',
'keywordMaxCpc': str(25 * 10000),
}
new_ad_group = ad_group_service.AddAdGroup(campaign_id, new_ad_group)[0]
ad_group_id = new_ad_group['id']
ad_groups = ad_group_service.GetAllAdGroups(campaign_id)
for ad_group in ad_groups:
print('Ad group: %s' % ad_group['name'])
......
$newAdGroup = addAdGroup(
"Sample Ad Group", // name
$campaignId, // campaign id
"Enabled", // status
25 * 10000, // default keyword max cpc
0 // site max cpm
);
$adGroupId = $newAdGroup->getId();
$adGroups = getAllAdGroups($campaignId);
foreach($adGroups as $adGroup) {
$adGroupName = $adGroup->getName();
print("Ad group: $adGroupName\n");
}
...
This code should print the name of your new ad group.
With a campaign and ad group in hand, you're ready to create ads themselves. A basic AdWords ad consists of an ad — the creative, i.e. what a user sees — and a keyword the search query or page content that triggers the ad. There are different types of ads. The most common is a text ad, which has a headline, two additional lines of text, and a link. An ad group can contain multiple ads and keywords. To create ads, you call addAds.
No language selected! Choose one above....
AdInterface adService = (AdInterface)adWordsUser.getService(AdWordsUser.AD_SERVICE);
TextAd newAd = new TextAd();
newAd.setAdGroupId(adGroupId);
newAd.setHeadline("Headline Goes Here!");
newAd.setDescription1("First line of description.");
newAd.setDescription2("Second line of description.");
newAd.setDestinationUrl("http://www.example.com/demo.html");
newAd.setDisplayUrl("www.example.com");
newAd.setStatus(AdStatus.Enabled);
Ad[] newAds = adService.addAds(new Ad[] { newAd });
Ad[] ads = adService.getAllAds(new int[] { adGroupId });
for(Ad ad : ads) {
if(ad instanceof TextAd) {
TextAd textAd = (TextAd)ad;
System.out.println("Text ad: " + textAd.getHeadline());
}
}
......
AdService adService = (AdService)adWordsUser.getService("AdService");
TextAd newAd = new TextAd();
newAd.adGroupId = adGroupId;
newAd.status = AdStatus.Enabled;
newAd.headline = "Headline Goes Here!";
newAd.description1 = "First line of description.";
newAd.description2 = "Second line of description.";
newAd.destinationUrl = "http://www.example.com/demo.html";
newAd.displayUrl = "www.example.com";
Ad[] newAds = adService.addAds(new Ad[] { newAd });
Ad[] ads = adService.getAllAds(new int[] { adGroupId });
foreach (Ad ad in ads) {
if (ad is TextAd) {
TextAd textAd = (TextAd)ad;
Console.Out.WriteLine("Text ad: " + textAd.headline);
}
}
......
ad_service = user.GetAdService('https://sandbox.google.com')
new_ad = {
'adType': 'TextAd',
'headline': 'Headline goes here!',
'description1': 'First line of description',
'description2': 'Second line of description',
'adGroupId': ad_group_id,
'status': 'Enabled',
'displayUrl': 'www.example.com',
'destinationUrl': 'http://www.example.com/demo.html',
}
new_ad = ad_service.AddAds([new_ad])
ads = ad_service.GetAllAds([ad_group_id])
for ad in ads:
if ad['adType'] == 'TextAd':
print('Text ad: %s' % ad['headline'])
......
$newAd = addTextAd(
$adGroupId, // ad group id
"Headline goes here!", // headline
"First line of description.", // description line 1
"Second line of description.", // description line 2
"Enabled", // status
"www.example.com", // display url
"http://www.example.com/demo.html" // destination url
);
$ads = getAllAds(array($adGroupId));
foreach($ads as $ad) {
if($ad->getAdType() == "TextAd") {
$headline = $ad->getHeadline();
print("Text ad: $headline\n");
}
}
...
Running this code should output your text ad headline.
This tutorial just scratches the surface of what's available in the AdWords API. The Developer Guide contains full documentation for the API's various services and methods and the campanion sample code can serve as a jumping off point for building a larger application on top of the API.
More advanced AdWords API functionality includes:
Creating detailed account performance and structure reports with the Report Service.
Using the Keyword Tool Service to automatically generate suggested keywords given a seed keyword or text on a website.
Estimating the amount of traffic and expected cost per click of keywords before adding them to your ad groups with the Traffic Estimator Service.
Generating lists of potential sites for placement-targeted campaigns with the Site Suggestion Service.
Tracking your API usage, including usage for client accounts within an MCC, using the Info Service.