How to Connect to Google Search Console & GA4 APIs: A Step-by-Step Developer Guide

This step-by-step instruction manual explains how to connect to the Google Search Console API and Google Analytics 4 (GA4) Data API, configure OAuth 2.0 credentials in the new Google Auth Platform layout, and programmatically query search visibility and ecommerce sales metrics.

To analyze SEO performance at scale or feed search metrics into automated platforms, developers need direct API access. By connecting to the Google Search Console (GSC) API and Google Analytics 4 (GA4) Data API, you can tie organic visibility metrics directly to actual ecommerce sales and transactions. In this guide, we walk through the exact steps to enable both APIs, configure OAuth 2.0 credentials, handle local token authentication, and write Python scripts to query your data.

1. Enable GSC & GA4 APIs in Google Cloud

To use the APIs, you must enable them in the Google Cloud Console:

  1. Go to the Google Cloud Console.
  2. Create a new project (e.g., mcp-search-console) or select an existing one.
  3. Navigate to the APIs & Services dashboard.
  4. Click + ENABLE APIS AND SERVICES at the top.
  5. Search for and enable the following two APIs:
    • Google Search Console API (Webmasters API)
    • Google Analytics Data API (for GA4 reports)

2. Configure Scopes in the Google Auth Platform

Google Cloud has updated its layout to consolidate app settings under the Google Auth Platform sidebar. Follow these steps to configure your OAuth permissions:

  1. In the Google Cloud navigation menu, select APIs & Services >OAuth consent screen.
  2. If prompted, select External User Type and click Create. Fill in the App Name, Support Email, and developer contact details.
  3. Click Save and Continue.
  4. Go to the Data access tab in the left sidebar of the Google Auth Platform menu.
    • Click ADD OR REMOVE SCOPES.
    • Scroll to the bottom of the drawer panel to "Manually add scopes".
    • Paste https://www.googleapis.com/auth/webmasters.readonly (Search Console read-only access) and click Add.
    • Paste https://www.googleapis.com/auth/analytics.readonly (GA4 Data read-only access) and click Add.
    • Check the boxes for both scopes in the table and click Update.
  5. Go to the Audience tab in the left sidebar.
    • Click + ADD USERS under Test Users.
    • Enter your own Google email address (the one associated with the GA4 properties and Search Console properties you wish to query). This is required while the app is in "Testing" mode.

3. Create OAuth 2.0 Credentials

Now, generate the client secrets required for desktop authorization:

  1. Click on Credentials in the left sidebar of the APIs & Services menu.
  2. Click + CREATE CREDENTIALS at the top and select OAuth client ID.
  3. Set the Application Type to Desktop app.
  4. Name your client (e.g., GSC Local Client) and click Create.
  5. A modal will appear showing your Client ID and Client Secret. Click DOWNLOAD JSON.
  6. Rename the downloaded file to client_secrets.json and place it in the root folder of your project repository.

4. Synchronize Python Environment

Ensure you have the required Google client libraries and the Model Context Protocol (MCP) packages installed. In your terminal, run the package synchronization command:

uv sync
uv add google-analytics-data

The core python dependencies required for this setup are:

  • google-api-python-client: The official Google API Python Client.
  • google-analytics-data: The official GA4 Data API client library.
  • google-auth-oauthlib: Integration helper to handle local OAuth server loops.
  • platformdirs: To locate platform-specific user config directories.

5. Configure the GSC MCP Server (Optional)

If you are using a Model Context Protocol (MCP) server host (e.g., Cursor, Antigravity, Claude Desktop), you can configure it by updating your local .mcp.json or mcp.json. This registers the server and passes the path to your client secrets file as an environment variable:

{ "mcpServers": { "mcp-search-console": { "command": "uvx", "args": ["mcp-search-console"], "env": { "GSC_CREDENTIALS_PATH": "/home/username/.gemini/antigravity-ide/gsc_credentials.json", "GSC_OAUTH_CLIENT_SECRETS_FILE": "/absolute/path/to/client_secrets.json", "GSC_DATA_STATE": "all" } } }
}

