javascriptgoogle-analytics-apigoogle-analytics-firebasegoogle-analytics-sdk

Accessing Google Analytics Data With API Key Only


I'm trying to use Google Analytics API in Javascript. I want to:

Every example I can find requires you to use OAuth to authenticate before you can query data. Because I only want to query (not delete/modify), is there a way to use a simple API Key to grab the data I need?


Solution

  • Yes and No. The Google Analytics Core Reporting API is an Authenticated API and requires the use of OAuth2, authorized with the appropriate scope:

    https://www.googleapis.com/auth/analytics.readonly
    

    The API key simply identifies your Google Project, it does not necessarily grant you authorization to read the data of your Google Analytics Accounts, even if that account is associated with the same Google Login. The API key is usually public and lives on the client browsers, it would not be secure to grant access to anyone's Google Analytics Account data simply if they had access to a particular key.

    What you are going to need to do is use a service account to access the data. Take a look at the Google Analytics Demos and Tools site. There they have a really good example example of using a service account server side to generate an access token and then has the JavaScript Client library make the final request. Alternatively you could build something akin to the Google Analytics Super Proxy which can query the API on your behalf and generates a public URL which can then be queried separately.