Posted:
You may have heard that we launched local time zone reporting for AdSense, a fantastic feature for publishers far from the Pacific Time Zone (PTZ)! On the API side we’ve been asked some questions about it, as in some cases this may lead to the AdSense web interface and the AdSense Management API showing different data.

In Version 1.3 of the AdSense Management API, the report.generate call has a new, optional parameter called useTimezoneReporting. If set to true, the report will be generated in the local time zone configured in the web interface. Note that billing is still based on PTZ, so if you want to fetch actual earnings you may want to make sure that useTimezoneReporting is set to false or you might see small discrepancies.

The default value for this parameter is false resulting in PTZ being respected, as it was before the feature was added. If an AdSense user doesn’t choose a local time zone it will default to PTZ, so this parameter won’t make a difference.

Our recommendation is that developers let users choose if they want reports in their “Billing time zone” or their “Local time zone” (to match AdSense’s terminology).

Bear in mind that users changing their local time zones can generate spikes or dips in the local time zone reports, as it makes the day of the change longer or shorter.

You can read more about this in the AdSense blog, and the AdSense help center has instructions on how to enable the feature.

Posted:
With the release of v1.2 (and the subsequent v1.3) of the AdSense Management API, older versions became deprecated, and we announced we would be retiring them later this year. The turnoff date will be August 12, 2013.

If your application is still using v1 or v1.1, please be sure to update it to use v1.2 ‒ or preferably, v1.3. The new versions build on top of the old ones, so all previous functionality will still be available and work exactly the same, which should make for an easy upgrade.

If you have any questions or need any help, be sure to join us in the forum!

, AdSense Management API Team

Posted:
In the AdSense Management API and AdSense Host API, you can let us manage date calculations for you. Apart from the standard YYYY-MM-DD format, all date fields accept the following special keywords:
  • today
  • startOfMonth
  • startOfYear
With these keywords you can define useful date ranges such as the following:

Start date End date
This month’s performance so far startOfMonth today
This year’s performance so far startOfYear today

But here is the really useful part: there is a handy feature that you can use to calculate relative dates by adding or subtracting days, weeks, months, or years:

Start date End date
Last 7 days’ performance today-6d today
Last month’s performance startOfMonth-1m startOfMonth-1d
Previous six months startOfMonth-6m startOfMonth-1d

You can use up to two operations per date. Let’s say we need to compare last month with the same period last year. We would need two requests like these two requests with these start and end dates:

Start date End date
Last month’s performance startOfMonth-1m startOfMonth-1d
Same month last year startOfMonth-1m-1y startOfMonth-1d-1y

If you want to try these out, we recommend using the APIs explorer. You’ll find it at the bottom of each method documentation page:
If you have any questions about this post or the AdSense APIs in general, visit the AdSense API Forum. You can also follow our Google Ads Developers G+ page for ad-related updates.


Posted:
We’ll soon be sunsetting v1.0 and v1.1 of the AdSense Management API so we encourage you to migrate to v1.2 as soon as possible. To get you started, follow this simple guide.

If you don't use the client libraries you need to replace the version on the base URL that you are using:
https://www.googleapis.com/adsense/v1.1/
with
https://www.googleapis.com/adsense/v1.2/
That will allow you to continue using the API as you were and should require no further modifications to your code.

If you use the client libraries, what you need to do depends on the language you use:
  • Java
    Download the latest client libraries and replace your project dependencies.
  • PHP
    Make sure you get the latest files from the trunk of the repository. You may only need to replace trunk/src/contrib/Google_AdSenseService.php but you should update all the files you use.
  • Python
    Good news for you! No need to download any libraries, the discovery service knows what to do. Create the service as follows:
    http = httplib2.Http()
    service = build("adsense", "v1.2", http=http)
  • C#
    Download the latest client libraries and replace your project dependencies.
To make sure you’re using the latest version, list your saved ad styles. It’s a new feature only available to v1.2, so if you don’t get an error, you’re on the right track.

To learn about the AdSense Management API read the docs and post your questions on the AdSense API Forum and we’ll do our best to help you! Also, follow our Google Ads Developers G+ page to receive important announcements and tips.

Posted:

Good news, everyone! Version 1.2 of the AdSense Management API is now available, and with it come two new features:
  • the ability to retrieve saved ad styles
  • the ability to retrieve and run saved reports