6. Perform the Initial OAuth Authentication

When running the server or executing a script that makes its first call to the APIs, the OAuth flow starts automatically:

  1. The Python script launches a temporary local web server (e.g., on http://localhost:port/).
  2. The script attempts to open your web browser automatically. If that fails, it prints a secure authorization URL in the console logs:
    Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?...
  3. Click the link, select your Google account, click Continue through Google's unverified app warning.
  4. ⚠️ IMPORTANT: You will see a permissions approval screen. You must check the checkbox next to "View your Google Analytics report data" and GSC permissions, then click Continue.
  5. The OAuth library captures the redirect authorization code, exchanges it for access and refresh tokens, and saves them locally to a file named token.json inside your local user config directory.

Windows WSL2 & Headless Environments Note

If you are developing inside Windows Subsystem for Linux (WSL2) or another headless server environment, keep these details in mind:

  • Manual Browser Authorization: Because WSL2 is headless by default, Python's webbrowser.open() will fail to open a window on Windows automatically. Instead, copy the secure authorization URL from the console logs and open it manually in a browser running on your Windows host.
  • Port Forwarding: WSL2 automatically forwards ports on localhost to your Windows host. This allows the Google authentication redirect (e.g., to http://localhost:8080/) to be intercepted correctly by the local server running inside WSL2. If you experience redirect errors, check your Windows host firewall or WSL2 network configurations.

7. Query GSC and GA4 Report Data

On subsequent runs, the application reads the saved tokens from token.json and automatically handles token refreshes behind the scenes. Here is how you can write Python scripts to query search analytics and ecommerce sales reports:

A. Query Google Search Console Data

from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials

SCOPES = [ "https://www.googleapis.com/auth/webmasters.readonly", "https://www.googleapis.com/auth/analytics.readonly" ]

creds = Credentials.from_authorized_user_file('token.json', SCOPES)

gsc_service = build("searchconsole", "v1", credentials=creds, cache_discovery=False)

request = { "startDate": "2026-05-01", "endDate": "2026-05-28", "dimensions": ["query"], "rowLimit": 10, "dataState": "all" } response = gsc_service.searchanalytics().query(siteUrl="sc-domain:example.com", body=request).execute() rows = response.get("rows", []) for r in rows: print(f"Query: {r['keys'][0]} | Clicks: {r['clicks']} | Impressions: {r['impressions']}")

B. Query GA4 Sales & Transaction Metrics

from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import ( DateRange, Dimension, Metric, RunReportRequest,
)

ga4_client = BetaAnalyticsDataClient(credentials=creds)

request = RunReportRequest( property="properties/YOUR_GA4_PROPERTY_ID", # e.g. "properties/261266719" dimensions=[Dimension(name="sessionDefaultChannelGroup")], metrics=[ Metric(name="sessions"), Metric(name="transactions"), Metric(name="purchaseRevenue") ], date_ranges=[DateRange(start_date="30daysAgo", end_date="today")] )

response = ga4_client.run_report(request)

print(f"{'Channel Group':30s} | {'Sessions':10s} | {'Transactions':12s} | {'Revenue':12s}") print("-" * 75) for row in response.rows: channel = row.dimension_values[0].value sessions = int(row.metric_values[0].value) transactions = int(row.metric_values[1].value) revenue = float(row.metric_values[2].value) print(f"{channel:30s} | {sessions:10d} | {transactions:12d} | €{revenue:,.2f}")

You have now successfully integrated both the Google Search Console API and the Google Analytics 4 Data API, enabling your python scripts to map SEO search visibility alongside direct transaction revenue!

TRUSTED BY LEADING BRANDS
Tower London
Out and Out
Bedstar
Hunter Boots
Care Fertility
Aroma Zone
Interflora
Unbiased
Vera John
Bubble
Mint Outdoor

Ready to Improve Your SEO?

Contact us for a free assessment—no commitment required.