How To Get Google Analytics Data Using Api

Google Analytics is a valuable resource for webmasters who wish to monitor their website’s performance. In certain cases, there may be a need to extract this data programmatically for additional analysis or integration with other platforms. Fortunately, Google offers an Application Programming Interface (API) specifically for Google Analytics to enable such capabilities.

Step 1: Enable Google Analytics API

The first step is to enable the Google Analytics API for your project in the Google Cloud Console. Log into the console, navigate to the APIs & Services dashboard, and enable the Google Analytics Reporting API.

Step 2: Create Credentials

Next, you need to create credentials that your application will use to authenticate with the API. Still in the APIs & Services dashboard, go to the Credentials section and create a new OAuth 2.0 client ID.

Step 3: Install Google Client Library

If you’re using Python for your project, you can install the Google Client Library by running the following command at your terminal: pip install –upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib.

Step 4: Set Up API Request

Now you can set up your API request. Here is a basic example of what your code might look like:

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import httplib2

# define the scope
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']

# define your service account
KEY_FILE_LOCATION = '<path_to_your_json_key_file>'
VIEW_ID = '<your_view_id>'

def initialize_analyticsreporting():
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        KEY_FILE_LOCATION, SCOPES)

    # Build the service object
    analytics = build('analyticsreporting', 'v4', credentials=credentials)

    return analytics

Replace <PATH_TO_YOUR_JSON_KEY_FILE> with the path to the JSON key file you downloaded when you created your credentials. Replace <YOUR_VIEW_ID> with the ID of the specific view you want to access data for.

Step 5: Make API Request

Finally, you can make an API request to retrieve your Google Analytics data as shown in the following code:

def get_report(analytics):
    return analytics.reports().batchGet(
        body={
            'reportRequests': [
                {
                    'viewId': VIEW_ID,
                    'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
                    'metrics': [{'expression': 'ga:sessions'}],
                    'dimensions': [{'name': 'ga:country'}]
                }]
        }
    ).execute()

def print_response(response):
    for report in response.get('reports', []):
        columnHeader = report.get('columnHeader', {})
        dimensionHeaders = columnHeader.get('dimensions', [])
        metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
        rows = report.get('data', {}).get('rows', [])

        for row in rows:
            dimensions = row.get('dimensions', [])
            dateRangeValues = row.get('metrics', [])

            for header, dimension in zip(dimensionHeaders, dimensions):
                print(header + ': ' + dimension)

            for i, values in enumerate(dateRangeValues):
                for metricHeader, value in zip(metricHeaders, values.get('values')):
                    print(metricHeader.get('name') + ': ' + value)

def main():
    analytics = initialize_analyticsreporting()
    response = get_report(analytics)
    print_response(response)

if __name__ == '__main__':
    main()

This code retrieves and prints the number of sessions per country for the past 7 days.

Conclusion

By following these steps, you can harness the power of Google’s data and extract Google Analytics data using API. Keep in mind the outlined steps above are basic and for more complex data extraction, the request and response handling might be more intricate.