← Blog

Google Analytics API Get Keywords: Choose the Right API and Retrieve Search Terms

2026-11-29 · IndexNowFast Team
Google Analytics API Get Keywords: Choose the Right API and Retrieve Search Terms

Quick Answer

For the task behind the search phrase “google analytics api get keywords,” use the Google Search Console Search Analytics API if you want to retrieve organic Google search queries programmatically. Its searchanalytics.query method returns search queries alongside clicks, impressions, click-through rate (CTR), and average position. Use the Google Analytics 4 (GA4) Data API for supported advertising keywords, manually tagged campaign terms, or internal website-search data. Neither API provides a complete record of every search made by individual visitors.

Key Takeaways

  • Use the Search Console Search Analytics API to retrieve organic Google search queries.
  • Use OAuth 2.0 authentication and an authorized Search Console property; an API key alone is insufficient.
  • The main endpoint is POST /sites/{siteUrl}/searchAnalytics/query.
  • Request the query dimension to group results by search term.
  • Add the page dimension to investigate query and landing-page combinations.
  • The GA4 Data API serves different reporting needs, including supported Google Ads, UTM campaign, and internal search dimensions.
  • Search Console can omit some queries, and reporting data is generally delayed by approximately two to three days.

Which Google API Should You Use to Get Keywords?

The first decision is what you mean by a keyword. Google provides different reporting systems for organic search performance, advertising activity, campaign attribution, and searches performed inside a website.

Choosing the wrong API can produce a technically successful report that answers the wrong question.

Google Keyword Retrieval API Decision Matrix

Desired informationCorrect APIMethod or dimensionTypical outputImportant limitation
Organic Google search queriesSearch Console Search Analytics APIsearchanalytics.query, queryClicks, impressions, CTR, average positionSome queries and rows are omitted
Query-to-page combinationsSearch Console Search Analytics APIquery and pageSearch performance grouped by query and pageNot complete visitor-level attribution
Google Ads matched keywordsGA4 Data APICompatible Google Ads keyword dimensionsAdvertising-related Analytics metricsRequires appropriate advertising data and compatible dimensions
Actual Google Ads search queriesGA4 Data APIsessionGoogleAdsQuery, where available and compatibleAdvertising search-query reportingNot the same as the configured targeting keyword
Manually assigned campaign termsGA4 Data APIsessionManualTerm, firstUserManualTermCampaign attribution informationRepresents supplied campaign values, not necessarily actual search queries
Internal website searchesGA4 Data APIsearchTerm and relevant event dataCollected site-search activityRequires suitable site-search tracking

The distinction between a Google Ads keyword and a search query is especially important. A keyword is a term an advertiser configures for targeting. A search query is what someone actually enters into a search engine. They are related but not interchangeable.

When to use the Search Console API

Choose Search Console when your reporting question is:

  • Which organic Google searches generated impressions for my website?
  • How many clicks did a particular query generate?
  • What is the average search position of a query?
  • Which pages receive impressions for a particular search term?
  • How has organic search performance changed over a selected date range?

The Search Analytics API groups performance data using dimensions such as query, page, country, device, and date.

Official documentation: Search Console Search Analytics API.

When GA4 is the better choice

Use the GA4 Data API when you need to analyze activity recorded by Google Analytics, rather than obtain a complete database of external organic Google searches.

For example, an advertising report might use supported Google Ads dimensions, while a campaign report might examine manually assigned UTM values. A website with properly configured internal search tracking can also report search terms entered into its own search function.

The existing How to Add Keywords to Google Analytics: A Step-by-Step GA4 Guide explains the interface-based approach for readers who do not need programmatic extraction.

For automated reporting, however, the API selection should follow the original source of the information.

How to Get Organic Google Keywords Through the Search Console API

Google's Search Analytics API provides programmatic access to Search Console performance information. The principal method is searchanalytics.query.

You send a POST request containing a property, date range, dimensions, and optional filters. Google returns grouped performance rows.

The API endpoint

``http POST https://www.googleapis.com/webmasters/v3/sites/{siteUrl}/searchAnalytics/query ``

Replace {siteUrl} with the URL-encoded identifier of the Search Console property.

Two common property formats are:

URL-prefix property:

``text https://www.example.com/ ``

Domain property:

``text sc-domain:example.com ``

Use the exact property identifier associated with the account authorized to access the data. A property in Google Analytics is not automatically interchangeable with a Search Console property.

Understanding the request parameters

A basic request for organic search queries might look like this:

