2022. 1. 9. 21:24ㆍ구글 애널리틱스(GA)
GA를 활용하여 행동데이터를 수집하고 대시보드를 통한 분석 이외에 API 호출을 통한 데이터를 전송받아 대시보드에서는 나타낼 수 없는 표나 그래프를 작성하거나 해당 데이터를 이용하여 통계분석 등에 사용할 수 있다.
지난 포스트에 이어 이번 포스트에서는 연동을 위한 설정 이후 실제 데이터를 가져오는 방법에 대한 가이드이다.
Google Analytics API 사용법 ①
GA를 활용하여 행동데이터를 수집하고 대시보드를 통한 데이터 분석을 할 수 있다. 하지만 정형화된 솔루션이기 때문에 한계가 있다. 커머스 산업 중심으로 보여지는 전자상거래 대시보드들은
bgradecoding.tistory.com
1. GA에 설정된 맞춤 정의 가져오기
GA 구성을 진행하면 해당 계정에 여러 정보를 만들어야 한다.
GA에서 기본적으로 제공하는 Dimension을 제외하고도
사용자가 필요에 의해 만드는 Custom Dimension(맞춤 측정기준), Custom Metric(맞춤 측정항목)이 있을 것이다.
이외에도 Conversion 요소로 잡는 Goals(목표)과 다양한 그래프 구성을 위한 Segment(세그먼트) 등이 있다.
GA API를 사용하면 이것들을 조회해 올 수 있고 추가, 삭제, 업데이트도 가능하다. 하지만 추가, 삭제, 업데이트의 경우 GA 대시보드에 주는 영향이 클 수 있어 조회만을 API를 활용하는 것을 권장한다.
1) Custom Dimension(맞춤 측정기준)
GA의 UA 버전에서 20개(무료 버전)까지 제공하는 값으로 이벤트 수집시 카테고리, 액션, 라벨으로만 수집하기에는 수집범위가 넓을때 해당 값을 만들어 사용한다.
GA API를 활용하여 이 값들을 가져오도록 하자
지난 글의 Sample 코드를 조금만 변형하고 새로운 메소드를 사용하면 손쉽게 가져올 수 있다.
역시 파이썬을 사용한다.
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.errors import HttpError
from googleapiclient import sample_tools
def get_service(api_name, api_version, scopes, key_file_location):
"""Get a service that communicates to a Google API.
Args:
api_name: The name of the api to connect to.
api_version: The api version to connect to.
scopes: A list auth scopes to authorize for the application.
key_file_location: The path to a valid service account JSON key file.
Returns:
A service that is connected to the specified API.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
key_file_location, scopes=scopes)
# Build the service object.
service = build(api_name, api_version, credentials=credentials)
return service
# Define the auth scopes to request.
scope = 'https://www.googleapis.com/auth/analytics.readonly'
key_file_location = 'API JSON 파일 상대경로' #지난 포스트 참고 ( 예시 : ./JSON명 )
# Authenticate and construct service.
service = get_service(
api_name='analytics',
api_version='v3',
scopes=[scope],
key_file_location=key_file_location)
dimensions = service.management().customDimensions().list(
accountId = 'GA 보기 ID' #지난 포스트 참고,
webPropertyId = 'GA 트레킹 ID' #지난 포스트 참고( 예시 : UA-어쩌고 )
).execute()
# 받아온 값을 출력하기 위한 부분
for dimension in dimensions.get('items', []):
print('Dimension Name '+str(dimension.get('index')) +
' ===== ' + dimension.get('name'))
해당 코드 실행 결과는 아래와 같다.
API를 호출한 GA는 현재 이 블로그와 연결이 되어 있다.
Dimension Name 1 ===== 포스트 제목 Dimension Name 2 ===== 포스트 태그명 Dimension Name 3 ===== 검색어 Dimension Name 4 ===== 포스트 카테고리 |
설정해둔 맞춤 측정항목을 잘 가져오는 것을 알 수 있다.
2) Custom Metric( 맞춤 측정항목 )
Dimension과 다르게 수치값을 저장하는 Custom Metric 또한
GA를 구성하면서 많이 만들어서 사용한다.
Dimension GA API와 마찬가지로 조회, 수정, 삭제, 업데이트가 가능하지만
역시 조회만 사용하기를 권장한다.
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.errors import HttpError
from googleapiclient import sample_tools
def get_service(api_name, api_version, scopes, key_file_location):
"""Get a service that communicates to a Google API.
Args:
api_name: The name of the api to connect to.
api_version: The api version to connect to.
scopes: A list auth scopes to authorize for the application.
key_file_location: The path to a valid service account JSON key file.
Returns:
A service that is connected to the specified API.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
key_file_location, scopes=scopes)
# Build the service object.
service = build(api_name, api_version, credentials=credentials)
return service
# Define the auth scopes to request.
scope = 'https://www.googleapis.com/auth/analytics.readonly'
key_file_location = 'API JSON 파일 상대경로' #지난 포스트 참고 ( 예시 : ./JSON명 )
# Authenticate and construct service.
service = get_service(
api_name='analytics',
api_version='v3',
scopes=[scope],
key_file_location=key_file_location)
dimensions = service.management().customDimensions().list(
accountId = 'GA 보기 ID' #지난 포스트 참고,
webPropertyId = 'GA 트레킹 ID' #지난 포스트 참고( 예시 : UA-어쩌고 )
).execute()
# 받아온 값을 출력하기 위한 부분
for metric in metrics.get('items', []):
print('Metric Name =============== ' + metric.get('name'))
해당 코드를 실행하면 Custom Metric을 조회해 올 수 있다. 결과는 아래와 같다.
Metric Name =============== 포스트 총 조회수 |
이것을 GA에서 확인해 보자
위와 같이 설정된 맞춤 측정기준과 측정항목을 잘 가져온 것을 볼 수 있다.
나머지 사항들( 목표, 세그먼트 )도 똑같은 방식으로 가져온다.
https://developers.google.com/analytics/devguides/config/mgmt/v3/parameters
위 링크를 참조하면 필요한 코드들을 얻어서 GA의 계정정보들을 조회해 올 수 있다.
2. 실제 수집 데이터 조회하기
GA에서 수집된 데이터는 대시보드를 통해 필터를 걸거나 Dimension들을 조합하여 데이터를 볼 수 있다.
하지만 한정된 대시보드 화면에서는 필터를 거는 것도 제한적이고 원하는 시각화 화면을 그리는 것도 불가능하다
하지만 GA API를 이용하면 데이터 가공 및 시각화의 제한에서 벋어날 수 있다.
몇가지 케이스를 통해 데이터를 가져오는 쿼리에 대해 알아 보자
아래 코드는 지난 포스트의 샘플 코드 중에서 실제 데이터를 가져오는 쿼리 부분만 변경한 것이다.
# 샘플 코드에서 쿼리 부분의 코드만 설명한다.
result = service.data().ga().get(
ids='ga:보기ID',
start_date='2022-01-05',
end_date='2022-01-07',
metrics='ga:totalEvents',
filters='ga:eventCategory=~^post_click*',
sort='-ga:totalEvents',
dimensions='ga:pagePath, ga:eventCategory'
).execute()
파라미터 하나하나에 대한 설명은 아래와 같다.
( ids, start_date, end_date 는 직관적이고 넣을 값이 고정적이여서 생략한다. )
1) metrics
파라미터로 보내는 Dimension에 대한 수치 값을 설정하는 영역이다.
metrics='ga:totalEvents',
위 예시는 해당 Dimension에 대해 총 이벤트 수를 가져오라는 의미이다.
ga:users 값을 넣으면 해당 Dimension에 총 사용자 수를 가져오라는 의미이다.
2) dimensions
파라미터로 보내는 metrics의 기준이 되는 값을 설정하는 영역이다.
dimensions='ga:pagePath, ga:eventCategory'
위 예시는 totalEvent 수를 가져오는데 pagePath 별로 eventCategory 별로 조회하라는 의미이다.
GA API에서 제공하는 metrics과 dimensions은 대시보드에서 쓸 수 있는 모든것을 그대로 쓸 수 있다.
API에 넣어야할 metrics과 dimensions은 아래 링크를 참고하면 된다.
UA Dimensions & Metrics Explorer
The Dimensions & Metrics Explorer lists and describes all of the dimensions and metrics available through the Core Reporting API. Explore all of the dimensions and metrics – Search or browse by group. Select a dimension or metric for additional details s
ga-dev-tools.web.app
3) filters
조회하는 Dimension에 조건을 거는 것이다.
SQL문에서 where 절과 같다고 생각하면 쉽다.
filters='ga:eventCategory=~^post_click*'
위 예시는 eventCategory가 post_click으로 시작하는 dimension만 조회하라는 의미이다.
4) sort
조회하는 Dimension이나 metric 에 순서를 부여하는 것이다.
SQL문에서 order by 절과 비슷하다고 생각하면 쉽다.
sort='-ga:totalEvents',
위 예시는 totalEvents를 기준으로 내림차순으로 정렬하라는 의미이다.
-를 붙이면 내림차순이고 -를 없애면 오름차순이 된다.
API 파라미터들에 대한 정의를 아래 링크에서 확인할 수 있다.
Core Reporting API - Reference Guide | Analytics Core Reporting API | Google Developers
Core Reporting API - Reference Guide This document provides the complete reference for both query and response for the Core Reporting API version 3.0. There is an updated version of the Google Analytics Reporting API. We recommend migrating your code today
developers.google.com
'구글 애널리틱스(GA)' 카테고리의 다른 글
jquery의 시대는 이제 끝난것인가?(w/ Google Tag Manager) (0) | 2022.02.28 |
---|---|
Javascript로 GA 데이터 전송법 ( Tistory Blog에 활용 하는 법 ) (0) | 2022.01.20 |
Google Analytics API 사용법 ① (0) | 2022.01.05 |
GA 스크립트나 GTM 스니펫 없이 데이터를 전송할 수 있다?Measurement Protocol (0) | 2021.12.24 |
② GA 설치시 개발자가 고려해야 할 사항 5가지 (0) | 2021.01.09 |