In addition, we’ll soon be deprecating versions 1.0 and 1.1. These will both be sunset six months from now, on April 17, 2013. Migration to the new version should be extremely simple, since version 1.2 is a superset of both previous versions, with no breaking changes.

If you have any questions or comments, let us know in the forum!


Posted:

If you are an advanced AdSense Management API user, your application may have run into one of the several different limits we have in place. We’ve created a new documentation page to keep track of system limits, but here’s a small description of what they are and what you can do to avoid them.

API Courtesy Limit

This limit refers to the number of requests your project can make via the API in a single day, across all of your users or AdSense accounts. This is set to 10,000 queries per day for all new projects.

If you’re running into the limit, feel free to request more from the “Quotas” page for your project, in the APIs Console. We’ll look at your request and project usage history, then decide an appropriate limit to set in place.

Page size for “list” calls

The various “list” methods in the AdSense Management API are paginated, with a default size of 10,000 entries per page. You can configure this limit yourself in your request with the maxResults parameter, but you can’t set it to any value greater than 10,000.

Reports

For regular, unpaginated reports, the maximum number of rows that the API will return is 50,000. If your report is larger than that, it will be truncated at 50,000 rows.

Pagination in reports should only be used when strictly necessary, as it’s generally only useful to applications running in devices with severe storage constraints. Because of this, paginated reports are limited to 5,000 rows and any attempt to obtain data beyond the 5000th row will return an error.


Let us know in our forum if you have any questions!

Posted:

Today we’ve published a new tutorial on scheduling AdSense reports with Google Apps Script.

By following the tutorial, you’ll learn how to create a script that’s executed every hour to retrieve data from the AdSense API and send a report of the evolution of several metrics over the current day. The report data will then be visualized using an area chart.

You’ll also learn how to add a user interface to let you configure the recipient of the report, the metrics included in the chart, the hours of the day and days of the week for the report sending, as shown in the image below.



The following is an example of chart that will be sent with the email.



This tutorial is an example of how Google Apps Script can provide easy ways to automate tasks across Google products and third party services. Check the tutorials page to learn the different things that you can do using this cloud scripting language.

For any additional questions, visit our AdSense API forum or the Google Apps Script forum. You can also check the schedule for our Office Hours Hangouts and join us for a chat on this and other topics -- visit the right column of this blog to find our schedule.


Posted:

Since launching the AdSense Management API in October last year, we’ve received a number of questions and feedback from you while coding your applications. Today, we’ll address the most frequently asked questions and share some best practices.

How do I authenticate? Do I need to use OAuth?

Right now, the only authentication method we support is OAuth, but don’t let that intimidate you; OAuth 2.0 supports several authentication methods, for web server, client-side and installed applications and devices, which together cover all use cases.

You can find more information on how to authenticate in your favourite client library language in our client library guide or the more generic OAuth 2.0 documentation.

How do I stop my users from having to authorize my application every time they use it?

If you don’t take steps to store your users’ authentication data or set the appropriate flags on your request, the authentication process will run them through a permission-granting dialog similar to the one below every time:


In order to avoid this and improve the experience for users of your web or installed application, you should store their authentication data.

There are two types of token that we need to know about here: access tokens and refresh tokens. Access tokens give you immediate access to a user’s data, and are short-lived, whereas refresh tokens are long-lived, allowing you to generate new access tokens when you need them, even if the user isn’t present.

For installed or web applications we recommend storing both, and using the refresh token to generate a new access token whenever the one you stored expires.

For client-side applications, things should be a little easier, as all it should take is a redirect. The OAuth 2.0 documentation for client-side applications has all the information you need.

For more information on request tokens, you can check the relevant section in the OAuth 2.0 documentation, or the “Persisting authentication data” section in our client library guide if you’re using one of the client libraries.

How often can I run my report queries?

Every application has different needs, so the answer to this question will no doubt depend on what you’re doing. There are, however, a few guidelines we can give you.

First of all, try to collect data on the same frequency that you analyze it. That is, if you’re interested in daily performance, there’s no need for you to collect data more often than once a day, as our reporting can compile that data for you.

On the other hand, if you’re trying to get data as frequently as possible, bear in mind that we cache our report data for 60 seconds. There’s thus no point in running the same report more often than once a minute; the data you get won’t be any fresher, and you’ll just be wasting your request quota.