``json { "startDate": "2026-10-01", "endDate": "2026-10-31", "dimensions": ["query"], "type": "web", "rowLimit": 25000, "startRow": 0 } ``

These dates are illustrative parameters, not actual performance results.

ParameterPurpose
startDateFirst date included in the report
endDateLast date included in the report
dimensionsDetermines how performance is grouped
typeSpecifies the search type, such as web
rowLimitSets the maximum number of rows requested in one response
startRowSpecifies the starting position for pagination

Two date details matter when building a reporting pipeline:

  1. Google interprets Search Analytics dates using Pacific Time.
  2. The endDate is inclusive.

For example, a request covering October 1 through October 31 includes both dates. When comparing API results with reports in another time zone, account for this difference.

The official Search Analytics query reference documents the supported request parameters and response structure.

Set Up API Access and OAuth Authentication

Before making requests, you need an enabled Google Cloud project, suitable API credentials, and permission to access the relevant Search Console property.

Step 1: Create a Google Cloud project

Open the Google Cloud Console.

Create a project or select an existing project that will own the API configuration. Keep your development, testing, and production credentials organized.

If several people maintain the reporting application, establish who controls the project and credential lifecycle.

Step 2: Enable the Search Console API

Find the Search Console API in the Google Cloud API Library and enable it for your project.

API activation and property authorization are separate requirements. Enabling the API does not automatically give your application access to a website's private Search Console performance data.

Step 3: Configure OAuth credentials

Configure an OAuth 2.0 client or an appropriate authorized service identity for your application.

The recommended read-only OAuth scope is:

``text https://www.googleapis.com/auth/webmasters.readonly ``

A broader alternative is:

``text https://www.googleapis.com/auth/webmasters ``

For a reporting application that only reads search performance, the read-only scope is generally the better choice because it follows the principle of least privilege.

Official reference: Search Analytics API authorization.

Step 4: Confirm Search Console property access

The Google identity used by your application must have appropriate access to the Search Console property.

Check the following before troubleshooting your code:

  • The correct Google account is being authorized.
  • The account has access to the intended property.
  • The property identifier matches the request.
  • The requested OAuth scope has been granted.
  • The API is enabled in the correct Cloud project.

An API key alone cannot authorize access to private Search Console performance data. Use OAuth credentials or another supported authorized identity.

Retrieve Keywords With Python

Python is a practical choice for automated keyword extraction because Google provides an official Search Console API Python example.

The following implementation demonstrates how to create an authorized service, request query-level performance, handle an empty response, paginate through results, and export the returned data to CSV.

It assumes that the required Google credentials are already configured in the environment.

Install the required packages

``bash pip install google-api-python-client google-auth pandas ``

For a local development environment, Application Default Credentials can be configured using Google's authentication tools. One common approach is:

``bash gcloud auth application-default login \\ --scopes=https://www.googleapis.com/auth/webmasters.readonly ``

The authorized account must have access to the Search Console property.

For production, use an appropriate securely managed identity or credential arrangement. Do not publish OAuth client secrets, refresh tokens, or private credential files in source code or public repositories.

Build the Search Console service

The following example uses Application Default Credentials:

```python import google.auth from googleapiclient.discovery import build

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

credentials, project_id = google.auth.default( scopes=SCOPES )

service = build( "searchconsole", "v1", credentials=credentials, cache_discovery=False ) ```

This creates the authenticated client. It does not yet retrieve any keyword data.

Request keyword performance data

The next example retrieves query-level search performance for one Search Console property.

```python import pandas as pd from datetime import datetime, timezone

SITE_URL = "sc-domain:example.com" START_DATE = "2026-10-01" END_DATE = "2026-10-31" SEARCH_TYPE = "web" ROW_LIMIT = 25000

all_rows = [] start_row = 0

while True: request_body = { "startDate": START_DATE, "endDate": END_DATE, "dimensions": ["query"], "type": SEARCH_TYPE, "rowLimit": ROW_LIMIT, "startRow": start_row }

response = service.searchanalytics().query( siteUrl=SITE_URL, body=request_body ).execute()

rows = response.get("rows", [])

if not rows: break

for row in rows: query = row["keys"][0]

all_rows.append({ "query": query, "clicks": row.get("clicks", 0), "impressions": row.get("impressions", 0), "ctr": row.get("ctr", 0), "position": row.get("position", 0) })

if len(rows) < ROW_LIMIT: break

start_row += len(rows)

columns = [ "query", "clicks", "impressions", "ctr", "position" ]

results = pd.DataFrame(all_rows, columns=columns)

results.to_csv( "google_search_keywords.csv", index=False )

retrieved_at = datetime.now(timezone.utc).isoformat()

print("Retrieved rows:", len(results)) print("Property:", SITE_URL) print("Date range:", START_DATE, "to", END_DATE) print("Retrieved at:", retrieved_at) print(results.head()) ```

