[Python] Get insight data using Google My Business API

Introduction

I couldn't find much information in Japanese to get insight data using Google My Business API, so I'll keep it as a memorandum.

reference

https://developers.google.com/my-business/content/prereqs Google API OAuth 2.0 access token & refresh token acquisition procedure February 2017 version

environment

Python(3.6.2)

What is Google My Business?

Google My Business is a free service that allows you to display registered business information on Google Maps and Google Search provided by Google. By registering your own business (restaurants, beauty salons, dentists, etc.) in this service, you can make the business easier for users to see when searching or browsing the map.

What is Google My Business API?

It is a function that allows you to acquire, register, update, and delete business information registered in Google My Business. For example, you can reply to reviews posted on business, get access information (insight data) for business, edit shop menus, add photos, etc. systematically using API. I can do it. In this article, I will explain how to get insight data.

What is insight data?

This data allows you to check how users found and accessed Google My Business information (restaurants, beauty salons, dentists, etc.). Specifically, you can check the data related to the following items.

・ How the user searched the GMB page ・ Search query ・ Google service used by users to search GMB pages ・ User behavior ・ Number of calls made by users ・ Number of registered photos viewed ・ ・ ・ Etc

Preparations required to use the API

To use the Google My Business API, you need to take the following four steps.

  1. Create a project in Google API Console
  2. Request access to the API
  3. Enable the Google My Business API
  4. Get credentials

1. Create a project in the Google API console

After creating a Google account

1-1. Go to Google API Console 1-2. Click "Create Project", enter the project name and click "Create"

2. Request access to the API

2-1. Go to Google API Console Select the project created in 2-2-1 2-3. Check the project ID in [Project ID] 2-4. Fill in and submit the Access Request Form. 2-5. After the submitted content is reviewed, you will receive a follow-up email, so reply

In my case, about two weeks after I submitted it, an English email (the email below) stating "Did you apply for a request to the Google My Business API?" Was sent to the email address you entered in the request form. ..

314efba9913dbb67409475013a389e1e.png

I replied in simple English, "Yes, I applied.", And a few days later, I received an email to the effect that I was allowed to use the API (the email below).

3a9d0d6e5e0b4402156fe4bcfcf4128a-min.png

Please note the following points when filling out the form. (1) You will be asked to enter the email address of the Google account that created the project and the URL of the company's homepage, but the URL and the domain of the email address must match. (2) You will also be asked to enter the company's Google My Business account, so if you do not have one, you need to create one in advance.

3. Enable the Google My Business API

3-1. Go to Google API Console. 3-2. Click "Library" from the left menu of the screen 3-3. Search and click Google My Business API 3-4. Click the "Enable" link at the top center of the screen

4. Get credentials

You will need an access token to make a request to the API. Even if this access token is issued once, it will be invalid after a certain period of time, but it can be reissued if you have a client ID, client secret, and refresh token. Therefore, get this information in order to use the API.

Google API OAuth 2.0 access token & refresh token acquisition procedure February 2017 version

Get insight data

Once you have the credentials, you can get the insight data by accessing the API using Python.

1. Get an access token

import requests

data = [
  ('grant_type', 'refresh_token'),
  ('client_id', '978904852xx-xxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com'),
  ('client_secret', 'qlDgUPlOIxxxxxxx5-L0yW'),
  ('refresh_token', '1/9OEydqvV2IExxxxxxxxxxxxxxxxxxx00vWVQ1CCs'),
]

response = requests.post('https://accounts.google.com/o/oauth2/token', data=data)

json = response.json()
access_token = json['access_token']

2. Get an account ID

Get the user account that manages each GMB account.


headers = {
    'Authorization': 'Bearer ' + access_token,
}

response = requests.get('https://mybusiness.googleapis.com/v4/accounts', headers=headers)
json = response.json()

account_id = json['accounts'][0]['name'].replace('accounts/','')

3. Get the location name

Use the account ID obtained in step 2 to get the location name given to each GMB account.


headers = {
    'Authorization': 'Bearer ' + access_token,
}

response = requests.get('https://mybusiness.googleapis.com/v4/accounts/'+account_id+'/locations', headers=headers)
json = response.json()

location_name = json['locations'][0]['name']

4. Get insight data using an access token

Once you have your account ID, location name and access token, you can get insight data with the code below.


headers = {
    'Authorization': 'Bearer ' + access_token,
}

#You can set the target period of insight data with startTime and endTime.
data = '{\'locationNames\':[\''+location_name+'\',],\'basicRequest\':{\'metricRequests\':[{\'metric\':\'ALL\'}],\'timeRange\':{\'startTime\':\'2020-10-01T04:00:00.00000000Z\',\'endTime\':\'2020-10-2T04:00:00.00000000Z\',},},}'

response = requests.post('https://mybusiness.googleapis.com/v4/accounts/'+account_id+'/locations:reportInsights', headers=headers, data=data)

