Get data from analytics API with Google API Client for python

reference https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/installed-py

Sample class

class GoogleAnalyticsUtility(object):
    SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
    DISCOVERY_URI = ('https://analyticsreporting.googleapis.com/$discovery/rest')
    VIEW_ID = 'xxxx'

    def __init__(self, target_date):
        self.target_date = target_date

    def get_report(self):
        parser = argparse.ArgumentParser(
                formatter_class=argparse.RawDescriptionHelpFormatter,
                parents=[tools.argparser])
        flags = parser.parse_args(['--noauth_local_webserver'])
        CLIENT_SECRETS_PATH = os.path.join(settings.BASE_DIR, '../etc/googleapi/client_id.json')
        flow = client.flow_from_clientsecrets(
                CLIENT_SECRETS_PATH, scope=self.SCOPES,
                message=tools.message_if_missing(CLIENT_SECRETS_PATH))

        storage = file.Storage(os.path.join(settings.BASE_DIR, '../etc/googleapi/analyticsreporting.dat'))
        credentials = storage.get()
        if credentials is None or credentials.invalid:
            credentials = tools.run_flow(flow, storage, flags)
        http = credentials.authorize(http=httplib2.Http())
        analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=self.DISCOVERY_URI)
        reports = analytics.reports()
        return reports.batchGet(
                body={
                    'reportRequests': [
                        {
                            'viewId': self.VIEW_ID,
                            'dateRanges': [{'startDate': self.target_date, 'endDate': 'today'}],
                            "dimensions": [
                                {
                                    "name": "ga:productSku",  #The product code of the item sold.
                                }],
                            'metrics': [
                                {'expression': 'ga:itemQuantity'}  #The number of items sold in an e-commerce transaction.
                            ],
                            'pageSize': 50000,
                            'pageToken': "nextpage",
                            "orderBys":
                                [
                                    {"fieldName": "ga:itemQuantity", "sortOrder": "DESCENDING"},
                                ]
                        }]
                }
        ).execute()

target_date = date.today() - timedelta(days=7)
ga = GoogleAnalyticsUtility(target_date.strftime('%Y-%m-%d'))
ga.get_report()

If you hit it on the command line, a link will be displayed, so copy and paste it into your browser to complete the authentication.

https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics.readonly&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&response_type=code&client_id=xxxxx-gd5j31ge4jdobhlg9a3jqnveae34cag1.apps.googleusercontent.com&access_type=offline

Recommended Posts

Get data from analytics API with Google API Client for python
Data acquisition from analytics API with Google API Client for python Part 2 Web application
Use Google Analytics API from Python
Play with YouTube Data API v3 using Google API Python Client
[Note] Get data from PostgreSQL with Python
Get Google Fit API data in Python
Get stock price data with Quandl API [Python]
Get Youtube data with python
Get schedule from Garoon SOAP API with Python + Zeep
[Python] Get insight data using Google My Business API
Get data from database via ODBC with Python (Access)
Get data from Quandl in Python
Get reviews with python googlemap api
[Python] Get economic data with DataReader
Python: Extract file information from shared drive with Google Drive API
Get data from MySQL on a VPS with Python 3 and SQLAlchemy
Get US stock price from Python with Web API with Raspberry Pi
Collecting information from Twitter with Python (Twitter API)
Get additional data in LDAP with python
Google Cloud Vision API sample for python
[google-oauth] [python] Google APIs Client Library for Python
Receive textual data from mysql with python
Get html from element with Python selenium
Simple Slack API client made with Python
Retrieving food data with Amazon API (Python)
Python: Reading JSON data from web API
Get data from Cloudant with Bluemix flask
Get Youtube data in Python using Youtube Data API
Use Google Cloud Vision API from Python
Get holidays with the Google Calendar API
[Python] Get Python package information with PyPI API
Get data from an oscilloscope with pyVISA
Creating Google Spreadsheet using Python / Google Data API
Edit Slide (PowerPoint for Google) with Python (Low-cost RPA case with Google API and Python)
Copy data from Amazon S3 to Google Cloud Storage with Python (boto)
Get time series data from k-db.com in Python
Csv output from Google search with [Python]! 【Easy】
Get a ticket for a theme park with python
[Python] Get all comments using Youtube Data API
Run Google Analytics API (core v3) in python
Wrap C with Cython for use from Python
I tried to get CloudWatch data with Python
~ Tips for Python beginners from Pythonista with love ① ~
Get Gmail subject and body with Python and Gmail API
Wrap C ++ with Cython for use from Python
~ Tips for Python beginners from Pythonista with love ② ~
Extract data from a web page with Python
Get users belonging to your organization from Garoon REST API with Python + Requests
[Introduction to Python] How to get the index of data with a for statement
Data analysis with python 2
Get date with python
Data analysis with Python
[GCP] [Python] Deploy API serverless with Google Cloud Functions!
[First API] Try to get Qiita articles with Python
Data analysis for improving POG 1 ~ Web scraping with Python ~
Export access data for each user of Google Analytics.
How to scrape image data from flickr with python
[Python] Get the text of the law from the e-GOV Law API
Get financial data with python (then a little tinkering)
Get LEAD data using Marketo's REST API in Python
Get data from GPS module at 10Hz in Python