How do I get my performance data per country / domain?

Most reports are based on a time dimension such as DATE, WEEK or MONTH, which is to say that they’re grouped by that particular dimension.

Not all reports need to be based on a time dimension, however. In fact, a very useful report for those of you with many international visitors is to get a breakdown of visitors per country. In order to get that, just set your start and end dates and choose COUNTRY_CODE or COUNTRY_NAME as the dimension.

You can combine both approaches as well, to get a breakdown per country for every month, for example.

To get some more background on reports and the concepts behind them, check out our Diving into Reports blog post.

What should I do if my question isn’t answered here?

We’ve got a whole bunch of resources for you, from the reference documentation to our client library guide and code examples for several programming languages.

If that doesn’t help, take a look in our forum, and you might find a similar question or get a chance to post your own. You can also join us in a Hangout during our regular office hours. We’ll be around to give you a hand in either case!

Posted:

Welcome back to Chart Tuning! In this second half of the series we will show you how to define the different views for our chart and implement the zooming functionalities.

Before diving into the code explanation, check out the live example and the source code of the example chart if you haven’t yet.

Defining week and month view

Now that all our data is in place, we can get the visualization started. First we create a ChartWrapper by calling getChartWrapper. After setting the data table for our chart, we set the visualization mode to month and we can draw the chart.

The function setMonthView shows:

  • how to set the view window of the chart so that the values on the X axis (the dates) goes from 0 to the last day of the current month

  • how to add the required text to points on the X axis

  • how to visualize the subset of columns that we want in the month view.

The function setWeekView shows how to set the view window so that we show seven points centered on the user’s selection and how to visualize all the columns, as per requirement of the week view.

Handling events

Google charts can fire events for which you can listen. Events can be triggered by user actions: for example a user clicks on a chart. This comes in handy for our zooming functionality, as we need to intercept a user clicking a column in the chart.

To listen for these clicks, we add an event listener on the chart, and call the setWeekView function when the select event occurs.

Job done!

And that’s it, our chart is ready!

Have you noticed the graceful transition of the chart when using the zoom functionality? Transition animations are one of the latest additions to the Google Chart Tools, and you can experiment with different transition behaviors to properly tune your chart!

Some more thoughts on the User Experience

The zooming effect is nice to see, and when we’re in week view, we can use it to scroll the chart without changing a single line of code: if we click on one of the columns, the view centers on the selected point.

Thinking about the user experience, we have to consider that it might not be clear for our user that the zooming effect is activated when clicking on one column, or that they can still scroll the chart by clicking the other columns.

We can provide a better user experience by adding a button to toggle between week and month view; when in week view, we can add two arrow buttons to allow the user to scroll to the previous or the following week.

Why don’t you try to modify the source code to implement this feature request? We will add our solutions to the example chart source code on February 21, and then discuss possible solutions and other improvement ideas during the AdSense Management API Office Hours scheduled for that day.

For any questions or suggestions, don’t hesitate to engage with us in our forums:

Update: our solution has been added to the AdSense API showcase project.

Posted:

During Chart Tools Week, we showed you how to create a basic dashboard for AdSense reporting using the AdSense Management API and Google Chart Tools.

In this new two-part series, we’ll examine more advanced charting techniques that will improve the look and feel of our chart as well as enable user interactivity.

We’ll also show you how to use the Google Closure Library to ease some of the data manipulation tasks when writing a JavaScript application.

The goal

Our goal is to produce this Column Chart showing the earnings per day for the current month. We also want a zoom feature, with the following requirements:

  • The chart is initially shown in a month view: standard columns are shown for the days of the current month up to the current day. For the current and future days we draw the columns with a different visualization style, to visually outline the uncertainty of the data measurement. On the X axis we show 4 or 5 titles, for day 1, 8, 15, 22 and 29 (except for non leap year February). The title is the day of the month.

  • By clicking one of the columns, the user can zoom the chart to a week view. In the week view we show the values over the week centered on the day selected by the user: 7 columns are visualized, and for each data point we show the title on the X axis. We also add two other columns to the data visualization in order to supply more detailed information:

  • Finally, we add to the visualization a Zoom Out button to allow the user to go back to the month view. The Zoom Out button will disappear when the user zooms all the way out.