json = response.json()

Insight Data: How Users Find Your Business Information

#Direct search
QUERIES_DIRECT = json['locationMetrics'][0]['metricValues'][0]['totalValue']['value']
#Indirect search
QUERIES_INDIRECT = json['locationMetrics'][0]['metricValues'][1]['totalValue']['value']
#Brand search
QUERIES_CHAIN = json['locationMetrics'][0]['metricValues'][2]['totalValue']['value']

Insight Data: Google services that users use to search for your business information

#Display via map
VIEWS_MAPS = json['locationMetrics'][0]['metricValues'][3]['totalValue']['value']
#Display via search
VIEWS_SEARCH = json['locationMetrics'][0]['metricValues'][4]['totalValue']['value']

Insight Data: User Behavior

#Access to the website
ACTIONS_WEBSITE = json['locationMetrics'][0]['metricValues'][5]['totalValue']['value']
#Number of users who called
ACTIONS_PHONE = json['locationMetrics'][0]['metricValues'][6]['totalValue']['value']
#Route request
ACTIONS_DRIVING_DIRECTIONS = json['locationMetrics'][0]['metricValues'][7]['totalValue']['value']

[Insight data]: View / number of photos

#Number of photos viewed(Other companies in the same industry)
PHOTOS_VIEWS_MERCHANT = json['locationMetrics'][0]['metricValues'][8]['totalValue']['value']
#Number of photos viewed(Customer)
PHOTOS_VIEWS_CUSTOMERS = json['locationMetrics'][0]['metricValues'][9]['totalValue']['value']
#Number of photos posted(Other companies in the same industry)
PHOTOS_COUNT_MERCHANT = json['locationMetrics'][0]['metricValues'][10]['totalValue']['value']
#Number of photos posted(Customer)
PHOTOS_COUNT_CUSTOMERS = json['locationMetrics'][0]['metricValues'][11]['totalValue']['value']

Get evaluation information for your business

headers = {
    'Authorization': 'Bearer '+access_token,
}

response = requests.get('https://mybusiness.googleapis.com/v4/'+location_name+'/reviews', headers=headers)

json = response.json()

#Average value of evaluation
averageRating = json['averageRating']

#Total number of reviews
totalReviewCount = json['totalReviewCount']

Recommended Posts

[Python] Get insight data using Google My Business API
Get Google Fit API data in Python
Creating Google Spreadsheet using Python / Google Data API
[Python] Get all comments using Youtube Data API
Get LEAD data using Marketo's REST API in Python
Get Salesforce data using REST API
Data acquisition using python googlemap api
[Python3] Google translate google translate without using api
Get Amazon data using Keep API # 1 Get data
Get data from analytics API with Google API Client for python
Play with YouTube Data API v3 using Google API Python Client
[Python] I tried to get various information using YouTube Data API!
Get image URL using Flickr API in Python
Get stock price data with Quandl API [Python]
How to get article data using Qiita API
Data analysis using Python 0
Data cleaning using Python
Upload JPG file using Google Drive API in Python
Speech transcription procedure using Python and Google Cloud Speech API
Speech file recognition by Google Speech API v2 using Python
A story about a Python beginner trying to get Google search results using the API
My python data analysis container
Get Youtube data with python
My python data analytics environment
Google Drive Api Tips (Python)
Data analysis using python pandas
Get data using Ministry of Internal Affairs and Communications API
Inflating text data by retranslation using google translate in Python
[Introduction] Artificial satellite data analysis using Python (Google Colab environment)
Get an English translation using python google translate selenium (memories)
[Python] I tried collecting data using the API of wikipedia
Get Leap Motion data in Python.
Get data from Quandl in Python
Get reviews with python googlemap api
[Python] Hit the Google Translation API
Stream speech recognition using Google Cloud Speech gRPC API on python3 on Mac!
How to get followers and followers from python using the Mastodon API
Try using Pleasant's API (python / FastAPI)
[Python] Get economic data with DataReader
My favorite boto3 (Python) API sample
Collect product information and process data using Rakuten product search API [Python]
Data acquisition memo using Backlog API
Get upcoming weather from python weather api
Try using Python argparse's action API
Regularly upload files to Google Drive using the Google Drive API in Python
Run Ansible from Python using API
Get data from Twitter using Tweepy
[SEO] Flow / sample code when using Google Analytics API in Python
Use Google Analytics API from Python
Get additional data in LDAP with python
Google Cloud Vision API sample for python
Mouse operation using Windows API in Python
[Note] Get data from PostgreSQL with Python
Get tweets containing keywords using Python Tweepy
Try using the Kraken API in Python
Retrieving food data with Amazon API (Python)
Python: Reading JSON data from web API
[Beginner] Python web scraping using Google Colaboratory
I tried using YOUTUBE Data API V3
Get mail using Gmail API in Java
Tweet using the Twitter API in Python