- Hello Analytics API: JavaScript quickstart for web applications
- Step 1: Enable the Analytics API
- Create a client ID
- Step 2: Setup the sample
- Hello Analytics
- Step 3: Run the sample
- Введение в Google Analytics API: краткое руководство по JavaScript для веб-приложений
- Шаг 1. Включите Google Analytics API
- Создайте идентификатор клиента
- Шаг 2. Настройте пример
- Hello Analytics
- Шаг 3. Запустите пример
- Hello Analytics API: JavaScript quickstart for web applications
- Step 1: Enable the Analytics API
- Create a client ID
- Step 2: Setup the sample
- Hello Analytics
- Step 3: Run the sample
Hello Analytics API: JavaScript quickstart for web applications
This tutorial walks through the steps required to access a Google Analytics account, query the Analytics APIs, handle the API responses, and output the results. The Core Reporting API v3.0, Management API v3.0, and OAuth2.0 are used in this tutorial.
Note: The purpose of these quickstart guides is to help you get through the initial hurdles of API authorization with the Google API Client Libraries. As these libraries are under active development, these guides may occasionally fall out of sync with the latest client libraries. If you run into this issue you should check the Client Library’s documentation and if needed see the help documentation.
Step 1: Enable the Analytics API
To get started using Google Analytics API, you need to first use the setup tool, which guides you through creating a project in the Google API Console, enabling the API, and creating credentials.
To create a Web Client ID or an Installed Application Client, you need to set a product name in the consent screen. If you have not done so already you will be prompted to Configure consent screen.
Create a client ID
From the Credentials page:
- Click Create Credentials and select OAuth client ID.
- Select Web application for APPLICATION TYPE.
- Name the credential.
- Set the AUTHORIZED JAVASCRIPT ORIGINS to http://localhost:8080
- Set the AUTHORIZED REDIRECT URIS to http://localhost:8080/oauth2callback
- Click Create.
Step 2: Setup the sample
You’ll need to create one file named HelloAnalytics.html , which will contain the HTML and JavaScript code for our example.
- Copy or download the following source code to HelloAnalytics.html .
- replace ‘<YOUR_CLIENT_ID>’ with your client ID. created above.
Hello Analytics
'; // Set authorized scope. var SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']; function authorize(event) < // Handles the authorization flow. // `immediate` should be false when invoked from the button click. var useImmdiate = event ? false : true; var authData = < client_id: CLIENT_ID, scope: SCOPES, immediate: useImmdiate >; gapi.auth.authorize(authData, function(response) < var authButton = document.getElementById('auth-button'); if (response.error) < authButton.hidden = false; >else < authButton.hidden = true; queryAccounts(); >>); > function queryAccounts() < // Load the Google Analytics client library. gapi.client.load('analytics', 'v3').then(function() < // Get a list of all Google Analytics accounts for this user gapi.client.analytics.management.accounts.list().then(handleAccounts); >); > function handleAccounts(response) < // Handles the response from the accounts list method. if (response.result.items && response.result.items.length) < // Get the first Google Analytics account. var firstAccountId = response.result.items[0].id; // Query for properties. queryProperties(firstAccountId); >else < console.log('No accounts found for this user.'); >> function queryProperties(accountId) < // Get a list of all the properties for the account. gapi.client.analytics.management.webproperties.list( ) .then(handleProperties) .then(null, function(err) < // Log any errors. console.log(err); >); > function handleProperties(response) < // Handles the response from the webproperties list method. if (response.result.items && response.result.items.length) < // Get the first Google Analytics account var firstAccountId = response.result.items[0].accountId; // Get the first property ID var firstPropertyId = response.result.items[0].id; // Query for Views (Profiles). queryProfiles(firstAccountId, firstPropertyId); >else < console.log('No properties found for this user.'); >> function queryProfiles(accountId, propertyId) < // Get a list of all Views (Profiles) for the first property // of the first Account. gapi.client.analytics.management.profiles.list(< 'accountId': accountId, 'webPropertyId': propertyId >) .then(handleProfiles) .then(null, function(err) < // Log any errors. console.log(err); >); > function handleProfiles(response) < // Handles the response from the profiles list method. if (response.result.items && response.result.items.length) < // Get the first View (Profile) ID. var firstProfileId = response.result.items[0].id; // Query the Core Reporting API. queryCoreReportingApi(firstProfileId); >else < console.log('No views (profiles) found for this user.'); >> function queryCoreReportingApi(profileId) < // Query the Core Reporting API for the number sessions for // the past seven days. gapi.client.analytics.data.ga.get(< 'ids': 'ga:' + profileId, 'start-date': '7daysAgo', 'end-date': 'today', 'metrics': 'ga:sessions' >) .then(function(response) < var formattedJson = JSON.stringify(response.result, null, 2); document.getElementById('query-output').value = formattedJson; >) .then(null, function(err) < // Log any errors. console.log(err); >); > // Add an event listener to the 'auth-button'. document.getElementById('auth-button').addEventListener('click', authorize);
Step 3: Run the sample
After you have enabled the Analytics API, and set up the sample source code the sample is ready to run.
- Publish HelloAnalytics.html to your web server and load the page in your browser.
- Click the Authorize button, and authorize access to Google Analytics.
When you finish these steps, the sample outputs the name of the authorized user’s first Google Analytics view (profile) and the number of sessions for the last seven days.
Note: To successfully run this sample you will need to have at least one Google Analytics property and view (profile).
With the authorized Analytics service object you can now run any of code samples found in the Management API reference docs. For example you could try changing the code to use the accountSummaries.list method.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2022-11-04 UTC.
Введение в Google Analytics API: краткое руководство по JavaScript для веб-приложений
В этом руководстве описывается, как получить доступ к аккаунту Google Analytics, отправлять запросы в API этого сервиса, обрабатывать ответы и извлекать результаты обработки с применением Core Reporting API 3.0, Management API 3.0 и OAuth 2.0.
Примечание. Цель этих кратких руководств – помочь пользователю выполнить авторизацию API с помощью клиентских библиотек Google API. Поскольку эти библиотеки постоянно обновляются, информации о последних изменениях здесь может не быть. Если вы не нашли нужные сведения, ознакомьтесь с документацией по клиентским библиотекам и справочной информацией.
Шаг 1. Включите Google Analytics API
Перед началом работы с Google Analytics API используйте инструмент настройки, чтобы создать проект в Google API Console, включить API и зарегистрировать учетные данные.
Чтобы создать идентификатор веб-клиента или клиента установленного приложения, нужно указать название продукта в окне запроса доступа. Если вы ещё не указали название, вам будет предложено это сделать.
Создайте идентификатор клиента
Откройте раздел «Учетные данные» и выполните следующие действия:
- Нажмите Создать учетные данные и выберите вариант Идентификатор клиента OAuth.
- В разделе Тип приложения выберите Веб-приложение.
- Введите название.
- В поле Разрешенные источники JavaScript укажите http://localhost:8080.
- В поле Разрешенные URI перенаправления введите http://localhost:8080/oauth2callback.
- Нажмите кнопку Создать.
Шаг 2. Настройте пример
Вам необходимо создать файл с названием HelloAnalytics.html , где будет содержаться код HTML и JavaScript.
- Скопируйте или скачайте приведенный ниже исходный код для HelloAnalytics.html .
- Замените на свой идентификатор клиента, который создали ранее.
Hello Analytics
Шаг 3. Запустите пример
После того как вы включили Google Analytics API и настроили код образца, он готов к запуску.
- Загрузите HelloAnalytics.html на свой веб-сервер и откройте эту страницу в браузере.
- Нажмите кнопку «Авторизация», чтобы открыть доступ к Google Analytics.
После выполнения всех шагов будет выведено название первого профиля авторизованного пользователя в Google Analytics и количество сеансов за последние семь дней.
Примечание. Для успешного запуска примера нужно иметь по крайней мере один ресурс и профиль Google Analytics.
Имея авторизованный служебный объект Analytics, вы можете запустить любой из примеров кода, приведенных в справочных материалах по Management API. Например, можно попробовать изменить код, чтобы использовать метод accountSummaries.list.
Если не указано иное, контент на этой странице предоставляется по лицензии Creative Commons «С указанием авторства 4.0», а примеры кода – по лицензии Apache 2.0. Подробнее об этом написано в правилах сайта. Java – это зарегистрированный товарный знак корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2019-01-23 UTC.
Hello Analytics API: JavaScript quickstart for web applications
This tutorial walks through the steps required to access a Google Analytics account, query the Analytics APIs, handle the API responses, and output the results. The Core Reporting API v3.0, Management API v3.0, and OAuth2.0 are used in this tutorial.
Note: The purpose of these quickstart guides is to help you get through the initial hurdles of API authorization with the Google API Client Libraries. As these libraries are under active development, these guides may occasionally fall out of sync with the latest client libraries. If you run into this issue you should check the Client Library’s documentation and if needed see the help documentation.
Step 1: Enable the Analytics API
To get started using Google Analytics API, you need to first use the setup tool, which guides you through creating a project in the Google API Console, enabling the API, and creating credentials.
To create a Web Client ID or an Installed Application Client, you need to set a product name in the consent screen. If you have not done so already you will be prompted to Configure consent screen.
Create a client ID
From the Credentials page:
- Click Create Credentials and select OAuth client ID.
- Select Web application for APPLICATION TYPE.
- Name the credential.
- Set the AUTHORIZED JAVASCRIPT ORIGINS to http://localhost:8080
- Set the AUTHORIZED REDIRECT URIS to http://localhost:8080/oauth2callback
- Click Create.
Step 2: Setup the sample
You’ll need to create one file named HelloAnalytics.html , which will contain the HTML and JavaScript code for our example.
- Copy or download the following source code to HelloAnalytics.html .
- replace ‘<YOUR_CLIENT_ID>’ with your client ID. created above.
Hello Analytics
'; // Set authorized scope. var SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']; function authorize(event) < // Handles the authorization flow. // `immediate` should be false when invoked from the button click. var useImmdiate = event ? false : true; var authData = < client_id: CLIENT_ID, scope: SCOPES, immediate: useImmdiate >; gapi.auth.authorize(authData, function(response) < var authButton = document.getElementById('auth-button'); if (response.error) < authButton.hidden = false; >else < authButton.hidden = true; queryAccounts(); >>); > function queryAccounts() < // Load the Google Analytics client library. gapi.client.load('analytics', 'v3').then(function() < // Get a list of all Google Analytics accounts for this user gapi.client.analytics.management.accounts.list().then(handleAccounts); >); > function handleAccounts(response) < // Handles the response from the accounts list method. if (response.result.items && response.result.items.length) < // Get the first Google Analytics account. var firstAccountId = response.result.items[0].id; // Query for properties. queryProperties(firstAccountId); >else < console.log('No accounts found for this user.'); >> function queryProperties(accountId) < // Get a list of all the properties for the account. gapi.client.analytics.management.webproperties.list( ) .then(handleProperties) .then(null, function(err) < // Log any errors. console.log(err); >); > function handleProperties(response) < // Handles the response from the webproperties list method. if (response.result.items && response.result.items.length) < // Get the first Google Analytics account var firstAccountId = response.result.items[0].accountId; // Get the first property ID var firstPropertyId = response.result.items[0].id; // Query for Views (Profiles). queryProfiles(firstAccountId, firstPropertyId); >else < console.log('No properties found for this user.'); >> function queryProfiles(accountId, propertyId) < // Get a list of all Views (Profiles) for the first property // of the first Account. gapi.client.analytics.management.profiles.list(< 'accountId': accountId, 'webPropertyId': propertyId >) .then(handleProfiles) .then(null, function(err) < // Log any errors. console.log(err); >); > function handleProfiles(response) < // Handles the response from the profiles list method. if (response.result.items && response.result.items.length) < // Get the first View (Profile) ID. var firstProfileId = response.result.items[0].id; // Query the Core Reporting API. queryCoreReportingApi(firstProfileId); >else < console.log('No views (profiles) found for this user.'); >> function queryCoreReportingApi(profileId) < // Query the Core Reporting API for the number sessions for // the past seven days. gapi.client.analytics.data.ga.get(< 'ids': 'ga:' + profileId, 'start-date': '7daysAgo', 'end-date': 'today', 'metrics': 'ga:sessions' >) .then(function(response) < var formattedJson = JSON.stringify(response.result, null, 2); document.getElementById('query-output').value = formattedJson; >) .then(null, function(err) < // Log any errors. console.log(err); >); > // Add an event listener to the 'auth-button'. document.getElementById('auth-button').addEventListener('click', authorize);
Step 3: Run the sample
After you have enabled the Analytics API, and set up the sample source code the sample is ready to run.
- Publish HelloAnalytics.html to your web server and load the page in your browser.
- Click the Authorize button, and authorize access to Google Analytics.
When you finish these steps, the sample outputs the name of the authorized user’s first Google Analytics view (profile) and the number of sessions for the last seven days.
Note: To successfully run this sample you will need to have at least one Google Analytics property and view (profile).
With the authorized Analytics service object you can now run any of code samples found in the Management API reference docs. For example you could try changing the code to use the accountSummaries.list method.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2022-11-04 UTC.