Dive with us into the source code of our example chart to see how easy this task can be! You can find instructions on how to setup the example project to use Closure in the README file.

Getting to the goal: fetching the data

After the Google API JavaScript client has loaded, the OAuth 2.0 flow completes, and the user logs in, makeApiCall is called to start the generation of the chart.

The first thing we do in makeApiCall is fetch our data from the AdSense Management API. We want DATE to be the dimension for our report, and EARNINGS, PAGE_VIEWS_RPM and AD_REQUEST_RPM as our metrics. To determine start date and end date, we can use the Google Closure Library as shown in the getRequestParams function. After that we are ready to send our request.

Formatting the data: using roles

Once we have the data, the next step is to format it into a DataTable that will be consumed by our chart. The addTableHeaders function shows how to add the columns that we need for our chart. Two column declarations might catch your attention:

dt.addColumn({'type': 'string', role: 'tooltip'});
dt.addColumn({'type': 'boolean', role:'certainty'});

For these columns we are using DataTable Roles, an experimental feature of the Google Chart Tools that can be used to describe the purpose of the data in a column. Using the tooltip role we can edit the text to display when the user hovers over data points. Using the certainty role we can indicate whether a data point is certain or not, and have the column visualized in a different way accordingly.

Formatting the data: the content

After defining the columns, we can add rows of data to our DataTable. To do this, we need to keep the following into account:

  • The AdSense Management API will return a result for a day only if there is a nonzero value for that day. In other words, if one day we had zero views, the API will not return a result for that day. This also means that we will not get results for days in the future.

  • We want to make the certainty of a data point visible, so that we have a different visualization for measures that are certain and measures that are in progress or not started.

For the first point, we need to iterate through the values returned from the API. If a DATE is not present in the response, we add a row with value zero for all the metrics for that DATE to the table. To satisfy the second point, we need to check if the current day of the iteration is the current day of the month or a day in the future. If it is in the future, we need to flag the row as uncertain.

Remember that the rows part of the API response will be an array similar to:

"rows": [
  ["2012-01-03", "28", "46", "41"],
  ...
  ["2011-11-07", "2", "3", "3"]
]

The function addTableRows implements the data manipulation algorithm, using Closure to help out with dates formatting and days iteration.

The function formatRow shows how to create rows for our DataTable and add data for our tooltip and certainty columns. In the example, we have built the tooltips to show the full name of the day of the week for each data point, to help the user to better contextualize the value.

Enough for today!

At the end of day one, we have all the data ready to be visualized. Tomorrow we’ll see more on how to define our week and month views and implement the zooming functionalities.

In the meantime, don’t hesitate to ask your questions, leave your suggestions, and engage with us in our forums:

Posted:

Thanks for joining us for Chart Tools week on the blog, where we're sharing ways to use Google Chart Tools. In the fourth and last part of this series, we’ll examine how to organize and manage multiple charts that share the same underlying data using dashboards and controls.

Interaction with data

The last request of the CEO is to be able to interact with the data: he wants to filter the line chart and the column chart by expressing a range of page views.

What we need to do now is compose the 2 charts into a Dashboard object, following these steps:

  • combine the data retrieved from the AdSense Management API into one single table
  • create the charts
  • add 1 control, a Number Range Filter for ad requests
  • create a view on top of the data table
  • create a Dashboard object and feed it with the view

Create the DataTable

To create a Dashboard, we need the charts to share the same underlying data. For this reason, we will combine the requests for the line and the column chart into a single request:

start date:2011-01-01
end date:2011-12-31
dimensions:MONTH
metrics:PAGE_VIEWS, AD_REQUESTS, MATCHED_AD_REQUESTS, INDIVIDUAL_AD_IMPRESSIONS
filters:(none)

The result will be similar to:

result = {
  "kind": "adsense#report",
  "totalMatchedRows": "9",
  "headers": [ {...} ],
  "rows": [
    ["2011-01", "28", "46", "41", "165"],
    ...
    ["2011-11", "2", "3", "3", "3"]
  ],
  "totals": ["", "241", "278", "264", "825"],
  "averages": ["", "26", "30", "29", "91"]
}

Now we can create our DataTable, adding columns for all the metrics:

var data = new google.visualization.arrayToDataTable(
    [['Month', 'PAGE_VIEWS', 'AD_REQUESTS', 'MATCHED_AD_REQUESTS',
        'INDIVIDUAL_AD_IMPRESSIONS']].concat(resp.rows));

