Editor's note: this announcement is cross-posted from the Google Ads Developer Blog, which caters to AdWords, AdSense, DoubleClick and AdMob developers. We hope you enjoy this latest addition to Google Apps Script — Ryan Boyd
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:
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]); } }
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); }