Fetch GCLID from Google Analytics 4 API

GCLID data reports stored in Google Analytics can be fetched along with other metrics using the GA4 API. This process is easier than you think. All you need is a Google Analytics property where you store the GCLIDs and a few lines of code. In this article, we’ll explain how you can view reports of your GCLIDs in Google Spreadsheets, thanks to the GA4 API and Apps Script. 

On this post

    Preparing Google Analytics 4 Property to Store GCLID 

    Before continuing, you need to ensure that your Google Analytics 4 property is already stores the GCLIDs of the visitors. To do this, you first need to create a custom dimension for GCLIDs in your GA4 property. You can then use Google Tag Manager to capture your visitors’ GCLIDs and send them to Google Analytics for storage.

    If you haven’t completed this setup on your property, see our article on how to add GCLIDs to Google Analytics. After completing the installation, you can continue. (article link will be added)

    Fetching Data with GA4 API on Google Apps Script

    uA8o3Uuy8aedTWIwtrHVqZSdWTr8FO 3jQTgqrQUsfEe7H61tnlw LClSuKCI KAsg72gTfNq5m7MuAwvHoBmJLg1XXn1S hE6PnFa6EN0Fr3e3VB3b14RhYJGXiKKCJMtGe2YX4Xj13SIwC2NhLcPbkGcy0vfM9sedXwJ8aKX2D1o29GbaOmsm4IrWgcA PEMAVOR

    The GA4 API provides Google Analytics users the ability to learn about the structure of their accounts and view reports on their performance. For example, using the GA4 API, you can create a report to get the number of active users by city in a certain date range with the help of a few lines of code. All you have to do is send a request to the API by specifying the property, dimension, metric, and date range. You can see how this happens in the sample code below.

    GwNQVT4UYCW7u 6fl4VwSuxEAtN8ko48SQwGZo1IFi2LrcnSSf QBWS8NCgsw O2Y NNvxgP6wanqUVyHK PEMAVOR

    That’s how easy it is. Get quick access to Analytics reports with just a few lines of code that you can edit and run according to your chosen development environment.

    In this article, we’ll explain how you can view these reports in Google Spreadsheet files using Google Apps Script.

    What is Google Apps Script?

    Google Apps script is a scripting platform developed by Google. While working on spreadsheets or documents, you can automate the workflow and perform API operations for Google products. In this article, we’ll perform Google Analytics API operations with Google Apps script.

    How to Create a Script on Google Sheets

    1. Go to sheets.google.com and create a new spreadsheet file.
    2. Once the page load complete, click “Extensions” then “Apps Script”
    Zxtx2mU07qxIyxCsJ3GCRbukfT80j59aPXXWV2S34TuQW SF6RMAURzBm6L9rmQUAbLOu6QEfqb34OMP6img IfeVhimVIcnv76c8riVcu7D4qztabK83 PEMAVOR
    1. Paste the script code at the end of this article to the code editor.
    2. Edit script parameters. If you are not sure about how to, in the next section we’ll cover this up. 
    PSt05AF9PQzGWz wX1H2TAsdSvh6cmdn0xTCN9DdcToTnJEXqgxxL8 jgmDuysl8LIEF6 sYErIHSrZIg8F6gNvk1H HHpMvKtZg5Vst7jN6W2 LBG3BvII8d6a t7dFV0pA4htTPNmkjARm 8moP Cpr 9qcqCoBy04yhuwwgEs859QRZKIEau2RNLFAw PEMAVOR
    1. Click “+” button next to the “Services” section on the left panel 
    H4mnb2zX pJB85 ATwJ6L9H8piuzkK GPcMUHjB1eAUVNZtFlV3gyKL79ThPJ7eCAOyfNfyBb CUQuoNMKET6i7kuKYC2 VkjOohUcnCdNXyta2IRt1RmSyuZ1nraG42GJGQbS4IFIoL aD PEMAVOR
    1. Find “Google Analytics Data API” on the list and click to select. Click “Add” button.
    ztNHzndYwBXlgbLErCVU6QU7QLyg02vmzlF91Tsex8T QsoqZAkH4kHEzERpTbKrjJD7WDrQOMRDP0 NZrYQyLTM6txylSzhfy9pilbnGQQW T9 WjZ 14cfeIqnww42zmhkhNRlUeFo2IUeZddJxkVcOZ2Y7P3A7qAvvwGOdoJjmIhH QGo3D0NJsB20Q PEMAVOR
    1. Click “Save” button to save code, or by pressing “Ctrl + S”
    2. Select “runReport” from the function list. (required for first run only)
    image 168 PEMAVOR
    1. Click “Run” button on the top panel (required for first run only)

    uNrOZl2b sz7awWK1i3 Tm PEMAVOR

    1. Authorization prompt will appear to ask you to authorize Google Sheet to access your Google Analytics account. Follow through dialog to authorize.
    2. Click “Review permissions”

    jLUsAVjJiwxZkyYwA0TcCo5imWn2yxXQ2cT5dEoeN6PY1 fDrqpsFbmvAV6EIEFyyBrVTUnXmpQi2GMEoZp2laFZYVF0jaN8ZzTQjPTg1WZnOKB7yLa04rDYC4leZFBSibv okuCwi9lv06 9A4lQvyTabJmratvCd0YwEE78OehZOyTVYrkD l46oO8HQ PEMAVOR

    1. Choose your Google account.
    2. Since the application you’ve just created isn’t verified by Google, it’ll be marked as “unsafe”. It’s not a problem since only you’ll be able to use the app, it’ll not be publicly accessible. So it’s totally safe to continue. 
    3. Click “Advanced” then “Go to Untitled project (unsafe)” (or the name of your project if you saved with a different name already.)
    2eGXblCDj1kWnXTcXtpvtOCh2qSoB6WNTTuyJ MessPskkYUYyVY N41qmHRLYlvT7TmnkLUyjuEzX7LQvJ4PJIZhzoEMvUdkzRurzoc400RMUZPZ2DWEyjSS 1rwZZWAAicPyVRmT l YNPa 802SVbyW6VH9Fx7ayk9nf8SmYrb2QqKeNuvW3l Pazkw PEMAVOR
    1. Click the “Allow” button.
    2. Script will run. You can check “Execution Log” to see details.
    Rujus3qo1d1oB XUqepwKKdNkJhkvUh3Ir8hHRitKbVoh77 JA5PZQ9isscHjHp0gk Y0sTuOQfn9NTNyA6UbOYHta0mm4f2fMPzAc14fTDSOCemP7nwHKVItaZmLUkymOWKhfZu8cfZ0 s bK4nF9Ga6KrX66f9 aEuAywauR KztSVrlbs OO2oTeneA PEMAVOR
    1.  You can now go to check your sheet to see report details. 
    W4CkISRBCmli3iHlYUu 6JhSRpEvD6WLuKbYFbOg eq3wqGNBmZHnFvB7lOIYwDyTS8K1k ig6YwR2ehZFKvk0pJow75nIurt1cJlRCYje4lnJ0OSh3Y41YO2VTIzmB 5l44sDbNTGiYovorYgGI1Xm 90mwQ5dEGh59FtEc1cWrczcob3gyRHRV3ITWZw PEMAVOR
    1.  After you refresh your page, you’ll be able to see a new menu item called “GCLID Report”. You can create a new sheet and click to the “GCLID Report > Fetch Report” to fetch report in every sheet you want to. 
    VZiYhZma0KBASW9 OxEIKDG s2CCoLC PyaiPppvFmAOBHdYlnwiR7wh6XHWA5u 5zttywSuctoal tFz29ew9Z2GNcCILP8VvNJigiICH4fzS3pjm1j0cg3NRHMdFJtVchzpJtzvS32wtRJnn D2VGDP CO1t8efr9gaE 9FvBP7TkRH3f8W Dh9 HjBg PEMAVOR

    How to Edit Script for your own GA4 Property

    With this script, we transfer a GA4 report to Google Sheet in the simplest way. However, if you use this script without editing, you’ll encounter errors. To prevent this, you need to edit the necessary parameters according to your own GA4 specification.

    Your GA4 Property ID

    At the xth line of script, you’ll see const propertyId = ‘255599xxx’ parameter. You’ll need to replace ‘255599xx’ with your own GA4 property ID. To do this, you’ll need to:

    1. Login to Google Analytics,
    2. Click “Admin” button on the left bottom,
    3. On the middle panel, you’ll see your Property Id.

    PJcTdVD7U8nFe15YGZooB6ufZCGWOXIY0ZmWp HeeEeTwfy6Ro8NBU4XfDOQsc6XBSrzE4b iKjnwLl2SFlcVA84HCtAJHPXQ0QY P3MWQbI28CjkeY16kn PEMAVOR

    Metrics You Need

    If the metrics in the script do not meet your needs, you can replace them with other metrics you would like to. In order to do this, you need to make sure that the metric name is spelled correctly. To access the metrics list, you can visit the relevant Google Documentation page.

     (link will be added to the text) https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema?hl=en#metrics

    Your GCLID Dimension

    GCLID is a custom added dimension that is not available by default in Google Analytics. So depending on how you created this dimension, your dimension Id may differ. 

    Be sure to replace the field with your own GCLID dimension Id. Just as dimension.name = ‘customUser:your_dimension_id; 

    Full App’s Script Code To Fetch GCLID Report From Google Analytics 4

    /**
     * Runs a report of a Google Analytics 4 property ID. 
     */
    function runReport() {
      /**
       * TODO(developer):  Edit Google Analytics 4 property ID before running the sample.
       */
      const propertyId = '255599xxx';
      try {
        const metrics =  [
          { "name": "averageSessionDuration" },
              { "name": "bounceRate" }
          //add more metrics in this format {"name":"metricName"},
          //See avaiable metrics https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema?hl=en#metrics
           ]
      
        //Replace "gclid" field below with the GCLID custom definition id in your GA4 property
         const dimension =[
        {"name" : "customUser:gclid"}
       ]
        const dateRange = AnalyticsData.newDateRange();
        //Edit report start-end date if necessary
        dateRange.startDate = '2020-03-31';
        dateRange.endDate = 'today';
        const request = AnalyticsData.newRunReportRequest();
        request.dimensions = dimension;
        request.metrics = metrics;
        request.dateRanges = dateRange;
      
    
        const report = AnalyticsData.Properties.runReport(request, 'properties/' + propertyId);
        if (!report.rows) {
          Logger.log('No rows returned.');
          return;
        }
    
      const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();  
      const sheet =  SpreadsheetApp.getActiveSheet()
    
        // Append the headers.
        const dimensionHeaders = report.dimensionHeaders.map(
            (dimensionHeader) => {
              return dimensionHeader.name;
            });
        const metricHeaders = report.metricHeaders.map(
            (metricHeader) => {
              return metricHeader.name;
            });
        const headers = [...dimensionHeaders, ...metricHeaders];
    
        sheet.appendRow(headers);
    
        // Append the results.
        const rows = report.rows.map((row) => {
          const dimensionValues = row.dimensionValues.map(
              (dimensionValue) => {
                return dimensionValue.value;
              });
          const metricValues = row.metricValues.map(
              (metricValues) => {
                return metricValues.value;
              });
          return [...dimensionValues, ...metricValues];
        });
    
        sheet.getRange(2, 1, report.rows.length, headers.length)
            .setValues(rows);
    
        Logger.log('Report spreadsheet created: %s',
            spreadsheet.getUrl());
      } catch (e) {
        Logger.log(e)
        // TODO (Developer) - Handle exception
        Logger.log('Failed with error: %s', e.error);
      }
    }
    
     
    
    function onOpen() {
      var ui = SpreadsheetApp.getUi();
      // Or DocumentApp or FormApp.
      ui.createMenu('GCLID Report')
          .addItem('Fetch Report', 'runReport')
          .addToUi();
    }
    

    More Similar Posts