Create the charts

The next step is to create the wrappers:

var lineChartWrapper = new google.visualization.ChartWrapper({
  chartType: 'LineChart',
  options: {'title': 'Ad requests trend - Year 2011'},
  containerId: 'line_chart_div',
  view: {'columns': [0, 2]}
});

var columnChartWrapper = new google.visualization.ChartWrapper({
  chartType: 'ColumnChart',
  options: {'title': 'Performances per month - Year 2011'},
  containerId: 'column_chart_div',
  view: {'columns': [0, 1, 3, 4]}
});

There are two important differences between creating wrappers for a dashboard and wrappers for standalone charts:

  • For each chart in a dashboard, we use the view option to select which columns are relevant for the chart (remember, all the data for the two charts is in the same table now)
  • We don’t draw the charts now, we’ll draw the entire dashboard later

Time to create the control!

Create the control

Let’s create the control wrapper for our number range filter for the ad requests:

var adRequestsSlider = new google.visualization.ControlWrapper({
  'controlType': 'NumberRangeFilter',
  'containerId': 'ad_requests_filter_div',
  'options': {
    'filterColumnLabel': 'Ad requests',
  }
});

The option container_id specifies the element of the page where the filter will be drawn into, while filterColumnLabel tells the filter which column to target.

Create the DataView

Remember that we need a DataView to convert our string field to numeric fields:

var view = new google.visualization.DataView(data);
view.setColumns([
  0,
  {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue(
      rowNum, 1))}, type:'number', label:'Page views'},
  {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue(
      rowNum, 2))}, type:'number', label:'Ad requests'},
  {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue(
      rowNum, 3))}, type:'number', label:'Matched ad requests'},
  {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue(
      rowNum, 4))}, type:'number', label:'Individual ad impressions'},
]);

Create the dashboard

Creating the Dashboard, binding the control to the charts and drawing the dashboard is as easy as the following:

var dashboard = new google.visualization.Dashboard(
    document.getElementById('dashboard_div'))
    .bind(adRequestsSlider, [lineChartWrapper, columnChartWrapper])
    .draw(view);

dashboard_div is the element of the page that acts as container for the Dashboard:

<div id="dashboard_div">
  <!--Divs that will hold each control-->
  <div id="ad_requests_filter_div"></div>
  <!--Divs that will hold each chart-->
  <div id="line_chart_div"></div>
  <div id="column_chart_div"></div>
</div>

And it’s done! Our Dashboard is ready. Check the live example and the source code for today!

Mission Accomplished!

Well done -- our dashboard is ready and the CEO is happy with his new tool! Now you can relax and play foosball!

If you want to know more about our APIs, check the documentation pages:

And if you have any additional questions, don’t hesitate to engage with us in our forums:

You can also join us in one of our AdSense API Office Hours on Google+ Hangouts. Check the schedule for the upcoming Office Hours in our Google Ads Developer Blog.

Lastly, a public service announcement: thanks Riccardo for your help!

Posted:

Welcome back to Chart Tools week here on the blog, where we're continuing our overview of generating charts for your AdSense reporting with Google Chart Tools. Today we’ll examine how to generate two other types of charts: a table chart and a geo chart.

Table chart

The third chart requested by our CEO is a table chart. The table chart will contain the number of ad requests, the number of matched ad requests, and the number of individual ad impressions broken down by ad client ID.

Our request will have these parameters:

start date:2011-01-01
end date:2011-12-31
dimensions:AD_CLIENT_ID
metrics:AD_REQUESTS, MATCHED_AD_REQUESTS, INDIVIDUAL_AD_IMPRESSIONS
filters:(none)

And the result will be similar to:

result = {
  "kind": "adsense#report",
  "totalMatchedRows": "4",
  "headers": [ {...} ],
  "rows": [
    ["ca-afdo-pub-1234567890123456", "59", "55", "232"],
    ...
    ["partner-mb-pub-1234567890123456", "1", "0", "0"]
  ],
  "totals": ["", "278", "264", "825"],
  "averages": ["", "69", "66", "206"]
}

As usual, let’s create a DataTable and a DataView to perform transformations on columns:

