play-console-cli icon indicating copy to clipboard operation
play-console-cli copied to clipboard

Feature: Google Analytics Data API (GA4) integration (analyticsdata/v1beta)

Open tamtom opened this issue 8 months ago • 3 comments

Summary

Add a gplay analytics command group that integrates the Google Analytics Data API v1beta, enabling developers to query GA4 app analytics (engagement, retention, conversions, real-time usage) directly from the CLI alongside existing Play Console vitals and reports.

Why This Is Applicable to Google Play

Google Analytics 4 is the standard analytics platform for Android apps distributed through Google Play. GA4 properties track app events via the Firebase/Google Analytics SDK, providing engagement and business metrics that directly complement the Play Console data already accessible through gplay. The same service account authentication model applies — a service account added as a Viewer on the GA4 property can query the Analytics Data API, just as it queries the Android Publisher and Play Developer Reporting APIs today.

Problem

The CLI currently covers two categories of app data:

  1. Play Console Vitals (gplay vitals) — crash rates, ANR rates, startup time, rendering, battery via the Play Developer Reporting API
  2. Play Console Reports (gplay reports) — financial earnings, installs, ratings via GCS bulk reports

Neither covers user engagement analytics: active users, session duration, screen views, retention, conversion funnels, geographic distribution of users, traffic source attribution, or real-time activity. These metrics live in GA4 and are critical for understanding app health beyond pure stability. Today, developers must leave the terminal and navigate the GA4 web UI or write custom scripts to access this data.

Goals

  • Provide CLI access to GA4 reporting for Android app properties
  • Support the core reporting workflow: run ad-hoc reports with dimensions, metrics, date ranges, and filters
  • Support real-time reporting for live monitoring and incident response
  • Expose metadata discovery so users can explore available dimensions and metrics without leaving the terminal
  • Support batch report execution for dashboard-style queries
  • Follow existing CLI patterns: JSON-first output, --output table/markdown, --paginate, --dry-run
  • Reuse the existing service account authentication infrastructure with the additional analytics.readonly scope

Proposed Commands

Command Group

gplay analytics <subcommand> [flags]

gplay analytics report

Run a standard GA4 report. This is the primary command.

# Active users and sessions by country for the last 7 days
gplay analytics report \
  --property 123456789 \
  --dimensions country,city \
  --metrics activeUsers,sessions,screenPageViews \
  --from 2026-03-28 --to 2026-04-04

# Engagement by app version with filter
gplay analytics report \
  --property 123456789 \
  --dimensions appVersion \
  --metrics engagedSessions,userEngagementDuration,eventCount \
  --from 2026-04-01 --to 2026-04-04 \
  --filter "platform==Android" \
  --order-by "activeUsers desc" \
  --limit 20 \
  --output table

# Revenue by source/medium
gplay analytics report \
  --property 123456789 \
  --dimensions sessionSource,sessionMedium \
  --metrics totalRevenue,transactions,purchaseRevenue \
  --from 2026-03-01 --to 2026-03-31

Flags:

Flag Required Description
--property Yes GA4 property ID (numeric, e.g. 123456789)
--dimensions No Comma-separated dimension names
--metrics Yes Comma-separated metric names
--from No Start date (YYYY-MM-DD, yesterday, 7daysAgo, 30daysAgo)
--to No End date (YYYY-MM-DD, today, yesterday)
--filter No Dimension filter expression (e.g. country==US, platform==Android)
--metric-filter No Metric filter expression (e.g. activeUsers>100)
--order-by No Sort order (e.g. activeUsers desc, date asc)
--limit No Max rows returned (default: 10000)
--offset No Row offset for pagination
--output No Output format: json (default), table, markdown
--pretty No Pretty-print JSON
--include-quota No Include token quota usage in response

gplay analytics realtime

Query real-time event data (last 30 minutes).

# Current active users by country
gplay analytics realtime \
  --property 123456789 \
  --dimensions country \
  --metrics activeUsers

# Live event stream by event name
gplay analytics realtime \
  --property 123456789 \
  --dimensions eventName,platform \
  --metrics eventCount,activeUsers \
  --output table

Flags: Same as report except no --from/--to (real-time is always the last 30 minutes). Supports --minute-ranges to specify custom minute ranges (e.g. 0-5,5-15,15-30).

gplay analytics metadata

Discover available dimensions and metrics for a property.

# List all available dimensions and metrics
gplay analytics metadata --property 123456789

# Filter to specific category
gplay analytics metadata --property 123456789 --filter-category "User"

gplay analytics batch

Run multiple reports in a single API call (up to 5 reports).

# Run reports from a JSON file
gplay analytics batch --property 123456789 --file reports.json

# The JSON file contains an array of report requests