This is an implementation example, not a claim that the code was executed against a real Search Console property. Replace the example property and dates with values appropriate for your environment.

Understand the returned metrics

Each returned row represents a query grouping and its associated search performance.

MetricMeaningExample interpretation
clicksClicks from Google search resultsA query generated 35 clicks
impressionsTimes results appeared in Google searchA query received 1,200 impressions
ctrClicks divided by impressions0.05 represents 5% CTR
positionAverage position of the highest result for the groupingA value of 4.2 is an average position, not a fixed ranking

The figures in the interpretation column are illustrative, not actual API output.

One important detail: average position is an aggregated metric. It should not be interpreted as a guaranteed position for every user, device, country, or search occurrence.

For better reporting, retain the original API response values and avoid converting CTR into a percentage more than once. The API returns CTR as a ratio.

Handle empty results correctly

An empty rows array does not necessarily mean that the API is broken.

Possible explanations include:

  • No reportable search activity exists for the selected period.
  • The property identifier is incorrect.
  • The authorized account lacks access.
  • The requested date range is too recent.
  • Filters or dimensions exclude available records.
  • Privacy and aggregation limitations prevent some information from appearing.

Check authorization and request parameters before treating an empty result as a technical failure.

Retrieve Keyword and Page Combinations

Query-level reporting answers which search terms generated activity. It does not always tell you which landing pages received that activity.

To examine query and page combinations, change the dimensions in the request:

``python request_body = { "startDate": "2026-10-01", "endDate": "2026-10-31", "dimensions": ["query", "page"], "type": "web", "rowLimit": 25000, "startRow": 0 } ``

The response now groups performance by combinations of search query and page.

For example, the same search query might generate impressions for two different URLs. With the query and page dimensions, those combinations can appear as separate rows.

This is useful for:

  • Identifying which pages attract impressions for a particular search term.
  • Finding pages that compete for similar queries.
  • Reviewing whether the intended landing page receives organic visibility.
  • Building page-level performance reports.
  • Investigating changes in query distribution over time.

However, this is not a complete visitor-level attribution dataset. Search Console aggregates its reporting data and can omit rows. A query-page combination should not be treated as a guaranteed record of every search and click.

For a complementary explanation of page-level analysis, see How to See What Keywords a Page Is Ranking For Using Search Console and SEO Tools.

What the GA4 Data API Can Retrieve Instead

The Google Analytics Data API is useful when the desired information belongs to Analytics reporting rather than external organic search-query reporting.

Its primary reporting method is:

``http POST https://analyticsdata.googleapis.com/v1beta/properties/{propertyId}:runReport ``

The API accepts dimensions, metrics, date ranges, and filters to produce customized reports.

Documentation:

The documented read-only OAuth scope is:

``text https://www.googleapis.com/auth/analytics.readonly ``

Google Ads keyword dimensions

The GA4 schema includes advertising-related dimensions such as:

  • googleAdsKeyword
  • sessionGoogleAdsKeyword
  • sessionGoogleAdsQuery

These dimensions relate to advertising data and should not be confused with organic Google search queries.

A configured Google Ads keyword and the actual query entered by a searcher are different pieces of information. Their availability in a report depends on the data and supported dimension and metric combinations.

Manually assigned campaign terms

If campaign URLs use UTM parameters, GA4 can report manually supplied campaign terms through dimensions such as:

  • sessionManualTerm
  • firstUserManualTerm

For example, a campaign URL might include:

``text https://example.com/?utm_source=newsletter&utm_medium=email&utm_campaign=autumn&utm_term=analytics-guide ``

The utm_term value can provide campaign attribution information when the relevant collection and reporting conditions are satisfied. It does not prove that someone searched for that exact phrase on Google.

Internal website search terms

The GA4 searchTerm dimension concerns search terms collected from a website's own search functionality.

For this information to be useful, the website must correctly collect internal search activity through appropriate events and configuration.

For example, if a visitor uses the search box on an online store to search for a product, that internal search activity can be reported when it is properly instrumented. It does not reveal a complete record of the external Google search that originally brought the visitor to the website.

