Google Analytics Admin API Client Library
The `google-analytics-admin` library provides a Python client for the Google Analytics Admin API, allowing programmatic management of Google Analytics 4 (GA4) account and property configurations. This includes tasks like managing accounts, properties, data streams, user links, custom dimensions, and metrics. It is currently at version 0.27.0 and is part of the actively developed Google Cloud Python client libraries, which typically see frequent updates.
Common errors
-
google.api_core.exceptions.PermissionDenied: 403 The caller does not have permission
cause The service account or user attempting to access Google Analytics Admin API resources lacks the necessary IAM permissions within Google Cloud or specific permissions within the Google Analytics account/property itself.fixEnsure the service account's email address is added to the Google Analytics account, property, or view with appropriate roles (e.g., 'Editor' or 'Administrator' in Google Analytics, not just 'Owner' in Google Cloud IAM) and that the Google Analytics Admin API is enabled for your Google Cloud project. -
ModuleNotFoundError: No module named 'google.analytics'
cause The Python environment does not have the `google-analytics-admin` package installed, or it is installed in a location not discoverable by the Python interpreter, or an incorrect import path is used.fixInstall the correct library using pip: `pip install google-analytics-admin` or ensure the Python environment's `PYTHONPATH` includes the directory where the package is installed. Ensure the import statement is `from google.analytics.admin import AnalyticsAdminServiceClient`. -
google.api_core.exceptions.Unauthenticated: 401 Request had invalid authentication credentials.
cause The client failed to provide valid authentication credentials (e.g., an expired or revoked OAuth 2.0 access token, or incorrect service account key usage) to the Google Analytics Admin API.fixVerify that your `GOOGLE_APPLICATION_CREDENTIALS` environment variable points to a valid service account key JSON file, or refresh your OAuth 2.0 access token if using user-based authentication. Ensure your credentials are not expired or revoked. -
google.api_core.exceptions.MethodNotImplemented: 501 The GRPC target is not implemented on the server
cause The API method being called is either deprecated, not yet implemented, or not supported by the specific version of the Google Analytics Admin API endpoint being targeted.fixCheck the official `google-analytics-admin` library documentation and Google Analytics Admin API changelog for the version you are using to confirm the method's availability and correct usage. Consider if there's a newer version of the method or an alternative approach.
Warnings
- breaking Breaking changes occur frequently in pre-1.0 versions. For example, version 0.2.0 introduced several changes including making `update_mask` required for update operations, renaming fields like `country_code` to `region_code` in the `Account` resource, and renaming `url_query_parameter` to `uri_query_parameter` in `EnhancedMeasurementSettings`.
- gotcha The Google Analytics Admin API is designed specifically for Google Analytics 4 (GA4) properties. It is not compatible with Universal Analytics (GA3) properties. Users migrating from GA3 will need to understand the GA4 data model and API structure.
- gotcha Resource names often follow specific formats (e.g., `accounts/{account_id}`, `properties/{property_id}`). Incorrectly formatted resource names will result in API errors.
- deprecated Support for Python 2 has been dropped for new client library versions as of January 1, 2020. This library requires Python 3.7 or newer.
- breaking A breaking change was introduced that updated the enum value for `KEY_EVENT` from 32 to 30 within the `ChangeHistoryResourceType`. This could affect code that relies on specific enum integer values.
- gotcha The application failed to find default credentials to authenticate with the API. This typically means the `GOOGLE_APPLICATION_CREDENTIALS` environment variable is not set, or a service account is not properly configured.
- gotcha The Google Analytics Admin API client requires proper authentication to be set up. This typically involves configuring Application Default Credentials (ADC) through environment variables (e.g., GOOGLE_APPLICATION_CREDENTIALS) or other methods supported by Google Cloud client libraries. Failure to do so will result in authentication errors.
Install
-
pip install google-analytics-admin
Imports
- AnalyticsAdminServiceClient
from google.analytics.admin import AnalyticsAdminServiceClient
from google.analytics.admin_v1beta import AnalyticsAdminServiceClient
- AnalyticsAdminServiceAsyncClient
from google.analytics.admin_v1beta import AnalyticsAdminServiceAsyncClient
Quickstart
import os
from google.analytics.admin_v1beta import AnalyticsAdminServiceClient
# Ensure GOOGLE_APPLICATION_CREDENTIALS environment variable is set
# or pass credentials explicitly.
# Example: os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/path/to/your/key.json'
def list_account_summaries():
"""Lists all accessible account summaries for the authenticated user."""
try:
client = AnalyticsAdminServiceClient()
print("Listing account summaries:")
for account_summary in client.list_account_summaries():
print(f" Account: {account_summary.display_name} ({account_summary.account})")
for property_summary in account_summary.property_summaries:
print(f" Property: {property_summary.display_name} ({property_summary.property}) - Type: {property_summary.property_type}")
except Exception as e:
print(f"An error occurred: {e}")
print("Please ensure you have set up authentication (e.g., GOOGLE_APPLICATION_CREDENTIALS) and enabled the Analytics Admin API.")
if __name__ == '__main__':
list_account_summaries()