Stay organized with collections
Save and categorize content based on your preferences.
The AdSense service allows you to use the
AdSense Management API in Apps Script. This API
gives AdSense customers the ability to get information about the structure
of their account and run reports on how it is performing.
Reference
For detailed information on this service, see the
reference documentation for the AdSense
Management API. Like all advanced services in Apps Script, the AdSense service
uses the same objects, methods, and parameters as the public API. For more information, see How method signatures are determined.
To report issues and find other support, please ask on Stack Overflow using the
adsense-api
tag.
This sample lists all of the accounts available to the user. The accounts are
specified as resource names, for example, accounts/pub-12345, that can be used
in other methods, such as listing ad clients. Notice the use
of page tokens to access the full list of results.
/** * Lists available AdSense accounts. */functionlistAccounts(){letpageToken;do{constresponse=AdSense.Accounts.list({pageToken:pageToken});if(!response.accounts){console.log('No accounts found.');return;}for(constaccountofresponse.accounts){console.log('Found account with resource name "%s" and display name "%s".',account.name,account.displayName);}pageToken=response.nextPageToken;}while(pageToken);}
List ad clients
This sample lists all of the ad clients for a given account. Specify the account
as a resource name, for example, accounts/pub-12345. You can get the account
resource name by using the List accounts sample code.
/** * Logs available Ad clients for an account. * * @param {string} accountName The resource name of the account that owns the * collection of ad clients. */functionlistAdClients(accountName){letpageToken;do{constresponse=AdSense.Accounts.Adclients.list(accountName,{pageToken:pageToken});if(!response.adClients){console.log('No ad clients found for this account.');return;}for(constadClientofresponse.adClients){console.log('Found ad client for product "%s" with resource name "%s".',adClient.productCode,adClient.name);console.log('Reporting dimension ID: %s',adClient.reportingDimensionId??'None');}pageToken=response.nextPageToken;}while(pageToken);}
List ad units
This sample lists all of the ad units for a given ad client. Specify the ad
client as a resource name, such as accounts/pub-12345/adclients/ca-pub-12345.
You can get the ad client resource name by using the
List ad clients sample code.
/** * Lists ad units. * @param {string} adClientName The resource name of the ad client that owns the collection * of ad units. */functionlistAdUnits(adClientName){letpageToken;do{constresponse=AdSense.Accounts.Adclients.Adunits.list(adClientName,{pageSize:50,pageToken:pageToken});if(!response.adUnits){console.log('No ad units found for this ad client.');return;}for(constadUnitofresponse.adUnits){console.log('Found ad unit with resource name "%s" and display name "%s".',adUnit.name,adUnit.displayName);}pageToken=response.nextPageToken;}while(pageToken);}
Generate a report
This sample generates a report over your AdSense account and outputs the
results to a spreadsheet.
/** * Generates a spreadsheet report for a specific ad client in an account. * @param {string} accountName The resource name of the account. * @param {string} adClientReportingDimensionId The reporting dimension ID * of the ad client. */functiongenerateReport(accountName,adClientReportingDimensionId){// Prepare report.consttoday=newDate();constoneWeekAgo=newDate(today.getTime()-7*24*60*60*1000);constreport=AdSense.Accounts.Reports.generate(accountName,{// Specify the desired ad client using a filter.filters:['AD_CLIENT_ID=='+escapeFilterParameter(adClientReportingDimensionId)],metrics:['PAGE_VIEWS','AD_REQUESTS','AD_REQUESTS_COVERAGE','CLICKS','AD_REQUESTS_CTR','COST_PER_CLICK','AD_REQUESTS_RPM','ESTIMATED_EARNINGS'],dimensions:['DATE'],...dateToJson('startDate',oneWeekAgo),...dateToJson('endDate',today),// Sort by ascending date.orderBy:['+DATE']});if(!report.rows){console.log('No rows returned.');return;}constspreadsheet=SpreadsheetApp.create('AdSense Report');constsheet=spreadsheet.getActiveSheet();// Append the headers.sheet.appendRow(report.headers.map((header)=>header.name));// Append the results.sheet.getRange(2,1,report.rows.length,report.headers.length).setValues(report.rows.map((row)=>row.cells.map((cell)=>cell.value)));console.log('Report spreadsheet created: %s',spreadsheet.getUrl());}/** * Escape special characters for a parameter being used in a filter. * @param {string} parameter The parameter to be escaped. * @return {string} The escaped parameter. */functionescapeFilterParameter(parameter){returnparameter.replace('\\','\\\\').replace(',','\\,');}/** * Returns the JSON representation of a Date object (as a google.type.Date). * * @param {string} paramName the name of the date parameter * @param {Date} value the date * @return {object} formatted date */functiondateToJson(paramName,value){return{[paramName+'.year']:value.getFullYear(),[paramName+'.month']:value.getMonth()+1,[paramName+'.day']:value.getDate()};}
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-28 UTC."],[[["\u003cp\u003eThe AdSense Management API allows you to programmatically access your AdSense account data within Google Apps Script.\u003c/p\u003e\n"],["\u003cp\u003eYou can retrieve information about your account structure, including accounts, ad clients, and ad units.\u003c/p\u003e\n"],["\u003cp\u003eThis API enables you to generate reports on your AdSense performance and export them to a Google Sheet.\u003c/p\u003e\n"],["\u003cp\u003eThis is an advanced service that needs to be enabled before use, offering functionality similar to the public AdSense Management API.\u003c/p\u003e\n"]]],[],null,["# AdSense Service\n\nThe AdSense service allows you to use the\n[AdSense Management API](/adsense/management) in Apps Script. This API\ngives AdSense customers the ability to get information about the structure\nof their account and run reports on how it is performing.\n| **Note:** This is an advanced service that must be [enabled before use](/apps-script/guides/services/advanced).\n\nReference\n---------\n\nFor detailed information on this service, see the\n[reference documentation](/adsense/management/reference/rest) for the AdSense\nManagement API. Like all advanced services in Apps Script, the AdSense service\nuses the same objects, methods, and parameters as the public API. For more information, see [How method signatures are determined](/apps-script/guides/services/advanced#how_method_signatures_are_determined).\n\nTo report issues and find other support, please ask on Stack Overflow using the\n[adsense-api](https://stackoverflow.com/questions/tagged/adsense-api)\ntag.\n\nSample code\n-----------\n\nThe sample code below uses [version 2](/adsense/management/reference/rest) of\nthe API.\n\n### List accounts\n\nThis sample lists all of the accounts available to the user. The accounts are\nspecified as resource names, for example, `accounts/pub-12345`, that can be used\nin other methods, such as [listing ad clients](#list_ad_clients). Notice the use\nof page tokens to access the full list of results. \nadvanced/adsense.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/adsense.gs) \n\n```javascript\n/**\n * Lists available AdSense accounts.\n */\nfunction listAccounts() {\n let pageToken;\n do {\n const response = AdSense.Accounts.list({pageToken: pageToken});\n if (!response.accounts) {\n console.log('No accounts found.');\n return;\n }\n for (const account of response.accounts) {\n console.log('Found account with resource name \"%s\" and display name \"%s\".',\n account.name, account.displayName);\n }\n pageToken = response.nextPageToken;\n } while (pageToken);\n}\n```\n\n### List ad clients\n\nThis sample lists all of the ad clients for a given account. Specify the account\nas a resource name, for example, `accounts/pub-12345`. You can get the account\nresource name by using the [List accounts](#list_accounts) sample code. \nadvanced/adsense.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/adsense.gs) \n\n```javascript\n/**\n * Logs available Ad clients for an account.\n *\n * @param {string} accountName The resource name of the account that owns the\n * collection of ad clients.\n */\nfunction listAdClients(accountName) {\n let pageToken;\n do {\n const response = AdSense.Accounts.Adclients.list(accountName, {\n pageToken: pageToken\n });\n if (!response.adClients) {\n console.log('No ad clients found for this account.');\n return;\n }\n for (const adClient of response.adClients) {\n console.log('Found ad client for product \"%s\" with resource name \"%s\".',\n adClient.productCode, adClient.name);\n console.log('Reporting dimension ID: %s',\n adClient.reportingDimensionId ?? 'None');\n }\n pageToken = response.nextPageToken;\n } while (pageToken);\n}\n```\n\n### List ad units\n\nThis sample lists all of the ad units for a given ad client. Specify the ad\nclient as a resource name, such as `accounts/pub-12345/adclients/ca-pub-12345`.\nYou can get the ad client resource name by using the\n[List ad clients](#list_ad_clients) sample code. \nadvanced/adsense.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/adsense.gs) \n\n```javascript\n/**\n * Lists ad units.\n * @param {string} adClientName The resource name of the ad client that owns the collection\n * of ad units.\n */\nfunction listAdUnits(adClientName) {\n let pageToken;\n do {\n const response = AdSense.Accounts.Adclients.Adunits.list(adClientName, {\n pageSize: 50,\n pageToken: pageToken\n });\n if (!response.adUnits) {\n console.log('No ad units found for this ad client.');\n return;\n }\n for (const adUnit of response.adUnits) {\n console.log('Found ad unit with resource name \"%s\" and display name \"%s\".',\n adUnit.name, adUnit.displayName);\n }\n\n pageToken = response.nextPageToken;\n } while (pageToken);\n}\n```\n\n### Generate a report\n\nThis sample generates a report over your AdSense account and outputs the\nresults to a spreadsheet. \nadvanced/adsense.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/adsense.gs) \n\n```javascript\n/**\n * Generates a spreadsheet report for a specific ad client in an account.\n * @param {string} accountName The resource name of the account.\n * @param {string} adClientReportingDimensionId The reporting dimension ID\n * of the ad client.\n */\nfunction generateReport(accountName, adClientReportingDimensionId) {\n // Prepare report.\n const today = new Date();\n const oneWeekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);\n\n const report = AdSense.Accounts.Reports.generate(accountName, {\n // Specify the desired ad client using a filter.\n filters: ['AD_CLIENT_ID==' + escapeFilterParameter(adClientReportingDimensionId)],\n metrics: ['PAGE_VIEWS', 'AD_REQUESTS', 'AD_REQUESTS_COVERAGE', 'CLICKS',\n 'AD_REQUESTS_CTR', 'COST_PER_CLICK', 'AD_REQUESTS_RPM',\n 'ESTIMATED_EARNINGS'],\n dimensions: ['DATE'],\n ...dateToJson('startDate', oneWeekAgo),\n ...dateToJson('endDate', today),\n // Sort by ascending date.\n orderBy: ['+DATE']\n });\n\n if (!report.rows) {\n console.log('No rows returned.');\n return;\n }\n const spreadsheet = SpreadsheetApp.create('AdSense Report');\n const sheet = spreadsheet.getActiveSheet();\n\n // Append the headers.\n sheet.appendRow(report.headers.map((header) =\u003e header.name));\n\n // Append the results.\n sheet.getRange(2, 1, report.rows.length, report.headers.length)\n .setValues(report.rows.map((row) =\u003e row.cells.map((cell) =\u003e cell.value)));\n\n console.log('Report spreadsheet created: %s',\n spreadsheet.getUrl());\n}\n\n/**\n * Escape special characters for a parameter being used in a filter.\n * @param {string} parameter The parameter to be escaped.\n * @return {string} The escaped parameter.\n */\nfunction escapeFilterParameter(parameter) {\n return parameter.replace('\\\\', '\\\\\\\\').replace(',', '\\\\,');\n}\n\n/**\n * Returns the JSON representation of a Date object (as a google.type.Date).\n *\n * @param {string} paramName the name of the date parameter\n * @param {Date} value the date\n * @return {object} formatted date\n */\nfunction dateToJson(paramName, value) {\n return {\n [paramName + '.year']: value.getFullYear(),\n [paramName + '.month']: value.getMonth() + 1,\n [paramName + '.day']: value.getDate()\n };\n}\n```"]]