Which API should your reporting application call?

A practical architecture may use both APIs:

  1. Search Console API for organic query impressions, clicks, CTR, and average position.
  2. GA4 Data API for Analytics sessions, engagement, conversions, and supported campaign or advertising dimensions.
  3. A reporting database or warehouse to combine appropriately defined datasets.

Do not automatically join every keyword row to every Analytics session. The systems use different aggregation methods, dimensions, and attribution models. A combined report needs a clearly defined relationship between its datasets.

Why Your API May Return Fewer Keywords Than Expected

One of the most important limitations of Google Search Console reporting is that its API does not expose every underlying search activity.

Google documents internal data limitations and explains that not all rows are guaranteed to be returned. Results are generally sorted by clicks in descending order, and some data can be omitted.

This means a successful API response is not equivalent to a complete organic search log.

1. Privacy-related omissions

Some search queries are not included in reporting because of privacy protections. Low-volume or otherwise restricted queries may therefore be missing from the returned data.

A report with 500 queries should not be interpreted as proof that the website appeared for exactly 500 distinct searches during the selected period.

2. The response has a maximum row size

The Search Analytics API supports a maximum response size of 25,000 rows per request. If more rows are available, use pagination with startRow.

For example:

RequeststartRowrowLimit
First page025,000
Second page25,00025,000
Third page50,00025,000

These are example pagination positions, not a promise that all three pages will contain data.

Google's documentation also specifies a maximum of 50,000 rows per day per search type per property for Search Analytics data retrieval. This is a reporting limit, not a guarantee that 50,000 rows will be available.

See Getting all available performance data for Google's extraction guidance.

3. Recent data may not be available yet

Search Console performance data is not necessarily available immediately.

Google's guidance indicates that data is typically available after approximately two to three days, although actual processing and reporting availability can vary.

A report that ends yesterday may therefore contain less information than a report for a fully processed historical period. For reliable recurring reporting, use a sensible reporting delay instead of assuming that the latest date is complete.

4. Dimensions change the returned dataset

A request using only query produces a different grouping from a request using query and page.

Adding dimensions increases the granularity of the report and can affect the number of returned rows.

Before comparing two exports, check that their dimensions, date ranges, search types, filters, and property identifiers are consistent.

5. Pagination does not eliminate every limitation

Using startRow helps retrieve additional available rows, but it cannot recover information Google does not expose through the reporting system.

Pagination should be implemented alongside a clear understanding of the API's aggregation and completeness limitations.

Official references:

API Quotas, New Capabilities, and Troubleshooting

API quotas are important when building scheduled extraction jobs or dashboards that make frequent requests. However, Search Console and GA4 use different quota systems. Do not apply a limit from one API to the other.

Search Console API usage limits

Search Console API limits account for factors such as user-level, project-level, and site-level request usage.

A reporting application should avoid unnecessary repeated requests, especially when several users or services access the same property.

Official reference: Search Console API usage limits.

GA4 Data API quotas

The GA4 Data API organizes quotas into categories including Core, Realtime, Funnel, and Chat.

Quota consumption depends on factors such as the number of rows, columns, filters, and date ranges requested. A large report with numerous dimensions and metrics can consume resources differently from a small report.

Check the current GA4 Data API quota documentation before designing a high-frequency reporting workflow.

November 16, 2026: Search Analytics API developments

Google Search Central announced additional Search Analytics API reporting and filtering capabilities on November 16, 2026.

The announcement describes:

  • Branded and non-branded query classification through brandedClassification for eligible properties.
  • Web multimodal reporting through the webMultimodal search type.
  • More flexible multi-country and multi-device filtering through filterLists.

These developments can make advanced search-performance reporting more flexible. However, eligibility and supported combinations matter. In particular, branded classification is not universally available to every property.

Before using these additions in production, check the current method reference and property eligibility. Do not assume that an announced feature is available to every account or that its request structure can be inferred from the announcement alone.

Read the Google Search Central announcement for the update and consult the detailed API reference before implementing it.

Common API errors and practical fixes

ProblemPossible causeWhat to check
HTTP 401Missing or invalid authorizationOAuth credentials, token validity, granted scopes
HTTP 403Insufficient permissions or API configurationProperty access, enabled API, authorized identity
HTTP 400Invalid request parametersDate format, dimensions, property identifier, request body
Empty responseNo available matching data or restrictive requestDate range, filters, property, processing delay
Fewer rows than expectedAggregation, privacy restrictions, or row limitsPagination and Search Analytics reporting limitations
Quota errorRequest usage exceeded an applicable limitRequest frequency, quota category, project and user usage