gplay analytics check-compatibility

Validate that a combination of dimensions and metrics can be used together.

gplay analytics check-compatibility \
  --property 123456789 \
  --dimensions country,sessionSource \
  --metrics activeUsers,totalRevenue

gplay analytics audience-exports

Manage audience exports.

# List audience exports
gplay analytics audience-exports list --property 123456789

# Create an audience export
gplay analytics audience-exports create \
  --property 123456789 \
  --audience "properties/123456789/audiences/456"

# Query an audience export
gplay analytics audience-exports query \
  --property 123456789 \
  --export-id abc123

Implementation Details

API Endpoints (v1beta)

Method Endpoint Purpose
runReport POST /v1beta/{property=properties/*}:runReport Standard reports
batchRunReports POST /v1beta/{property=properties/*}:batchRunReports Batch up to 5 reports
runPivotReport POST /v1beta/{property=properties/*}:runPivotReport Pivot table reports
batchRunPivotReports POST /v1beta/{property=properties/*}:batchRunPivotReports Batch pivot reports
runRealtimeReport POST /v1beta/{property=properties/*}:runRealtimeReport Real-time data (last 30 min)
getMetadata GET /v1beta/{name=properties/*/metadata} Discover dimensions/metrics
checkCompatibility POST /v1beta/{property=properties/*}:checkCompatibility Validate dim/metric combos

Service endpoint: https://analyticsdata.googleapis.com

Authentication

  • OAuth Scope: https://www.googleapis.com/auth/analytics.readonly (read-only access is sufficient for all reporting operations)
  • Service Account Setup: The same service account JSON key used for Play Console can be used, provided:
    1. The Google Analytics Data API is enabled in the GCP project
    2. The service account email is added as a Viewer on the GA4 property (Admin > Property Access Management)
  • Implementation: Create internal/analyticsclient/client.go following the same pattern as internal/reportingclient/client.go, with scope set to analyticsdata.AnalyticsReadonlyScope

New Packages

internal/
  cli/
    analytics/
      analytics.go           # AnalyticsCommand() group
      report.go              # gplay analytics report
      realtime.go            # gplay analytics realtime
      metadata.go            # gplay analytics metadata
      batch.go               # gplay analytics batch
      check_compatibility.go # gplay analytics check-compatibility
      audience_exports.go    # gplay analytics audience-exports (list/create/query)
      analytics_test.go      # CLI flag/output tests
  analyticsclient/
    client.go                # Authenticated GA4 Data API service wrapper

GA4 Property ID Configuration

  • Flag: --property <id> on every command (required)
  • Environment variable: GPLAY_GA4_PROPERTY as default when --property is omitted
  • Config file: ga4_property: "123456789" in ~/.gplay/config.yaml or .gplay/config.yaml
  • Resolution order: --property flag > GPLAY_GA4_PROPERTY env > config file

Report Request Building

The RunReportRequest struct from the Go client library maps directly to CLI flags:

req := &analyticsdata.RunReportRequest{
    DateRanges: []*analyticsdata.DateRange{{
        StartDate: fromFlag,  // "2026-03-28" or "7daysAgo"
        EndDate:   toFlag,    // "2026-04-04" or "today"
    }},
    Dimensions: parseDimensions(dimensionsFlag), // "country,city" -> []*Dimension
    Metrics:    parseMetrics(metricsFlag),        // "activeUsers,sessions" -> []*Metric
    DimensionFilter: parseFilter(filterFlag),     // "platform==Android" -> *FilterExpression
    MetricFilter:    parseFilter(metricFilterFlag),
    OrderBys:        parseOrderBy(orderByFlag),   // "activeUsers desc" -> []*OrderBy
    Limit:           limitFlag,
    Offset:          offsetFlag,
    ReturnPropertyQuota: includeQuotaFlag,
}

Filter expression parsing should support:

  • Equality: country==US
  • Contains: pagePath~=/store/
  • In-list: country in [US,GB,DE]
  • Numeric: activeUsers>100
  • Compound: country==US AND platform==Android (AND/OR groups)

Go Client Library

  • Package: google.golang.org/api/analyticsdata/v1beta (already available in google.golang.org/api v0.272.0 which is in go.mod)
  • Service creation: analyticsdata.NewService(ctx, option.WithHTTPClient(httpClient))
  • Key types: RunReportRequest, RunReportResponse, Dimension, Metric, DateRange, FilterExpression, Filter, StringFilter, NumericFilter, InListFilter, BetweenFilter, OrderBy
  • No additional Go module dependency is needed since google.golang.org/api is already a dependency

Output Format Considerations

  • JSON (default): Minified JSON of the full API response, consistent with all other commands
  • Table: Particularly useful for analytics data — dimensions as row headers, metrics as columns. Example:
COUNTRY     CITY           ACTIVE USERS   SESSIONS   PAGE VIEWS
US          New York       12,453         18,291     45,012
US          San Francisco  8,102          11,444     28,331
GB          London         6,891          9,234      21,109
  • Markdown: Same tabular layout in markdown format for documentation/reports
  • Table output should right-align numeric metric columns and format large numbers with commas
  • The --include-quota flag appends quota consumption to stderr (not stdout) to keep output pipeable

Quota Awareness

The API enforces token-based quotas per property:

Quota Standard Analytics 360
Tokens per day 200,000 2,000,000
Tokens per hour 40,000 400,000
Tokens per project per hour 14,000 140,000
Concurrent requests 10 50
  • --include-quota returns PropertyQuota showing tokens consumed and remaining
  • Consider printing a stderr warning when remaining daily quota drops below 10%

Registration

Register analytics.AnalyticsCommand() in internal/cli/registry/registry.go, following existing command registration patterns.

Acceptance Criteria

  • [ ] gplay analytics report runs a GA4 report with dimensions, metrics, date ranges, filters, ordering, and limit
  • [ ] gplay analytics realtime queries real-time data with dimensions and metrics
  • [ ] gplay analytics metadata lists available dimensions and metrics for a property
  • [ ] gplay analytics batch runs up to 5 reports in a single API call from a JSON file
  • [ ] gplay analytics check-compatibility validates dimension/metric combinations
  • [ ] gplay analytics audience-exports list/create/query manages audience exports
  • [ ] All commands support --output json/table/markdown and --pretty
  • [ ] GA4 property ID is resolved from --property flag, GPLAY_GA4_PROPERTY env var, or config file
  • [ ] Authentication uses the existing service account infrastructure with analytics.readonly scope
  • [ ] --dry-run logs the API request to stderr without executing
  • [ ] --include-quota reports token usage to stderr
  • [ ] Filter expression parsing supports equality, contains, in-list, numeric, and compound expressions
  • [ ] Table output formats analytics data with aligned columns and number formatting
  • [ ] New internal/analyticsclient/ package follows the pattern of internal/reportingclient/
  • [ ] Command registered in internal/cli/registry/registry.go
  • [ ] UsageFunc: shared.DefaultUsageFunc set on all commands
  • [ ] Timeout respects GPLAY_TIMEOUT via shared.ContextWithTimeout
  • [ ] CLI-level tests cover flag validation, required flags, output formats, and error messages
  • [ ] Unit tests for filter expression parsing, dimension/metric parsing, and date range handling
  • [ ] gplay analytics --help documents all subcommands; each subcommand --help documents all flags

References

tamtom avatar Apr 04 '26 18:04 tamtom

Implementation Checklist

Command & Registration

  • [ ] Command group gplay analytics in internal/cli/analytics/
  • [ ] Subcommands: report run, report batch, realtime, metadata list, dimensions list, metrics list
  • [ ] Registered in internal/cli/registry/registry.go
  • [ ] UsageFunc: shared.DefaultUsageFunc set on all commands
  • [ ] Dedicated client wrapper for analyticsdata/v1beta API
  • [ ] GA4 property ID resolution from flag or config
  • [ ] Required flags validated with stderr error messages

Tests

  • [ ] CLI black-box tests in internal/cmdtest/analytics_test.go
  • [ ] Unit tests for date range parsing, dimension/metric validation
  • [ ] Error paths: missing --property, invalid date range, unknown metric name

Docs & Help

  • [ ] --help output follows existing conventions
  • [ ] Command docs regenerated: gplay docs generate

Validation (before opening PR)

make format
make lint
make test
make build
/tmp/gplay analytics --help
/tmp/gplay analytics report run --help
/tmp/gplay analytics report run            # missing required flags → stderr error
/tmp/gplay analytics report run --property 123 --start-date bad  # invalid date

tamtom avatar Apr 05 '26 04:04 tamtom

Addendum to checklist above — docs CI gate:

The PR CI now runs make check-docs on every PR. This means:

  1. After implementing the command, run make docs to regenerate GPLAY.md
  2. Commit the updated GPLAY.md alongside your code changes
  3. If you forget, the PR check will fail with: "GPLAY.md is out of date"

This ensures every user-facing command, flag, and help text is always reflected in the reference docs.

tamtom avatar Apr 05 '26 04:04 tamtom

Consolidating individual feature requests into the roadmap so new visitors see a clean tracker. This item is on the roadmap: #245 — please 👍 there and comment which item you're waiting on. Reopen or file a fresh issue if you start on a PR.

tamtom avatar Jul 05 '26 10:07 tamtom