var data = new google.visualization.arrayToDataTable([['Ad client id',
    'AD_REQUESTS', 'MATCHED_AD_REQUESTS', 'INDIVIDUAL_AD_IMPRESSIONS']]
    .concat(resp.rows));
var view = new google.visualization.DataView(data);
view.setColumns([
  0,
  {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue(
      rowNum, 1))}, type:'number', label:'Ad requests'},
  {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue(
      rowNum, 2))}, type:'number', label:'Matched ad requests'},
  {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue(
      rowNum, 3))}, type:'number', label:'Individual ad impressions'}
]);

Finally, let’s draw the table chart. Note that there is no title for a table chart: if you need one, you’ll have to add it in a different element.

var tableWrapper = new google.visualization.ChartWrapper({
  chartType: 'Table',
  dataTable: view,
  containerId: 'vis_div'
});
tableWrapper.draw();

The table chart for our CEO is ready, and it can be sorted and paged.

Check the live example and the source code for today!

Geo chart

Finally, the last chart requested from our CEO: a geo chart. The geo chart will show the number of page views for the year broken down by country name.

Our request will have these parameters:

start date:2011-01-01
end date:2011-12-31
dimensions:COUNTRY_NAME
metrics:PAGE_VIEWS
filters:(none)

And the result will be similar to:

result = {
  "kind": "adsense#report",
  "totalMatchedRows": "9",
  "headers": [ {...} ],
  "rows": [
    ["Canada", "1"],
    ...
    ["United States", "52"]
  ],
  "totals": ["", "241"],
  "averages": ["", "26"],
}

DataTable and DataView creation step:

var data = new google.visualization.arrayToDataTable(
          [['Country', 'Page Views']].concat(resp.rows));

var view = new google.visualization.DataView(data);
view.setColumns([
  0,
  {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue(
      rowNum, 1))}, type:'number', label:'Page views'}
]);

Now we can draw the geo chart. For the geo chart there is no title:

var geoChartWrapper = new google.visualization.ChartWrapper({
  chartType: 'GeoChart',
  dataTable: view,
  containerId: 'vis_div'
});
geoChartWrapper.draw();

Et voilà! We have a map of the world with colors and values assigned to specific countries representing the page views from the countries for the current year.

Check the live example and the source code for today.

Time to play!

Eager to try to see what you can do combining these two powerful Google APIs?

You can start immediately using our Google API Explorer and our Google Visualization PlayGround. You can use the Explorer to query our AdSense Management API, and then use the results inside the code on the Visualization PlayGround to generate a chart.

In the next and final part of this series, we will see how to assemble multiple charts into dashboards and enrich them with interactive controls to manipulate the data they display.

Meanwhile, feel free to post any questions related to Google Chart Tools in Google Visualization API forum, or visit our AdSense Management API forum to ask general questions.

Posted:

It's Chart Tools week here on the blog, and so we'll be showing you in a 4-part series how to easily generate charts for your AdSense reporting using Google Chart Tools. In today’s second post we’ll examine how to generate another type of chart: a column chart.

Column chart

The second item required by our CEO is a column chart. The column chart will show the number of page views, ad requests, matched ad requests and individual ad impressions for each month of the current year.

Our request becomes:

start date:2011-01-01
end date:2011-12-31
dimensions:MONTH
metrics:PAGE_VIEWS, AD_REQUESTS, MATCHED_AD_REQUESTS, INDIVIDUAL_AD_IMPRESSIONS
filters:(none)

Now the result will be similar to:

result = {
 "kind": "adsense#report",
 "totalMatchedRows": "9",
 "headers": [ {...{ ],
 "rows": [
   ["2011-01", "28", "46", "41", "165"],
   ...
   ["2011-11", "2", "3", "3", "3"]
 ],
 "totals": ["", "241", "278", "264", "825"],
 "averages": ["", "26", "30", "29", "91"]
}

We create the DataTable object, adding the columns for our dimensions:

// Create the data table.
var data = new google.visualization.arrayToDataTable(
    [['Month', 'PAGE_VIEWS', 'AD_REQUESTS', 'MATCHED_AD_REQUESTS',
    'INDIVIDUAL_AD_IMPRESSIONS']].concat(result.rows));

Once again we use a DataView to convert the string values to numbers:

var view = new google.visualization.DataView(data);
view.setColumns([
  0,
  {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue(
      rowNum, 1))}, type:'number', label:'Page views'},
  ...
  {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue(
      rowNum, 4))}, type:'number', label:'Individual ad impressions'}
]);

