Stay organized with collections
Save and categorize content based on your preferences.
The Analytics service allows you to use the Google Analytics
Management API and
Reporting APIs in Apps Script. These APIs
gives Analytics users 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 various Google Analytics APIs:
Like all advanced services in Apps Script, the Analytics 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, see the corresponding support pages:
/** * Lists Analytics accounts. */functionlistAccounts(){try{constaccounts=Analytics.Management.Accounts.list();if(!accounts.items||!accounts.items.length){console.log('Noaccountsfound.');return;}for(leti=0;i < accounts.items.length;i++){constaccount=accounts.items[i];console.log('Account:name"%s",id"%s".',account.name,account.id);// List web properties in the account.listWebProperties(account.id);}}catch(e){// TODO (Developer) - Handle exceptionconsole.log('Failedwitherror:%s',e.error);}}/** * Lists web properites for an Analytics account. * @param {string} accountId The account ID. */functionlistWebProperties(accountId){try{constwebProperties=Analytics.Management.Webproperties.list(accountId);if(!webProperties.items||!webProperties.items.length){console.log('\tNowebpropertiesfound.');return;}for(leti=0;i < webProperties.items.length;i++){constwebProperty=webProperties.items[i];console.log('\tWebProperty:name"%s",id"%s".',webProperty.name,webProperty.id);// List profiles in the web property.listProfiles(accountId,webProperty.id);}}catch(e){// TODO (Developer) - Handle exceptionconsole.log('Failedwitherror:%s',e.error);}}/** * Logs a list of Analytics accounts profiles. * @param {string} accountId The Analytics account ID * @param {string} webPropertyId The web property ID */functionlistProfiles(accountId,webPropertyId){// Note: If you experience "Quota Error: User Rate Limit Exceeded" errors// due to the number of accounts or profiles you have, you may be able to// avoid it by adding a Utilities.sleep(1000) statement here.try{constprofiles=Analytics.Management.Profiles.list(accountId,webPropertyId);if(!profiles.items||!profiles.items.length){console.log('\t\tNowebpropertiesfound.');return;}for(leti=0;i < profiles.items.length;i++){constprofile=profiles.items[i];console.log('\t\tProfile:name"%s",id"%s".',profile.name,profile.id);}}catch(e){// TODO (Developer) - Handle exceptionconsole.log('Failedwitherror:%s',e.error);}}
Run a report
The sample runs a report to retrieve the top 25 keywords and traffic sources
and stores the results in a new spreadsheet.
/** * Runs a report of an Analytics profile ID. Creates a sheet with the report. * @param {string} profileId The profile ID. */functionrunReport(profileId){consttoday=newDate();constoneWeekAgo=newDate(today.getTime()-7*24*60*60*1000);conststartDate=Utilities.formatDate(oneWeekAgo,Session.getScriptTimeZone(),'yyyy-MM-dd');constendDate=Utilities.formatDate(today,Session.getScriptTimeZone(),'yyyy-MM-dd');consttableId='ga:'+profileId;constmetric='ga:visits';constoptions={'dimensions':'ga:source,ga:keyword','sort':'-ga:visits,ga:source','filters':'ga:medium==organic','max-results':25};constreport=Analytics.Data.Ga.get(tableId,startDate,endDate,metric,options);if(!report.rows){console.log('Norowsreturned.');return;}constspreadsheet=SpreadsheetApp.create('GoogleAnalyticsReport');constsheet=spreadsheet.getActiveSheet();// Append the headers.constheaders=report.columnHeaders.map((columnHeader)=>{returncolumnHeader.name;});sheet.appendRow(headers);// Append the results.sheet.getRange(2,1,report.rows.length,headers.length).setValues(report.rows);console.log('Reportspreadsheetcreated:%s',spreadsheet.getUrl());}
[[["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 2024-12-19 UTC."],[[["The Analytics service enables the use of Google Analytics Management and Reporting APIs within Apps Script to access account structure and performance data."],["This advanced service requires prior enabling before utilization and mirrors the functionality of the public Google Analytics APIs."],["Provided sample code demonstrates listing account structures (accounts, web properties, and profiles) and running reports to extract keyword and traffic source data."],["Comprehensive reference documentation and support pages for various Google Analytics APIs are linked for further information and troubleshooting."]]],[]]