This tutorial walks through the steps required to access the Analytics Reporting API v4.
1. Enable the API
To get started using Analytics Reporting API v4, 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.
Note: 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 credentials
- Open the
Credentials page
.
- Click
Create credentials
and select
OAuth client ID
- For the
Application type
select
Web application
.
- Name the client ID
quickstart
and click
Create
.
- Set the
Authorized JavaScript origins
to
http://localhost:8080
- Click
Create
.
2. Setup the sample
You will need to create one file name
HelloAnalytics.html
, which will contain the HTML and JavaScript code for our example.
- Copy or
download
the following source code to
HelloAnalytics.html
.
- Replace
<REPLACE_WITH_CLIENT_ID>
with your client ID created above.
- Replace
<REPLACE_WITH_VIEW_ID>
with a view ID. A view ID can be retrieved from the
Account Explorer
.
<!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: Run the sample
- Publish
HelloAnalytics.html
to your web server and load the page in your browser.
- Click the
Sign in
button, and authorize access to Google Analytics.
When you finish these steps, the sample outputs the number of sessions for the last seven days for the given view.