Run Google Analytics API (core v3) in python

testga.py


# -*- coding: utf-8 -*-
# Google Analytics API

import yaml
import datetime
import httplib2
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client import tools
import argparse

CLIENT_SECRETS = 'client_secrets.json'

# The Flow object to be used if we need to authenticate.
FLOW = flow_from_clientsecrets(
    CLIENT_SECRETS,
    scope='https://www.googleapis.com/auth/analytics.readonly',
    message='%s is missing' % CLIENT_SECRETS
    )

# A file to store the access token
TOKEN_FILE_NAME = 'credentials.dat'

def prepare_credentials():
    parser = argparse.ArgumentParser(parents=[tools.argparser])
    flags = parser.parse_args()
    # Retrieve existing credendials
    storage = Storage(TOKEN_FILE_NAME)
    credentials = storage.get()
    # If no credentials exist, we create new ones
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(FLOW, storage, flags)
    return credentials 

def initialize_service():
    http = httplib2.Http()
    credentials = prepare_credentials()
    http = credentials.authorize(http)
    return build('analytics', 'v3', http=http)


#API execution(core API)
def get_ga_data(service, profile_id, start_date, end_date):
    ids = "ga:" + profile_id
    metrics = "ga:pageviews"
    dimensions = "ga:Year,ga:month,ga:day,ga:pagetitle"
    filter = "ga:pageviews>=100"
    data = service.data().ga().get(
        ids=ids, start_date=start_date, end_date=end_date, metrics=metrics,
        dimensions=dimensions, filters=filter).execute()
    return data

# main
if __name__ == '__main__':
    service = initialize_service()
    profile_id = "12345678"  #Profile ID of the target site
    start_date = "2017-01-01"
    end_date = "2017-01-10"
    data = get_ga_data(service, profile_id, start_date, end_date)
    row = data["rows"]
    nm = ['ga_year','ga_month','ga_day','ga_pageTitle','ga_pageviews'] 
    lst = []
    for i in row:
        d = dict(zip(nm,i))
        lst.append(d)
    print(lst)
    print("finish!")  

-Enable the Google Analytics API in the Google Developers Console ・ Obtain an authentication token for oauth from google Developers as well. (File name: client_secrets.json) ・ At the first access, the browser is displayed and Google's Oauth authentication is performed, and credentials.dat is generated at that time (Oauth authentication can be omitted from the second time onward based on this credentials.dat) -In the above script, get_ga_data () is used to execute the Google Analytics API to get the data, and finally the dictionary dict format is [Store data in the nearest RDB with SQLAlchemy](http: // qiita. for com / Fortinbras / items / 884b140de5af10183738)

Recommended Posts

Run Google Analytics API (core v3) in python
Use Google Analytics API from Python
Get Google Fit API data in Python
[SEO] Flow / sample code when using Google Analytics API in Python
Evernote API in Python
C API in Python 3
[WP REST API v2] Upload images in Python
Try using the DropBox Core API in Python
Run Qiita API v2 Python wrapper in Python3 environment (Mac OS X 10.11 (El Capitan))
Upload JPG file using Google Drive API in Python
Speech file recognition by Google Speech API v2 using Python
Run automatic jobs in python
Run Python unittests in parallel
Blender Python API in Houdini (Python 3)
Google Drive Api Tips (Python)
[LINE Messaging API] Issue channel access token v2.1 in Python
Get data from analytics API with Google API Client for python
[CLPEX memo] Run DO Python API in COS installed environment
Issue reverse geocoding in Japanese with Python Google Maps API
Play with YouTube Data API v3 using Google API Python Client
Getting the arXiv API in Python
Hit the Sesami API in Python
Run shell command / python in R
Run Rotrics DexArm with python API
[Python] Hit the Google Translation API
[Python3] Google translate google translate without using api
Download Google Drive files in Python
Create Gmail in Python without API
Hit the web API in Python
Quickly implement REST API in Python
Run unittests in Python (for beginners)
Run Ansible from Python using API
Run a simple algorithm in Python
Access the Twitter API in Python
Regularly upload files to Google Drive using the Google Drive API in Python
Google Cloud Vision API sample for python
Mouse operation using Windows API in Python
Try using the Wunderlist API in Python
Try using the Kraken API in Python
[Python] Run Flask on Google App Engine
Tweet using the Twitter API in Python
Run AzureKinect in Python on Christmas Eve.
Run the Python interpreter in a script
Get Youtube data in Python using Youtube Data API
Use Google Cloud Vision API from Python
Quickly try Microsoft's Face API in Python
Try hitting the YouTube API in Python
Make cron-like jobs run regularly in Python
Creating Google Spreadsheet using Python / Google Data API
Implemented Python wrapper for Qiita API v2
Run Python in C ++ on Visual Studio 2017
Data acquisition from analytics API with Google API Client for python Part 2 Web application
First steps to try Google CloudVision in Python
Receive websocket of kabu station ® API in Python
Play with Google Spread Sheets in python (OAuth)
Type Python scripts to run in QGIS Processing
Unattended operation of Google Spreadsheets (etc.) in Python
Put text scraped in Python into Google Sheets
Run Python YOLOv3 in C ++ on Visual Studio 2017
Try using the BitFlyer Ligntning API in Python
One liner to 100% CPU1 core usage in Python