And finally, let’s create a wrapper for the column chart and draw it:

var columnChartWrapper = new google.visualization.ChartWrapper({
  chartType: 'ColumnChart',
  dataTable: view,
  options: {'title': 'Performances - Year 2011'},
  containerId: 'vis_div'
});
columnChartWrapper.draw();

Another piece is done: a column chart of our performances that is also displaying tips when hovering over bars. Check the live example and the source code for today!

Time to play!

Eager to try to see what you can do combining these two powerful Google APIs?

You can start immediately by using our Google API Explorer and our Google Visualization PlayGround. You can use the Explorer to query our Management API, and then use the results inside the code on the Visualization PlayGround to generate a chart.

Stay tuned for our next post this week, where we’ll show you how to generate other two charts, a table chart and a geo chart.

If you have any questions related to the AdSense Management API, come to our forum; alternatively, visit the Google Visualization API forum if you're looking for support on Chart Tools.


Posted:
It’s Monday morning, and you’re sitting in front of your computer, ready for a relaxed start of the week. But wait!

You’ve received an email from your CEO. He wants you to add AdSense reporting to his dashboard, and he wants to see the following:
  • a line chart showing the number of ad requests for the current year, broken down by month
  • a column chart showing the number of page views, ad requests, matched ad requests and individual ad impressions for the current year, broken down by month
  • a table showing the number of ad requests, matched ad requests and individual ad impressions for the current year, broken down by ad client id
  • a geo chart showing the number of page views for the current year broken down by country
He also requires the ability to interact with data: he wants to refine the visualization of the line and column charts filtering by lowest and highest number of ad requests shown in the charts.

It might look like a week of hard work is coming, but don’t worry! It’s Chart Tools week here on the AdSense Management API blog, and we’re going to show you how to easily and rapidly create the dashboard using the Google AdSense Management API and the Google Chart Tools. In the first part of this series, we’ll examine how to generate a line chart.

Background


You can access the AdSense Management API from different programming languages using the appropriate Google APIs Client. Check our documentation for AdSense Management API specific information.

The Google Chart Tools API are accessible using Javascript, check this ‘Hello Charts’ example for a quick start lesson on the API.

Line chart


The CEO wants a line chart showing the number of ad requests for the current year, broken down by month.

We will send a request to the AdSense Management API with the following parameters:
start date:2011-01-01
end date:2011-12-31
dimensions:MONTH
metrics:AD_REQUESTS

And the result will be a json array similar to the following:
result = {
  "kind": "adsense#report",
  "totalMatchedRows": "9",
  "headers": [ {...} ],
  "rows": [
    ["2011-01", "46"],
    ...
    ["2011-11", "3"]
  ],
  "totals": ["", "278"],
  "averages": ["", "30"]
}
To use the Chart API we first need to create a DataTable object representing the result of our request:
// Create the data table.
var data = new google.visualization.arrayToDataTable(
    [['Month', 'AD_REQUESTS']].concat(result.rows));
The AdSense Management API is returning the value for AD_REQUESTS as a string, but we need a numeric value for our charts. To achieve this, we are going to build a Data View on top of our Data Table and convert the string column to a number column:
var view = new google.visualization.DataView(data);
view.setColumns([
  0,
  {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue(
      rowNum, 1))}, type:'number', label:'Ad requests'}
]);
Our DataView will use the first column of the DataTable as it is, but will generate on the fly a second column composed of numeric values by calling a function of our choice that implements the conversion.

Finally we can draw the chart using a chart wrapper and passing our DataView to the wrapper. Make sure to define an element with id equal to the containerId parameter, as this is where the chart will be drawn.
var lineChartWrapper = new google.visualization.ChartWrapper({
  chartType: 'LineChart',
  dataTable: view,
  options: {'title': 'Ad requests trend - Year 2011'},
  containerId: 'vis_div'
});
lineChartWrapper.draw();
The line chart for the CEO is ready, and it’s also displaying tips when hovering over points. Check the live example and the source code for today!

Time to play!

Eager to try to see what you can do combining these two powerful Google APIs?

You can start immediately by using our Google API Explorer and our Google Visualization PlayGround. You can use the Explorer to query our Management API, and then use the results inside the code on the Visualization PlayGround to generate a chart.