These are diagnostic starting points rather than a guarantee that every error has only one cause. Inspect the actual response body and Google documentation when troubleshooting a production integration.

Build a Reliable Automated Keyword Reporting Workflow

Retrieving keyword data once is relatively straightforward. Maintaining a useful reporting system requires more careful data handling.

A good extraction workflow should preserve enough context to explain where every exported row came from.

Record data provenance

For every extraction, retain the following information:

FieldWhy it matters
Search Console property or GA4 property IDIdentifies the source account and property
Data source and API methodDistinguishes Search Console from Analytics data
Search typeIdentifies the Search Console reporting category
Start and end datesDefines the reporting period
DimensionsExplains how the data was grouped
MetricsIdentifies the measurements returned
Extraction timestampRecords when the data was retrieved
Pagination stateHelps identify incomplete extraction attempts
Applied filtersExplains which records were included or excluded

For example, two reports may both contain a column called query but represent different reporting contexts. Without source metadata, combining them can create misleading results.

Use a repeatable extraction schedule

For most recurring organic keyword reports, a daily extraction is a practical starting point.

A sensible process is:

  1. Select a completed reporting date range.
  2. Request the appropriate Search Console dimensions and metrics.
  3. Retrieve available pages of results using startRow.
  4. Save the raw response or a normalized equivalent.
  5. Record the extraction metadata.
  6. Export the report to CSV or store it in a reporting database.
  7. Compare subsequent snapshots to identify changes.

Avoid assuming that every daily extraction will contain identical results. Search Console can process and update historical reporting data, and its results remain subject to reporting limitations.

For larger systems, storing periodic snapshots makes it easier to investigate changes without confusing a newly retrieved report with a historical record.

Keep indexing checks separate from keyword reporting

Keyword performance and URL indexing are different questions.

Search Console performance reporting tells you about search visibility and engagement. An index-status check tells you whether a URL is reported as indexed or not indexed.

If you need to investigate the indexing status of a large URL list, the IndexNowFast Google Index Checker provides bulk checking and CSV export functionality. It is not an organic keyword database and should not be substituted for the Search Analytics API.

Likewise, the IndexNowFast API documentation describes a separate URL-indexing API for submission and task-status workflows. It does not retrieve GA4 or Search Console keyword information.

Keeping these systems separate prevents an indexing workflow from being mistaken for a search-performance reporting system.

Frequently Asked Questions

Can the GA4 API retrieve organic Google keywords?

Not as a complete organic Google search-query database. Use the Search Console Search Analytics API for organic query performance. The GA4 Data API provides Analytics event and supported advertising, campaign, and internal-search reporting.

Is the Google Search Console API free to use?

Google provides the Search Console API for retrieving performance information without a separate per-keyword purchase. However, API usage limits apply. Check Google's current API usage limits before building a high-volume application.

Do I need an API key or OAuth credentials?

You need an authorized identity with permission to access the Search Console property. OAuth 2.0 is the appropriate approach for private performance data. An API key alone does not grant access to that information.

Can I retrieve keywords for individual pages?

Yes. Request the query and page dimensions together using searchanalytics.query. This provides grouped query-page performance data, although it does not guarantee complete attribution for every search occurrence.

Why are some Google search queries missing?

Search Console applies aggregation and privacy-related reporting limitations. Some low-volume or otherwise restricted queries may not appear, and the API does not guarantee every available row. Pagination helps retrieve additional available results but cannot recover omitted information.

How often should an automated keyword report run?

A daily extraction is a reasonable starting point for many reporting workflows. Because Search Console data is typically available after approximately two to three days, avoid treating the most recent reporting date as necessarily complete. Preserve extraction timestamps and compare consistent date ranges.

Conclusion

Getting Google Analytics API keyword data starts with identifying which keywords you actually need. For organic Google searches, the correct solution is the Google Search Console Search Analytics API, using searchanalytics.query to retrieve grouped query performance.

For supported advertising, UTM campaign, and internal website-search information, the GA4 Data API is the appropriate alternative.

A reliable implementation combines correct API selection, OAuth authorization, carefully constructed requests, pagination, and transparent reporting metadata. Most importantly, treat returned search queries as aggregated performance data rather than a complete record of every visitor's searches.

That distinction makes the resulting keyword reports more accurate, useful, and trustworthy.