Hello Analytics Reporting API v4; 웹 애플리케이션용 자바스크립트 빠른 시작

이 튜토리얼에서는 Analytics Reporting API v4에 액세스하는 데 필요한 단계를 안내합니다.

1. API 사용 설정

애널리틱스 Reporting API v4를 사용하려면 먼저 설정 도구를 사용하여 Google API 콘솔에서 프로젝트를 만들고 API를 사용 설정하며 사용자 인증 정보를 만드는 과정을 진행합니다.

참고: 웹 클라이언트 ID 또는 설치된 애플리케이션 클라이언트를 만들려면 동의 화면에서 제품 이름을 설정해야 합니다. 아직 구성하지 않았다면 동의 화면 구성하라는 메시지가 표시됩니다.

사용자 인증 정보 만들기

  • 사용자 인증 정보 페이지를 엽니다.
  • 사용자 인증 정보 만들기를 클릭하고 OAuth 클라이언트 ID를 선택합니다.
  • 애플리케이션 유형으로 웹 애플리케이션을 선택합니다.
  • 클라이언트 ID의 이름을 quickstart로 지정하고 만들기를 클릭합니다.
  • 승인된 자바스크립트 원본http://localhost:8080로 설정합니다.
  • 만들기를 클릭합니다.

2. 샘플 설정

이 예에서는 HTML과 자바스크립트 코드가 포함될 파일 이름 HelloAnalytics.html을(를) 만들어야 합니다.

  • 다음 소스 코드를 복사하거나 HelloAnalytics.html다운로드합니다.
  • <REPLACE_WITH_CLIENT_ID>를 위에서 만든 클라이언트 ID로 바꿉니다.
  • <REPLACE_WITH_VIEW_ID>를 뷰 ID로 바꿉니다. 보기 ID는 계정 탐색기에서 가져올 수 있습니다.
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Hello Analytics Reporting API V4</title>
  <meta name="google-signin-client_id" content="<REPLACE_WITH_CLIENT_ID>">
  <meta name="google-signin-scope" content="https://www.googleapis.com/auth/analytics.readonly">
</head>
<body>

<h1>Hello Analytics Reporting API V4</h1>

<!-- The Sign-in button. This will run `queryReports()` on success. -->
<p class="g-signin2" data-onsuccess="queryReports"></p>

<!-- The API response will be printed here. -->
<textarea cols="80" rows="20" id="query-output"></textarea>

<script>
  // Replace with your view ID.
  var VIEW_ID = '<REPLACE_WITH_VIEW_ID>';

  // Query the API and print the results to the page.
  function queryReports() {
    gapi.client.request({
      path: '/v4/reports:batchGet',
      root: 'https://analyticsreporting.googleapis.com/',
      method: 'POST',
      body: {
        reportRequests: [
          {
            viewId: VIEW_ID,
            dateRanges: [
              {
                startDate: '7daysAgo',
                endDate: 'today'
              }
            ],
            metrics: [
              {
                expression: 'ga:sessions'
              }
            ]
          }
        ]
      }
    }).then(displayResults, console.error.bind(console));
  }

  function displayResults(response) {
    var formattedJson = JSON.stringify(response.result, null, 2);
    document.getElementById('query-output').value = formattedJson;
  }
</script>

<!-- Load the JavaScript API client and Sign-in library. -->
<script src="https://apis.google.com/js/client:platform.js"></script>

</body>
</html>

3: 샘플 실행

  • HelloAnalytics.html을 웹 서버에 게시하고 브라우저에서 페이지를 로드합니다.
  • 로그인 버튼을 클릭하고 Google 애널리틱스에 대한 액세스를 승인합니다.

이 단계를 완료하면 샘플에서는 지정된 뷰의 지난 7일 동안의 세션 수를 출력합니다.