:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(google_sheets): support Google Sheets API version v4 (#71676)
Tom Owers1c5c2c388205
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.pyindex 6079fdb02039..bdb924db512b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py@@ -29,6 +29,15 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment# bytes (not total download time), so it stays safe for large sheets that stream in steadily._REQUEST_TIMEOUT_SECONDS: tuple[float, float] = (30.0, 120.0)+# Google Sheets exposes a single current stable REST API version — v4 — which gspread targets for+# every request (its base URL is pinned in gspread.urls and is not per-client configurable); v3 and+# earlier are retired. The resolved version is threaded down to `_get_worksheet`, where it keys the+# worksheet-handle cache, so a future version whose client differs can't reuse another version's+# handle; every supported label resolves to the same v4 calls today. The framework's legacy+# UNVERSIONED default ("v1") predates this metadata and was never Google's v3, so sources created+# before this change keep issuing identical requests.+GOOGLE_SHEETS_API_VERSION_V4 = "v4"+def google_sheets_client() -> gspread.Client:credentials = service_account.Credentials.from_service_account_info(@@ -175,7 +184,11 @@ def _retry_on_transient_api_error(execute: Callable[[], T]) -> T:@cached(cache)-def _get_worksheet(spreadsheet_url: str, worksheet_id: int) -> gspread.Worksheet:+def _get_worksheet(+ spreadsheet_url: str, worksheet_id: int, api_version: str = GOOGLE_SHEETS_API_VERSION_V4+) -> gspread.Worksheet:+ # `api_version` participates in the memoization key so a future version whose client differs+ # can't collide with a cached handle built for another version.def execute() -> gspread.Worksheet:client = google_sheets_client()try:@@ -210,7 +223,9 @@ def get_schemas(config: GoogleSheetsSourceConfig) -> list[tuple[str, int]]:return [(NamingConvention.normalize_identifier(worksheet.title), worksheet.id) for worksheet in worksheets]-def get_schema_incremental_fields(config: GoogleSheetsSourceConfig, worksheet_name: str) -> list[IncrementalField]:+def get_schema_incremental_fields(+ config: GoogleSheetsSourceConfig, worksheet_name: str, api_version: str = GOOGLE_SHEETS_API_VERSION_V4+) -> list[IncrementalField]:worksheets = get_schemas(config)selected_worksheet = [id for name, id in worksheets if name == worksheet_name]if len(selected_worksheet) == 0:@@ -218,7 +233,7 @@ def get_schema_incremental_fields(config: GoogleSheetsSourceConfig, worksheet_naworksheet_id = selected_worksheet[0]- worksheet = _get_worksheet(config.spreadsheet_url, worksheet_id)+ worksheet = _get_worksheet(config.spreadsheet_url, worksheet_id, api_version)try:rows = _retry_on_transient_api_error(lambda: worksheet.get_all_values("1:2")) # Get the first two rows@@ -254,6 +269,7 @@ def google_sheets_source(config: GoogleSheetsSourceConfig,worksheet_name: str,db_incremental_field_last_value: Optional[Any],+ api_version: str,should_use_incremental_field: bool = False,) -> SourceResponse:worksheets = get_schemas(config)@@ -263,7 +279,7 @@ def google_sheets_source(worksheet_id = selected_worksheet[0]- worksheet = _get_worksheet(config.spreadsheet_url, worksheet_id)+ worksheet = _get_worksheet(config.spreadsheet_url, worksheet_id, api_version)headers = _retry_on_transient_api_error(lambda: worksheet.get_all_values("1:1")) # Get the first rowif len(headers) > 0:@@ -283,7 +299,7 @@ def google_sheets_source(# range-based batching (e.g. A2:Z1001, A1002:Z2001, ...), which is a behavior change to# the sync itself and is out of scope for restart-safety alone.def get_rows():- worksheet = _get_worksheet(config.spreadsheet_url, worksheet_id)+ worksheet = _get_worksheet(config.spreadsheet_url, worksheet_id, api_version)# default_blank defaults to "", which turns empty cells into strings and breaks numeric# columns that legitimately have gaps. None lets blank cells import as null instead.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/source.pyindex dfbd100ab561..020a7c826a3d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/source.py@@ -18,13 +18,18 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineSourceInputs,SourceResponse,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ UNVERSIONED_API_VERSION,+ FieldType,+ SimpleSource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistryfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.googlesheets import (GoogleSheetsSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets import (+ GOOGLE_SHEETS_API_VERSION_V4,get_schema_incremental_fields as get_google_sheets_schema_incremental_fields,get_schemas as get_google_sheets_schemas,google_sheets_client,@@ -37,6 +42,12 @@ from products.warehouse_sources.backend.types import ExternalDataSourceTypeclass GoogleSheetsSource(SimpleSource[GoogleSheetsSourceConfig]):api_docs_url = "https://developers.google.com/sheets/api"+ # "v1" is the framework's legacy UNVERSIONED default kept so pre-existing sources stay pinned+ # and unchanged; "v4" names Google's current stable REST API version and is the default for new+ # sources. Both drive identical calls today — see GOOGLE_SHEETS_API_VERSION_V4 in google_sheets.+ supported_versions = (UNVERSIONED_API_VERSION, GOOGLE_SHEETS_API_VERSION_V4)+ default_version = GOOGLE_SHEETS_API_VERSION_V4+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GOOGLESHEETS@@ -73,6 +84,10 @@ class GoogleSheetsSource(SimpleSource[GoogleSheetsSourceConfig]):force_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:+ # Listing worksheets is version-agnostic (gspread's `worksheets()`), but the per-worksheet+ # header read goes through `_get_worksheet`, whose memoization key includes the version —+ # so discovery must resolve the pin rather than let it default.+ resolved_version = self.resolve_api_version(api_version)sheets = get_google_sheets_schemas(config)if names is not None:@@ -81,7 +96,7 @@ class GoogleSheetsSource(SimpleSource[GoogleSheetsSourceConfig]):schemas: list[SourceSchema] = []for name, _ in sheets:- incremental_fields = get_google_sheets_schema_incremental_fields(config, name)+ incremental_fields = get_google_sheets_schema_incremental_fields(config, name, resolved_version)schemas.append(SourceSchema(@@ -102,6 +117,7 @@ class GoogleSheetsSource(SimpleSource[GoogleSheetsSourceConfig]):db_incremental_field_last_value=inputs.db_incremental_field_last_valueif inputs.should_use_incremental_fieldelse None,+ api_version=self.resolve_api_version(inputs.api_version),)def validate_credentials(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.pyindex 8364dea88e8f..a90ad971bbad 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py@@ -8,12 +8,14 @@ import gspreadimport requestsfrom google.auth import exceptions as google_auth_exceptions+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import UNVERSIONED_API_VERSIONfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.googlesheets import (GoogleSheetsSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets import (_PERMISSION_DENIED_MESSAGE,_REQUEST_TIMEOUT_SECONDS,+ GOOGLE_SHEETS_API_VERSION_V4,_assert_unique_normalized_column_names,_get_worksheet,_retry_on_transient_api_error,@@ -398,7 +400,9 @@ def test_google_sheets_source_retries_transient_error_on_data_reads():),mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets.time"),):- response = google_sheets_source(config, "sheet1", db_incremental_field_last_value=None)+ response = google_sheets_source(+ config, "sheet1", db_incremental_field_last_value=None, api_version=GOOGLE_SHEETS_API_VERSION_V4+ )list(cast(Iterable[Any], response.items()))assert mock_worksheet.get_all_values.call_count == 2@@ -425,7 +429,9 @@ def test_google_sheets_source_reads_blank_cells_as_null():return_value=mock_worksheet,),):- response = google_sheets_source(config, "sheet1", db_incremental_field_last_value=None)+ response = google_sheets_source(+ config, "sheet1", db_incremental_field_last_value=None, api_version=GOOGLE_SHEETS_API_VERSION_V4+ )list(cast(Iterable[Any], response.items()))mock_worksheet.get_all_records.assert_called_once_with(default_blank=None)@@ -657,3 +663,69 @@ def test_validate_credentials_maps_google_auth_error(auth_error, expect_retry_hiassert "try again in a moment" in (error_message or "").lower()else:assert "try again in a moment" not in (error_message or "").lower()+++ "pinned_version,expected_version",+ [+ # No pin resolves to the source default — v4, Google's current stable Sheets REST API.+ pytest.param(None, GOOGLE_SHEETS_API_VERSION_V4, id="unpinned_uses_default_v4"),+ # A legacy "v1" pin is honored verbatim so sources created before the v4 label are unaffected.+ pytest.param("v1", "v1", id="legacy_v1_pin_honored"),+ pytest.param(GOOGLE_SHEETS_API_VERSION_V4, GOOGLE_SHEETS_API_VERSION_V4, id="v4_pin_honored"),+ ],+)+def test_source_for_pipeline_threads_resolved_api_version_to_worksheet(pinned_version, expected_version):+ """The source resolves the instance's pin (falling back to the default) and threads the result+ down to `_get_worksheet`, where it keys the handle cache. Dropping the resolve or the threading+ would send the wrong version — or none — to the request layer, breaking the seam every future+ Sheets version relies on. Behaviour is unchanged today because gspread pins the v4 base URL."""+ config = GoogleSheetsSourceConfig(spreadsheet_url="https://docs.google.com/spreadsheets/d/fake")++ worksheet = mock.MagicMock()+ worksheet.get_all_values.return_value = [["id"]]+ worksheet.get_all_records.return_value = [{"id": 1}]++ inputs = mock.MagicMock()+ inputs.schema_name = "sheet1"+ inputs.should_use_incremental_field = False+ inputs.api_version = pinned_version++ with (+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets.get_schemas",+ return_value=[("sheet1", 123)],+ ),+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets._get_worksheet",+ return_value=worksheet,+ ) as mock_get_worksheet,+ ):+ response = GoogleSheetsSource().source_for_pipeline(config, inputs)+ list(cast(Iterable[Any], response.items()))++ assert mock_get_worksheet.called+ assert all(call.args[2] == expected_version for call in mock_get_worksheet.call_args_list)+++ "pin, expected",+ [("v4", "v4"), (None, "v4"), (UNVERSIONED_API_VERSION, UNVERSIONED_API_VERSION)],+)+def test_get_schemas_threads_resolved_pin_into_incremental_fields(pin, expected):+ # `_get_worksheet` memoizes on (url, worksheet_id, api_version), so discovery must pass the+ # source's resolved pin — otherwise a pinned source reads headers under a different key.+ with (+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.source.get_google_sheets_schemas",+ return_value=[("sheet1", 10)],+ ),+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.source.get_google_sheets_schema_incremental_fields",+ return_value=[],+ ) as mock_incremental,+ ):+ config = GoogleSheetsSourceConfig(spreadsheet_url="https://docs.google.com/spreadsheets/d/fake")+ GoogleSheetsSource().get_schemas(config, team_id=1, api_version=pin)++ assert mock_incremental.call_args.args[-1] == expected