Use Google Analytics API from Python

Google Developers tutorial doesn't work

Perhaps if you want to use the Google Analytics API from Python, [Python Quick Start](https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/service-py?hl=ja# Did you see enable)? However, if you go this way, in step 3

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    from oauth2client.client import SignedJwtAssertionCredentials
ImportError: cannot import name SignedJwtAssertionCredentials

It didn't work next to me. (As of March 20, 2016)

As conclusion The solution was to use ServiceAccountCredentials instead ofSignedJwtAssertionCredentials.

This time, I applied this change and created sample that outputs the ranking of the number of pageviews.

How to use

python uses Python 2.7.6.

Go to step 2 of Python Quick Start

Please get.

Download the Github repository. Place the P12 key file you created earlier in the downloaded folder.

Prepare the json file

cp config.json.sample config.json

Edit the contents of config.json as follows.

{
    "email": "<your google developer email adress> ex) [email protected] ",
    "key": "<*.p12 path> ex) ./sample-5a5a55a5a5a5.p12",

"start_date": "Start date of ranking period ex) 2016-02-07", "end_date": "End date of ranking period ex) 2016-03-07", "home": "URL of page to analyze ex) http://qiita.com" }

Put the following two with pip

sudo pip install --upgrade google-api-python-client
pip install pyopenssl

I will do it

python googel_analystic_api_ranking.py

Commentary

The following parts determine the content of the ranking.

def get_rankings_results(service, profile_id, config):
    return service.data().ga().get(
        ids='ga:' + profile_id,
        start_date=config['start_date'],
        end_date=config['end_date'],
        sort='-ga:pageviews',
        max_results='10',
        dimensions='ga:pageTitle,ga:pagePath',
        metrics='ga:pageviews').execute()

sort ='-ga: pageviews', is sorted by ga: pageviews and is acquired in descending order by the first-. The Analytics API gets the results in the form of a matrix. At this time, specify the upper limit of the number of rows of the result acquired by the API with max_results. Also, the contents to be acquired are decided by dimensions and metrics. This time, dimensions specifies the page title and page path, and metrics specifies the number of page views. As an image, you can see metrics for each dimensions.

The result is output in the following part.

def print_rankings_results(results, home):
    # Print data nicely for the user.
    if results:
        print(u'-----------Ranking Top 10-----------')
        for col in results.get('rows'):
            print(u'{0}\t{1}{2}\t{3}'.format(col[0], home, col[1], col[2]))
    else:
        print ('No results found')

The argument results contains the response from the API obtained by the previous get_rankings_results. You can also access each row of results with'results.get ('rows')'. The results are arranged in the order of dimensions, metrics, so you can get the pagePath of the first result by doing'results.get ('rows') [0] [1]'.

Recommended Posts

Use Google Analytics API from Python
Use Google Cloud Vision API from Python
Use e-Stat API from Python
Forcibly use Google Translate from python
Use the Flickr API from Python
Get data from analytics API with Google API Client for python
Use thingsspeak from python
Use fluentd from python
Use MySQL from Python
Use MySQL from Python
Use BigQuery from python.
Use mecab-ipadic-neologd from python
Run Google Analytics API (core v3) in python
Use Trello API with python
Use Twitter API with Python
Use MySQL from Anaconda (python)
Use subsonic API with python3
Google Drive Api Tips (Python)
Data acquisition from analytics API with Google API Client for python Part 2 Web application
[Python] Hit the Google Translation API
Read and use Python files from Python
How to use OpenPose's Python API
Use Azure Blob Storage from Python
Get upcoming weather from python weather api
Run Ansible from Python using API
Use fastText trained model from Python
Handle SOAP API from Python (Zeep)
Python: Extract file information from shared drive with Google Drive API
[SEO] Flow / sample code when using Google Analytics API in Python
Google Cloud Vision API sample for python
[Python] Web application from 0! Hands-on (3) -API implementation-
Use PostgreSQL data type (jsonb) from Python
Python: Reading JSON data from web API
How to update Google Sheets from Python
Use machine learning APIs A3RT from Python
I want to use jar from python
Get Google Fit API data in Python
I tried using UnityCloudBuild API from Python
Use Django from a local Python script
Use C ++ functions from python with pybind11
API explanation to touch mastodon from python
Connect to coincheck's Websocket API from Python
Python calling Google Cloud Vision API from LINE BOT via AWS Lambda
sql from python
Use JIRA API
MeCab from Python
Csv output from Google search with [Python]! 【Easy】
Firebase: Use Cloud Firestore and Cloud Storage from Python
Procedure to use TeamGant's WEB API (using python)
Study from Python Hour7: How to use classes
[Bash] Use here-documents to get python power from bash
Wrap C with Cython for use from Python
Tweet (API 1.1) on Google App Engine for Python
How to use the Google Cloud Translation API
Until you can use the Google Speech API
Use Python in your environment from Win Automation
I want to use ceres solver from python
Google Colaboratory 90-minute session disconnection countermeasures --- Use Python! ---
Let's use different versions of SQLite3 from Python3!
[Google Cloud Platform] Use Google Cloud API using API Client Library
Use the nghttp2 Python module from Homebrew from pyenv's Python