서비스어카운트로 접근 할 경우 OAuth 2.0 과 다르게 추가적인 인증(ex 구글 콘솔에서 만든 프로젝트가 인가되지 않았을 경우, 접근 허용 여부에 대한 문의) 을 신경 쓸 필요가 없어 현재 주로 쓰고 있는 방식이다.
Google의 시작가이드를 보고 따라하면 수월하게 적용 가능하나, 내 상황에서는 해당 방식의 적용이 어려운 환경인지라 이 방식이 아닌 OAuth 2.0으로 인증할 예정이다. (해당 가이드는 다음에 작성할 예정이다.)
현재 작성한 내역은 당장 사용하진 않겠지만, 공부했던 건이니 미래의 나를 위해 기록해두자!
1. 서비스어카운트 사용을 위해서는 구글 콘솔에서 서비스어카운트 계정이 생성 되어 있어야 한다.
구글 Cloud 콘솔에서 OAuth 2.0 클라이언트ID내 JSON 파일을 다운받아 로컬에 저장 해 둔다.
서비스어카운트 계정이 없다면 아래 링크를 참고하여 만들어 둘것

해당 JSON 파일을 열어보면, 안쪽에는 접속을 위한 정보값이 작성되어 있다
중요한 정보이니 잊어버리지 않게 잘 보관해 둘 것
{
"installed": {
"client_id": [클라이언트 ID],
"project_id": [프로젝트 ID],
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": [클라이언트 시크릿 ID],
"redirect_uris": [
[리다이렉트 URL],
]
}
}
2. Python 으로 작업할 예정이기에 pip로 Google 클라이언트 라이브러리를 설치 한다.
구글 클라이언트 패키지를 이용하여 쉽게 구글 인증을 이용 가능하다.
pip install --upgrade google-api-python-client
3. HelloAnalytics.py 샘플의 내역을 복사하여 내 환경에 맞게 컨버팅 한다.
내 경우 Analytics API를 사용할 예정인지라 구글의 Analytics 가이드를 사용한다.
"""A simple example of how to access the Google Analytics API."""
# 구글의 기본가이드
# from apiclient.discovery import build
# 내 환경에서 정상 호출이 되지 않아 변경한 소스
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
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
def get_first_profile_id(service):
# Use the Analytics service object to get the first profile id.
# Get a list of all Google Analytics accounts for this user
accounts = service.management().accounts().list().execute()
if accounts.get('items'):
# Get the first Google Analytics account.
account = accounts.get('items')[0].get('id')
# Get a list of all the properties for the first account.
properties = service.management().webproperties().list(
accountId=account).execute()
if properties.get('items'):
# Get the first property id.
property = properties.get('items')[0].get('id')
# Get a list of all views (profiles) for the first property.
profiles = service.management().profiles().list(
accountId=account,
webPropertyId=property).execute()
if profiles.get('items'):
# return the first view (profile) id.
return profiles.get('items')[0].get('id')
return None
def get_results(service, profile_id):
# Use the Analytics Service Object to query the Core Reporting API
# for the number of sessions within the past seven days.
return service.data().ga().get(
ids='ga:' + profile_id,
start_date='7daysAgo',
end_date='today',
metrics='ga:sessions').execute()
def print_results(results):
# Print data nicely for the user.
if results:
print 'View (Profile):', results.get('profileInfo').get('profileName')
print 'Total Sessions:', results.get('rows')[0][0]
else:
print 'No results found'
def main():
# Define the auth scopes to request.
scope = 'https://www.googleapis.com/auth/analytics.readonly'
key_file_location = '[상단에 다운받은 json파일의 위치를 넣는다]'
# Authenticate and construct service.
service = get_service(
api_name='analytics',
api_version='v3',
scopes=[scope],
key_file_location=key_file_location)
profile_id = get_first_profile_id(service)
print_results(get_results(service, profile_id))
if __name__ == '__main__':
main()
5. 사용하기 전, Analytics 내에 하나의 속성이라도 서비스계정이 등록되어 있어야만 한다.
해당 소스는 Analytics 내 하나라도 등록된 속성이 존재해야만 동작하는 소스이다.
때문에 서비스 어카운트가 등록된 Analytics 가 한개도 없을 경우 값을 가져올 수 없다고 에러가 발생한다.
등록하여야 할 계정 형식은 아래와 같다.
<projectId>-<uniqueId>@developer.gserviceaccount.com
내 경우 아래 서비스 계정의 값을 넣어 주었다.

5-1. Analytics 내 서비스계정 등록 방법
우측의 '관리' 에서

'계정 액서스 관리' > '속성 액서스 관리' 에서 등록한 서비스 계정 클릭 > 최하단으로 스크롤
각 속성에 '뷰어' 이상의 권한을 부여한다.

5-2. Analytics 는 현재 2가지 버전으로 나눠져 있다. 하나는 기본 Analytics. 다른 하나는 v4 버전이다.
Analytics는 과거이자 현재 버전이며 ids값이 'UA' 로 시작된다. (Ex. UA-123456789)
V4는 현재 Analytics 에서 변경되는 과정의 버전으로 ids 값이 숫자로만 구성되어 있다. (Ex. 123456789)

V4 API 는 호출 URL에서도 알 수 있듯이 베타이므로 이 포스팅에서는 Analytics 버전만 다룬다
6. 정상적으로 등록되었을 경우 호출 시 결과가 나오게 된다.
단, 내경우 기존 쿼리에서 약간 수정하여 호출 하였다.
def get_results(service, profile_id):
#기존 쿼리 컨버팅. 보고자 하는 dimension, metrics, filter 를 수정하여 확인
return service.data().ga().get(
ids='ga:'+profile_id,
start_date='2023-03-09',
end_date='2023-03-09',
dimensions='ga:campaign,ga:source,ga:medium,ga:adContent,ga:date',
metrics='ga:users',
filters='ga:medium==display').execute()
.....
# 세션값에 대한 확인을 제외하고 결과 전체를 추출해보고자 함.
def print_results(results):
# Print data nicely for the user.
print('=======================================')
print(results)
print('=======================================')
if results:
print('View (Profile):'+ results.get('profileInfo').get('profileName'))
else:
print('No results found')
결과 내역 :

Tip. Query Explorer 를 사용하면 사용하고자 하는 API 를 더 수월하게 만들 수 있다.
https://ga-dev-tools.google/query-explorer/
참고사이트 :
https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/service-py?hl=ko
Hello Analytics API: 서비스 계정용 Python 빠른 시작 | Analytics Management API | Google Developers
이 튜토리얼에서는 Google 애널리틱스 계정 액세스, 애널리틱스 API 쿼리, API 응답 처리, 결과 출력에 필요한 단계를 설명합니다. 이 튜토리얼에서는 Core Reporting API v3.0, Management API v3.0, OAuth2.0이 사
developers.google.com
https://ga-dev-tools.google/query-explorer/
UA Query Explorer
ga-dev-tools.google
'환경설정' 카테고리의 다른 글
Monday API - 사용 셋팅 (0) | 2023.03.26 |
---|---|
Google API - OAuth 2.0 인증 (0) | 2023.03.19 |
Google API - POSTMAN 내 OAuth 2.0 인증 (0) | 2023.03.14 |
Tistory 목차 셋팅- TOC(Table Of Contents) (0) | 2023.03.13 |
WSL2- 우분투 검은 화면 부팅 (0) | 2022.12.27 |