YYYY-MM-DD
today
startOfMonth
startOfYear
today-6d
startOfMonth-1m
startOfMonth-1d
startOfMonth-6m
startOfMonth-1m-1y
startOfMonth-1d-1y
https://www.googleapis.com/adsense/v1.1/
https://www.googleapis.com/adsense/v1.2/
trunk/src/contrib/Google_AdSenseService.php
http = httplib2.Http()service = build("adsense", "v1.2", http=http)
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.
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.
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.
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!
- Sérgio Gomes, AdSense API Team
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.
- Silvano Luciani, AdSense API Team
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.
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.
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.
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.
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.
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!
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.
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.
ChartWrapper
getChartWrapper
The function setMonthView shows:
setMonthView
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.
setWeekView
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.
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!
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.
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.
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:
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.
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.
makeApiCall
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.
DATE
EARNINGS
PAGE_VIEWS_RPM
AD_REQUEST_RPM
start date
end date
getRequestParams
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:
DataTable
addTableHeaders
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.
tooltip
certainty
After defining the columns, we can add rows of data to our DataTable. To do this, we need to keep the following into account:
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.
addTableRows
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.
formatRow
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:
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.
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:
Dashboard
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:
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));
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:
Time to 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.
container_id
filterColumnLabel
Remember that we need a DataView to convert our string field to numeric fields:
DataView
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'}, ]);
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:
dashboard_div
<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!
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!
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.
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:
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!
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.
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.
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.
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.
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:
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!
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.
result = { "kind": "adsense#report", "totalMatchedRows": "9", "headers": [ {...} ], "rows": [ ["2011-01", "46"], ... ["2011-11", "3"] ], "totals": ["", "278"], "averages": ["", "30"] }
// Create the data table. var data = new google.visualization.arrayToDataTable( [['Month', 'AD_REQUESTS']].concat(result.rows));
AD_REQUESTS
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'} ]);
containerId
var lineChartWrapper = new google.visualization.ChartWrapper({ chartType: 'LineChart', dataTable: view, options: {'title': 'Ad requests trend - Year 2011'}, containerId: 'vis_div' }); lineChartWrapper.draw();
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]); } }
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); }
Edit: fixed typo.