Google Analytics API quickstart Stay organized with collections Save and categorize content based on your preferences.
Page Summary
Use either the Data API or Admin API for this quickstart.
Authenticate with a user account or service account.
This quickstart demonstrates how to create and send a
runReportrequest using a service account.The steps involve setting up tools and access, enabling the API, installing an SDK, and making an API call.
You can find client library installation guides and code samples for various programming languages, including Java, PHP, Python, Node.js, .NET, Ruby, Go, and REST.
You can use theData API orAdminAPI for this quickstart
You can authenticate with auseraccount orserviceaccount:
In this quickstart, you create and send arunReportrequest.
Here's a summary of the steps:
- Set up tools and access.
- Enable the API.
- Install an SDK.
- Make an API call.
Before you begin
Install and initialize the gcloudCLI.
To give your service account the necessary scopes and link it toyour VM instance, run the following:
gcloudcomputeinstancesstopVM-INSTANCE-NAMEgcloudcomputeinstancesset-service-accountVM-INSTANCE-NAME\--service-accountSERVICE-ACCOUNT-EMAIL\--scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/analytics.readonly"In theGoogle Analytics UI, grant the serviceaccountaccess to a Google Analyticsproperty.
Enable the Data API
To select or create aGoogle Cloudproject,and enable the API, clickEnable the Google AnalyticsData API v1.
Enable the Google Analytics Data API v1Install an SDK
Install the SDK for your programming language.
Java
PHP
Python
Node.js
.NET
Ruby
Go
go get google.golang.org/genproto/googleapis/analytics/data/v1beta
REST
Configure your environment variables by entering the following.ReplacePROJECT_ID with the ID of your Google Cloud projectandPROPERTY_ID with the ID of your Google Analytics property.
exportPROJECT_ID=PROJECT_IDexportPROPERTY_ID=PROPERTY_ID
Make an API call
To verify your setup and make an API call, run the following sample.
This sample calls therunReportmethod. The response lists active users for your property.
To install all the Analytics API code samples, see ourGitHub.
Java
importcom.google.analytics.data.v1beta.BetaAnalyticsDataClient;importcom.google.analytics.data.v1beta.DateRange;importcom.google.analytics.data.v1beta.Dimension;importcom.google.analytics.data.v1beta.Metric;importcom.google.analytics.data.v1beta.Row;importcom.google.analytics.data.v1beta.RunReportRequest;importcom.google.analytics.data.v1beta.RunReportResponse;/** * Google Analytics Data API sample quickstart application. * * <p>This application demonstrates the usage of the Analytics Data API using service account * credentials. * * <p>Before you start the application, please review the comments starting with "TODO(developer)" * and update the code to use correct values. * * <p>To run this sample using Maven: * * <pre>{@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.QuickstartSample" * }</pre> */publicclassQuickstartSample{publicstaticvoidmain(String...args)throwsException{/** * TODO(developer): Replace this variable with your Google Analytics 4 property ID before * running the sample. */StringpropertyId="YOUR-GA4-PROPERTY-ID";sampleRunReport(propertyId);}// This is an example snippet that calls the Google Analytics Data API and runs a simple report// on the provided GA4 property id.staticvoidsampleRunReport(StringpropertyId)throwsException{// Using a default constructor instructs the client to use the credentials// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.try(BetaAnalyticsDataClientanalyticsData=BetaAnalyticsDataClient.create()){RunReportRequestrequest=RunReportRequest.newBuilder().setProperty("properties/"+propertyId).addDimensions(Dimension.newBuilder().setName("city")).addMetrics(Metric.newBuilder().setName("activeUsers")).addDateRanges(DateRange.newBuilder().setStartDate("2020-03-31").setEndDate("today")).build();// Make the request.RunReportResponseresponse=analyticsData.runReport(request);System.out.println("Report result:");// Iterate through every row of the API response.for(Rowrow:response.getRowsList()){System.out.printf("%s, %s%n",row.getDimensionValues(0).getValue(),row.getMetricValues(0).getValue());}}}}
PHP
require 'vendor/autoload.php';use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;use Google\Analytics\Data\V1beta\DateRange;use Google\Analytics\Data\V1beta\Dimension;use Google\Analytics\Data\V1beta\Metric;use Google\Analytics\Data\V1beta\RunReportRequest;/** * TODO(developer): Replace this variable with your Google Analytics 4 * property ID before running the sample. */$property_id = 'YOUR-GA4-PROPERTY-ID';// Using a default constructor instructs the client to use the credentials// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.$client = new BetaAnalyticsDataClient();// Make an API call.$request = (new RunReportRequest()) ->setProperty('properties/' . $property_id) ->setDateRanges([ new DateRange([ 'start_date' => '2020-03-31', 'end_date' => 'today', ]), ]) ->setDimensions([new Dimension([ 'name' => 'city', ]), ]) ->setMetrics([new Metric([ 'name' => 'activeUsers', ]) ]);$response = $client->runReport($request);// Print results of an API call.print 'Report result: ' . PHP_EOL;foreach ($response->getRows() as $row) { print $row->getDimensionValues()[0]->getValue() . ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL;}
Python
fromgoogle.analytics.data_v1betaimportBetaAnalyticsDataClientfromgoogle.analytics.data_v1beta.typesimport(DateRange,Dimension,Metric,RunReportRequest,)defsample_run_report(property_id="YOUR-GA4-PROPERTY-ID"):"""Runs a simple report on a Google Analytics 4 property."""# TODO(developer): Uncomment this variable and replace with your# Google Analytics 4 property ID before running the sample.# property_id = "YOUR-GA4-PROPERTY-ID"# Using a default constructor instructs the client to use the credentials# specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.client=BetaAnalyticsDataClient()request=RunReportRequest(property=f"properties/{property_id}",dimensions=[Dimension(name="city")],metrics=[Metric(name="activeUsers")],date_ranges=[DateRange(start_date="2020-03-31",end_date="today")],)response=client.run_report(request)print("Report result:")forrowinresponse.rows:print(row.dimension_values[0].value,row.metric_values[0].value)
Node.js
/** * TODO(developer): Uncomment this variable and replace with your * Google Analytics 4 property ID before running the sample. */// propertyId = 'YOUR-GA4-PROPERTY-ID';// Imports the Google Analytics Data API client library.const{BetaAnalyticsDataClient}=require('@google-analytics/data');// Using a default constructor instructs the client to use the credentials// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.constanalyticsDataClient=newBetaAnalyticsDataClient();// Runs a simple report.asyncfunctionrunReport(){const[response]=awaitanalyticsDataClient.runReport({property:`properties/${propertyId}`,dateRanges:[{startDate:'2020-03-31',endDate:'today',},],dimensions:[{name:'city',},],metrics:[{name:'activeUsers',},],});console.log('Report result:');response.rows.forEach((row)=>{console.log(row.dimensionValues[0],row.metricValues[0]);});}runReport();
.NET
usingGoogle.Analytics.Data.V1Beta;usingSystem;namespaceAnalyticsSamples{classQuickStart{staticvoidSampleRunReport(stringpropertyId="YOUR-GA4-PROPERTY-ID"){/***TODO(developer):Uncommentthisvariableandreplacewithyour*GoogleAnalytics4propertyIDbeforerunningthesample.*///propertyId="YOUR-GA4-PROPERTY-ID";//Usingadefaultconstructorinstructstheclienttousethecredentials//specifiedinGOOGLE_APPLICATION_CREDENTIALSenvironmentvariable.BetaAnalyticsDataClientclient=BetaAnalyticsDataClient.Create();//Initializerequestargument(s)RunReportRequestrequest=newRunReportRequest{Property="properties/"+propertyId,Dimensions={newDimension{Name="city"},},Metrics={newMetric{Name="activeUsers"},},DateRanges={newDateRange{StartDate="2020-03-31",EndDate="today"},},};//MaketherequestRunReportResponseresponse=client.RunReport(request);Console.WriteLine("Report result:");foreach(Rowrowinresponse.Rows){Console.WriteLine("{0}, {1}",row.DimensionValues[0].Value,row.MetricValues[0].Value);}}staticintMain(string[]args){if(args.Length >0){SampleRunReport(args[0]);}else{SampleRunReport();}return0;}}}
REST
To send this request, run the curl command from the command line or include the REST call in your application.
curl-XPOST\-H"Authorization: Bearer$(gcloudauthapplication-defaultprint-access-token)"\-H"x-goog-user-project:${PROJECT_ID}"\-H"Content-Type: application/json"\-d' { "dateRanges": [ { "startDate": "2025-01-01", "endDate": "2025-02-01" } ], "dimensions": [ { "name": "country" } ], "metrics": [ { "name": "activeUsers" } ] }'https://analyticsdata.googleapis.com/v1beta/properties/${PROPERTY_ID}:runReport
Here's a sample response in JSON:
{"dimensionHeaders":[{"name":"country"}],"metricHeaders":[{"name":"activeUsers","type":"TYPE_INTEGER"}],"rows":[{"dimensionValues":[{"value":"United States"}],"metricValues":[{"value":"3242"}]},{"dimensionValues":[{"value":"(not set)"}],"metricValues":[{"value":"3015"}]},{"dimensionValues":[{"value":"India"}],"metricValues":[{"value":"805"}]}],"rowCount":3,"metadata":{"currencyCode":"USD","timeZone":"America/Los_Angeles"},"kind":"analyticsData#runReport"}Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-08-27 UTC.