In the next post of this series, we’ll look at how to generate a column chart.

Have questions in the meantime?

Posted:
Starting today, the AdSense Management API is available as part of AdSense Services in Google Apps Script. This means that you’ll be able to do things like:
  • Create AdSense performance reports for your AdSense accounts in a Google spreadsheet
  • Create a chart based on your AdSense reporting data and display it in a Google Spreadsheet
  • Embed your scripts in a Google Sites page, for instance to import a chart
  • Use triggers to schedule the execution of your scripts, for instance to periodically update the chart imported in the Google Sites page
Accessing the API from Google Apps Scripts is very easy. The following snippet of code shows how to generate a report and populate columns of a spreadsheet with the data retrieved:
function generateReport() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Reports');
  var startDate = Browser.inputBox(
      "Enter a start date (format: 'yyyy-mm-dd')");
  var endDate = Browser.inputBox(
      "Enter an end date (format: 'yyyy-mm-dd')");
  var args = {
    'metric': ['PAGE_VIEWS', 'AD_REQUESTS', 'MATCHED_AD_REQUESTS',
               'INDIVIDUAL_AD_IMPRESSIONS'],
    'dimension': ['MONTH']};
  var report = AdSense.Reports.generate(startDate, endDate, args).getRows();
  for (var i=0; i<report.length; i++) {
    var row = report[i];
    sheet.getRange('A' + String(i+2)).setValue(row[0]);
    sheet.getRange('B' + String(i+2)).setValue(row[1]);
    sheet.getRange('C' + String(i+2)).setValue(row[2]);
    sheet.getRange('D' + String(i+2)).setValue(row[3]);
    sheet.getRange('E' + String(i+2)).setValue(row[4]);
  }    
}
If you want to generate a chart from your data instead of populating the spreadsheet, that’s very easy as well:
function generateLineChart() {
  var doc = SpreadsheetApp.getActiveSpreadsheet();
  var startDate = Browser.inputBox(
      "Enter a start date (format: 'yyyy-mm-dd')");
  var endDate = Browser.inputBox(
      "Enter an end date (format: 'yyyy-mm-dd')");
  var adClientId = Browser.inputBox("Enter an ad client id");
  var args = {
    'filter': ['AD_CLIENT_ID==' + adClientId],
    'metric': ['PAGE_VIEWS', 'AD_REQUESTS', 'MATCHED_AD_REQUESTS',
               'INDIVIDUAL_AD_IMPRESSIONS'],
    'dimension': ['MONTH']};
  var report = AdSense.Reports.generate(startDate, endDate, args).getRows();
  var data = Charts.newDataTable()
      .addColumn(Charts.ColumnType.STRING, "Month")
      .addColumn(Charts.ColumnType.NUMBER, "Page views")
      .addColumn(Charts.ColumnType.NUMBER, "Ad requests")
      .addColumn(Charts.ColumnType.NUMBER, "Matched ad requests")
      .addColumn(Charts.ColumnType.NUMBER, "Individual ad impressions");
  
  // Convert the metrics to numeric values.
  for (var i=0; i<report.length; i++) {
    var row = report[i];
    data.addRow([row[0],parseInt(row[1]),parseInt(row[2]),
        parseInt(row[3]),parseInt(row[4])]);  
  }
  data.build();
  
  var chart = Charts.newLineChart()
      .setDataTable(data)
      .setTitle("Performances per Month")
      .build();
  
  var app = UiApp.createApplication().setTitle("Performances");
  var panel = app.createVerticalPanel()
      .setHeight('350')
      .setWidth('700');
  panel.add(chart);
  app.add(panel);
  doc.show(app); 
}
A shiny line chart will be displayed in your spreadsheet, as shown in the following picture:


You can start using the service by checking out the reference documentation, that contains also some sample scripts, and this tutorial that implements the use cases mentioned above.

Happy Google Apps Scripting with the AdSense Management API!

Edit: fixed typo.


Posted:
We’re happy to announce we’ve just launched AdSense Management API v1.1!

With the new features in this release, you’ll be able to retrieve ad units via custom channels (and vice-versa), make GET calls on most inventory items, and access extended targeting information on custom channels.

Take a look at our updated documentation for more details.

Let us know if you have any questions, and happy holidays!