Skip to content

: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.

feat(warehouse_sources): support Similarweb API version V5 (#86366)

Tom Owers0cf7f2293008
diff --git a/.agents/skills/warehouse-source-new-version/SKILL.md b/.agents/skills/warehouse-source-new-version/SKILL.md
index 4df5a117b09f..530fca7b5895 100644
--- a/.agents/skills/warehouse-source-new-version/SKILL.md
+++ b/.agents/skills/warehouse-source-new-version/SKILL.md
@@ -50,7 +50,7 @@ Add it when any of these hold:
3. **Dispatch on `SourceInputs.api_version`** at the request layer:
- Keep it minimal. If the version is just a header/URL segment and response shapes are compatible, thread the version string down to where the client/URL is built (see Stripe: `StripeSource.source_for_pipeline` passes `self.resolve_api_version(inputs.api_version)` → `stripe_source(...)` → `StripeClient(stripe_version=...)`). Resolve through `resolve_api_version` at the source class — never hardcode a fallback version in the request layer.
- Only introduce per-version modules/branches where behavior genuinely diverges (different pagination, different field mapping). Keep all version branching inside the source's own directory — never in shared layers.
- - A source can front several vendor API families versioned on independent tracks, so a source-level bump may move only a subset of its endpoints (and change auth for just those) — dispatch path and auth per endpoint against the resolved pin, leave the rest on their existing wire, and keep the table set identical, rather than rewriting every endpoint to the new label.
+ - A source can front several vendor API families versioned on independent tracks, so a source-level bump may move only a subset of its endpoints (and change auth for just those) — dispatch path and auth per endpoint against the resolved pin, leave the rest on their existing wire, and keep the table set identical, rather than rewriting every endpoint to the new label. The verifiable subset can also be what bounds the move: when the new version's wire is documented (paths, auth, response shape) for only some of the source's endpoints, move those to the new wire and leave the rest on their still-served legacy wire under the new default — the table set stays identical, and no endpoint ships a guessed shape. Blocking the whole bump because part of the wire is undocumented is the wrong call when the vendor still serves the old paths.
- When the new version renames endpoints, changes primary keys, or reshapes responses, the divergence must actually be branched — never leave the old single-version request path serving the new default. All the relevant surfaces can vary by version: `get_rows` receives the resolved pin in `inputs.api_version`; credential fields can key off `default_version`.
- Conversely, don't add inert scaffolding: an `api_version` param no caller varies, or a version→URL map with identical values, is a review finding, not forward-compat. Declaration-only (`supported_versions`/`default_version` and nothing else) is the correct shape just when the gate above passed on a non-wire reason — the old label is being retired, the vendor switches behavior account-side rather than per request, or the source already reads the vendor's newest generation under the framework's legacy unversioned label (verify the request paths the source actually builds, not the label — a legacy label can already ride the new wire, so the new label just formalizes it for new rows and both resolve identically). If the gate passed on nothing at all, there is no PR. When no-header requests resolve to a version bound to the credential account-side (not a moving "latest"), threading a version header is not merely inert — it overrides the customer's chosen version, the silent move this framework exists to prevent — so stay declaration-only and don't send one.
- **Discovery and probe paths receive the pin — consume it.** The framework passes the resolved pin as the `api_version` parameter of `get_schemas`, `validate_credentials`, `get_endpoint_permissions`, and the webhook management methods. A multi-version source MUST build its discovery/probe/webhook clients from that parameter, not from `default_version` or a hardcoded header — otherwise a pinned source discovers/reconciles under the wrong version and its tables can disappear, duplicate, or fail reconciliation. Resolve it with `self.resolve_api_version(api_version)` — callers with a row pass an already-resolved value (mirroring `SourceInputs.api_version`), so the source-side resolve only covers pre-creation calls that pass `None`. Ignoring the parameter is only correct when you can state why the version makes no difference to that path.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/settings.py
index e55c96bc1774..7bc15946883a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/settings.py
@@ -1,9 +1,25 @@
-from dataclasses import dataclass, field
+from dataclasses import field
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import UNVERSIONED_API_VERSION
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.types import IncrementalField
BASE_URL = "https://api.similarweb.com"
+
+# Similarweb's legacy REST API versions each resource in its own URL path segment (`/v1/...`,
+# `/v4/...`) and carries the key in the `api_key` query param. This is the wire the source has
+# always spoken, so it stays the behaviour of a source pinned to the framework's unversioned label.
+API_VERSION_LEGACY = UNVERSIONED_API_VERSION
+# API V5 replaces the per-resource paths with one `/v5/website-analysis` host, `api-key` header
+# auth, and a standardized `{"meta": ..., "data": [...]}` envelope; metrics are selected with a
+# `metrics` query param rather than a per-metric path.
+API_VERSION_V5 = "v5"
+
+# V5 serves every engagement metric from this one multi-metric endpoint. Each per-metric table
+# requests only its own metric so the table set stays identical across versions.
+V5_ENGAGEMENT_PATH = "/v5/website-analysis/websites/traffic-and-engagement"
# Free endpoint (no data credits) that reports the account's remaining credits and data access,
# so credential validation costs the customer nothing.
CAPABILITIES_PATH = "/capabilities"
@@ -19,6 +35,9 @@ CHUNK_ROWS = 5000
PAGE_LIMIT = 100
DEFAULT_COUNTRY = "world"
+# V5 documents the worldwide breakdown as `ww`, where the legacy API used `world`; the sentinel is
+# translated only on the V5 request wire, so stored rows keep the configured `world` value.
+V5_WORLDWIDE_COUNTRY = "ww"
GRANULARITY_OPTIONS = (
("monthly", "Monthly"),
@@ -36,7 +55,7 @@ TRAFFIC_SOURCES = "traffic_sources"
TRAFFIC_BY_COUNTRY = "traffic_by_country"
-@dataclass
+@frozen
class SimilarwebEndpointConfig:
name: str
# `{domain}` is substituted with each configured domain.
@@ -55,6 +74,10 @@ class SimilarwebEndpointConfig:
accepts_granularity: bool = True
# Offset-paginated (`limit`/`offset`) rather than a single full-window response.
paginated: bool = False
+ # The metric name to request from the V5 multi-metric engagement endpoint. Set only on the
+ # engagement tables whose V5 wire is documented; `None` keeps the endpoint on its legacy path
+ # under every pin (its V5 response shape isn't documented in enough detail to implement).
+ v5_metric: str | None = None
_ENGAGEMENT_PATH = "/v1/website/{domain}/total-traffic-and-engagement"
@@ -67,6 +90,7 @@ SIMILARWEB_ENDPOINTS: dict[str, SimilarwebEndpointConfig] = {
primary_keys=["domain", "country", "granularity", "date"],
description="Estimated desktop and mobile web visits per period for each configured domain",
incremental_fields=[incremental_field("date")],
+ v5_metric="visits",
),
PAGE_VIEWS: SimilarwebEndpointConfig(
name=PAGE_VIEWS,
@@ -76,6 +100,7 @@ SIMILARWEB_ENDPOINTS: dict[str, SimilarwebEndpointConfig] = {
primary_keys=["domain", "country", "granularity", "date"],
description="Estimated desktop and mobile web page views per period for each configured domain",
incremental_fields=[incremental_field("date")],
+ v5_metric="page_views",
),
PAGES_PER_VISIT: SimilarwebEndpointConfig(
name=PAGES_PER_VISIT,
@@ -84,6 +109,7 @@ SIMILARWEB_ENDPOINTS: dict[str, SimilarwebEndpointConfig] = {
primary_keys=["domain", "country", "granularity", "date"],
description="Average number of pages viewed per visit, per period, for each configured domain",
incremental_fields=[incremental_field("date")],
+ v5_metric="pages_per_visit",
),
AVERAGE_VISIT_DURATION: SimilarwebEndpointConfig(
name=AVERAGE_VISIT_DURATION,
@@ -92,6 +118,7 @@ SIMILARWEB_ENDPOINTS: dict[str, SimilarwebEndpointConfig] = {
primary_keys=["domain", "country", "granularity", "date"],
description="Average visit duration in seconds, per period, for each configured domain",
incremental_fields=[incremental_field("date")],
+ v5_metric="average_visit_duration",
),
BOUNCE_RATE: SimilarwebEndpointConfig(
name=BOUNCE_RATE,
@@ -100,6 +127,7 @@ SIMILARWEB_ENDPOINTS: dict[str, SimilarwebEndpointConfig] = {
primary_keys=["domain", "country", "granularity", "date"],
description="Share of visits that ended without further interaction, per period, for each configured domain",
incremental_fields=[incremental_field("date")],
+ v5_metric="bounce_rate",
),
GLOBAL_RANK: SimilarwebEndpointConfig(
name=GLOBAL_RANK,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/similarweb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/similarweb.py
index f6001e7555e8..18295aa4b534 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/similarweb.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/similarweb.py
@@ -8,7 +8,6 @@ requested stamped onto them because the payload doesn't carry them.
"""
import re
-import dataclasses
from collections.abc import Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
@@ -17,10 +16,13 @@ from urllib.parse import quote
import requests
from structlog.types import FilteringBoundLogger
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.similarweb.settings import (
+ API_VERSION_V5,
BASE_URL,
CAPABILITIES_PATH,
CHUNK_ROWS,
@@ -29,6 +31,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.similarweb
PAGE_LIMIT,
SIMILARWEB_ENDPOINTS,
TRAFFIC_SOURCES,
+ V5_ENGAGEMENT_PATH,
+ V5_WORLDWIDE_COUNTRY,
SimilarwebEndpointConfig,
)
@@ -40,7 +44,7 @@ _MONTH_PATTERN = re.compile(r"^\d{4}-\d{2}$")
_COUNTRY_PATTERN = re.compile(r"^[a-z]{2}$")
+@frozen
class SimilarwebResumeConfig:
# Index into the configured domain list that the next request should start from.
next_domain_index: int
@@ -108,6 +112,52 @@ def _parse_row_date(value: Any) -> Optional[datetime]:
return None
+def _uses_v5_engagement(config: SimilarwebEndpointConfig, api_version: str) -> bool:
+ """Whether this request goes to the V5 multi-metric engagement endpoint rather than legacy."""
+ return api_version == API_VERSION_V5 and config.v5_metric is not None
+
+
+@frozen
+class _PreparedRequest:
+ url: str
+ params: dict[str, Any]
+ headers: dict[str, str]
+
+
+def _prepare_request(
+ api_key: str,
+ api_version: str,
+ config: SimilarwebEndpointConfig,
+ domain: str,
+ country: str,
+ granularity: str,
+ start_month: Optional[str],
+ end_month: Optional[str],
+ offset: Optional[int] = None,
+) -> _PreparedRequest:
+ """Build the request for one call, dispatching on the resolved API version.
+
+ V5 serves the engagement metrics from one `/v5/website-analysis` endpoint with `api-key` header
+ auth and a `metrics` selector; every other table — and every table under the legacy pin — keeps
+ the per-resource path and `api_key` query param it has always used.
+ """
+ if _uses_v5_engagement(config, api_version):
+ params: dict[str, Any] = {"domain": domain, "metrics": config.v5_metric, "format": "json"}
+ if config.accepts_country:
+ # V5 spells the worldwide breakdown `ww`; the legacy `world` sentinel is rejected there.
+ params["country"] = V5_WORLDWIDE_COUNTRY if country == DEFAULT_COUNTRY else country
+ if config.accepts_granularity:
+ params["granularity"] = granularity
+ if start_month and end_month:
+ params["start_date"] = start_month
+ params["end_date"] = end_month
+ return _PreparedRequest(url=f"{BASE_URL}{V5_ENGAGEMENT_PATH}", params=params, headers={"api-key": api_key})
+
+ url = f"{BASE_URL}{config.path.format(domain=quote(domain, safe=''))}"
+ legacy_params = _build_params(api_key, config, country, granularity, start_month, end_month, offset=offset)
+ return _PreparedRequest(url=url, params=legacy_params, headers={})
+
+
def _build_params(
api_key: str,
config: SimilarwebEndpointConfig,
@@ -135,14 +185,16 @@ def _build_params(
def _request(
session: requests.Session,
+ prepared: _PreparedRequest,
config: SimilarwebEndpointConfig,
domain: str,
- params: dict[str, Any],
logger: FilteringBoundLogger,
) -> dict[str, Any]:
- url = f"{BASE_URL}{config.path.format(domain=quote(domain, safe=''))}"
+ url = prepared.url
try:
- response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+ response = session.get(
+ url, params=prepared.params, headers=prepared.headers or None, timeout=REQUEST_TIMEOUT_SECONDS
+ )
except requests.RequestException as exc:
# Connection/timeout exceptions carry the prepared URL — including the api_key query param —
# and str(exc) is persisted as the import's error, so re-raise with the param-free url only.
@@ -173,8 +225,12 @@ def _series_rows(
country: str,
granularity: str,
logger: FilteringBoundLogger,
+ api_version: str,
) -> list[dict[str, Any]]:
- payload = body.get(config.data_key)
+ # V5 wraps every metric's series under a standardized `data` key; legacy names the key after
+ # the metric. Either way each row carries its `date` and the metric value.
+ data_key = "data" if _uses_v5_engagement(config, api_version) else config.data_key
+ payload = body.get(data_key)
if not isinstance(payload, list):
return []
@@ -285,6 +341,7 @@ def _paginated_rows(
end_month: Optional[str],
resumable_source_manager: ResumableSourceManager[SimilarwebResumeConfig],
logger: FilteringBoundLogger,
+ api_version: str,
) -> Iterator[list[dict[str, Any]]]:
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
start_index = resume.next_domain_index if resume is not None else 0
@@ -295,8 +352,10 @@ def _paginated_rows(
offset = start_offset if index == start_index else 0
while True:
- params = _build_params(api_key, config, country, granularity, start_month, end_month, offset=offset)
- rows = _record_rows(_request(session, config, domain, params, logger), config, domain)
+ prepared = _prepare_request(
+ api_key, api_version, config, domain, country, granularity, start_month, end_month, offset=offset
+ )
+ rows = _record_rows(_request(session, prepared, config, domain, logger), config, domain)
if rows:
yield rows
if len(rows) < PAGE_LIMIT:
@@ -321,6 +380,7 @@ def _series_chunks(
start_month: Optional[str],
end_month: Optional[str],
logger: FilteringBoundLogger,
+ api_version: str,
) -> Iterator[list[dict[str, Any]]]:
"""Collect every domain's series, then emit it ordered by period.
@@ -333,12 +393,12 @@ def _series_chunks(
"""
rows: list[dict[str, Any]] = []
for domain in domains:
- params = _build_params(api_key, config, country, granularity, start_month, end_month)
- body = _request(session, config, domain, params, logger)
+ prepared = _prepare_request(api_key, api_version, config, domain, country, granularity, start_month, end_month)
+ body = _request(session, prepared, config, domain, logger)
if config.name == TRAFFIC_SOURCES:
rows.extend(_traffic_sources_rows(body, config, domain, country, granularity, logger))
else:
- rows.extend(_series_rows(body, config, domain, country, granularity, logger))
+ rows.extend(_series_rows(body, config, domain, country, granularity, logger, api_version))
rows.sort(key=lambda row: (row["date"], row["domain"]))
@@ -355,6 +415,7 @@ def _get_rows(
endpoint: str,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[SimilarwebResumeConfig],
+ api_version: str,
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Any = None,
) -> Iterator[list[dict[str, Any]]]:
@@ -383,6 +444,7 @@ def _get_rows(
end_month,
resumable_source_manager,
logger,
+ api_version,
)
return
@@ -396,6 +458,7 @@ def _get_rows(
start_month,
end_month,
logger,
+ api_version,
)
@@ -408,6 +471,7 @@ def similarweb_source(
endpoint: str,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[SimilarwebResumeConfig],
+ api_version: str,
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Any = None,
) -> SourceResponse:
@@ -424,6 +488,7 @@ def similarweb_source(
endpoint=endpoint,
logger=logger,
resumable_source_manager=resumable_source_manager,
+ api_version=api_version,
should_use_incremental_field=should_use_incremental_field,
db_incremental_field_last_value=db_incremental_field_last_value,
),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/source.py
index 6181d00e115a..757c85870f13 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/source.py
@@ -26,6 +26,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
SimilarwebSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.similarweb.settings import (
+ API_VERSION_LEGACY,
+ API_VERSION_V5,
ENDPOINTS,
GRANULARITY_OPTIONS,
INCREMENTAL_FIELDS,
@@ -47,10 +49,15 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class SimilarwebSource(ResumableSource[SimilarwebSourceConfig, SimilarwebResumeConfig]):
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
- # Similarweb versions each endpoint in its own path segment (the traffic and rank endpoints
- # sit on /v1, the geo breakdown on /v4) rather than exposing one account-wide API version,
- # so there is no single version token to pin.
- api_docs_url = "https://developers.similarweb.com/docs/getting-started"
+ # The legacy REST API versions each resource in its own path segment (`/v1/...`, `/v4/...`);
+ # API V5 replaces that with one `/v5/website-analysis` host that serves every engagement metric
+ # from a single multi-metric endpoint. New sources default to V5; a source pinned to the legacy
+ # label keeps the per-resource paths untouched. Only the engagement tables have a documented V5
+ # wire today, so the rank, traffic-sources and geo tables stay on the still-served legacy paths
+ # under both pins (see `settings.SimilarwebEndpointConfig.v5_metric`).
+ supported_versions = (API_VERSION_LEGACY, API_VERSION_V5)
+ default_version = API_VERSION_V5
+ api_docs_url = "https://developers.similarweb.com/changelog"
@property
def source_type(self) -> ExternalDataSourceType:
@@ -125,6 +132,7 @@ class SimilarwebSource(ResumableSource[SimilarwebSourceConfig, SimilarwebResumeC
endpoint=inputs.schema_name,
logger=inputs.logger,
resumable_source_manager=resumable_source_manager,
+ api_version=self.resolve_api_version(inputs.api_version),
should_use_incremental_field=inputs.should_use_incremental_field,
db_incremental_field_last_value=inputs.db_incremental_field_last_value
if inputs.should_use_incremental_field
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/tests/test_similarweb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/tests/test_similarweb.py
index 60f6a8496e7a..342c72a60178 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/tests/test_similarweb.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/tests/test_similarweb.py
@@ -11,10 +11,16 @@ from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.similarweb.settings import (
+ API_VERSION_LEGACY,
+ API_VERSION_V5,
+ BASE_URL,
GLOBAL_RANK,
PAGE_LIMIT,
+ PAGE_VIEWS,
TRAFFIC_BY_COUNTRY,
TRAFFIC_SOURCES,
+ V5_ENGAGEMENT_PATH,
+ V5_WORLDWIDE_COUNTRY,
VISITS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.similarweb.similarweb import (
@@ -83,6 +89,7 @@ def _run(
start_date: Optional[str] = None,
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Any = None,
+ api_version: str = API_VERSION_LEGACY,
) -> list[list[dict[str, Any]]]:
with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
response = similarweb_source(
@@ -94,12 +101,22 @@ def _run(
endpoint=endpoint,
logger=mock.MagicMock(),
resumable_source_manager=manager if manager is not None else FakeResumeManager(),
+ api_version=api_version,
should_use_incremental_field=should_use_incremental_field,
db_incremental_field_last_value=db_incremental_field_last_value,
)
return list(cast(Iterable[Any], response.items()))
+def _v5_series_body(metric: str, points: list[dict[str, Any]]) -> dict[str, Any]:
+ # V5 wraps every metric's series under a standardized `data` key; each row carries the metric.
+ return {"meta": {"status": "Success"}, "data": points}
+
+
+def _headers(session: mock.MagicMock, index: int = 0) -> Optional[dict[str, str]]:
+ return session.get.call_args_list[index].kwargs["headers"]
+
+
def _params(session: mock.MagicMock, index: int = 0) -> dict[str, Any]:
return session.get.call_args_list[index].kwargs["params"]
@@ -194,6 +211,59 @@ class TestSimilarwebTransport:
assert _params(session)["country"] == "gb"
assert _params(session)["granularity"] == "weekly"
+ @parameterized.expand([("visits", VISITS, "visits"), ("page_views", PAGE_VIEWS, "page_views")])
+ def test_v5_engagement_hits_the_multimetric_endpoint_with_header_auth(
+ self, _name: str, endpoint: str, metric: str
+ ) -> None:
+ session = _session(_response(json_body=_v5_series_body(metric, [{"date": "2024-01-01", metric: 9}])))
+
+ rows = _run(endpoint, session, domains="a.com", api_version=API_VERSION_V5)[0]
+
+ # One `/v5/website-analysis` endpoint serves every metric; the table selects its own via
+ # `metrics`, the key moves to the `api-key` header, and rows come from the `data` envelope.
+ assert _urls(session) == [f"{BASE_URL}{V5_ENGAGEMENT_PATH}"]
+ assert _params(session)["metrics"] == metric
+ assert _params(session)["domain"] == "a.com"
+ assert "api_key" not in _params(session)
+ assert _headers(session) == {"api-key": "key-123"}
+ assert rows == [
+ {
+ "domain": "a.com",
+ "country": "world",
+ "granularity": "monthly",
+ "date": datetime(2024, 1, 1, tzinfo=UTC),
+ metric: 9,
+ }
+ ]
+
+ def test_v5_pin_leaves_non_engagement_tables_on_the_legacy_wire(self) -> None:
+ # Only the engagement family has a documented V5 wire; rank keeps its legacy path and
+ # query-param key even under the V5 pin, so a new V5 source still syncs it.
+ session = _session(_response(json_body=_series_body("global_rank", [{"date": "2024-01", "global_rank": 86}])))
+
+ _run(GLOBAL_RANK, session, domains="a.com", api_version=API_VERSION_V5)
+
+ assert _urls(session) == [f"{BASE_URL}/v1/website/a.com/global-rank/global-rank"]
+ assert _params(session)["api_key"] == "key-123"
+ assert _headers(session) is None
+
+ @parameterized.expand(
+ [
+ # V5 rejects the legacy `world` sentinel and documents `ww`; legacy keeps sending `world`.
+ ("legacy_worldwide_stays_world", API_VERSION_LEGACY, None, "world"),
+ ("v5_worldwide_becomes_ww", API_VERSION_V5, None, V5_WORLDWIDE_COUNTRY),
+ ("v5_explicit_country_passes_through", API_VERSION_V5, "gb", "gb"),
+ ]
+ )
+ def test_worldwide_country_is_translated_only_for_v5(
+ self, _name: str, api_version: str, country: Optional[str], expected_param: str
+ ) -> None:
+ session = _session(_response(json_body={"visits": [], "data": []}))
+
+ _run(VISITS, session, domains="a.com", country=country, api_version=api_version)
+
+ assert _params(session)["country"] == expected_param
+
def test_global_rank_takes_no_filters_and_parses_month_dates(self) -> None:
session = _session(_response(json_body=_series_body("global_rank", [{"date": "2024-01", "global_rank": 86}])))
@@ -358,6 +428,7 @@ class TestSimilarwebTransport:
endpoint=VISITS,
logger=mock.MagicMock(),
resumable_source_manager=FakeResumeManager(),
+ api_version=API_VERSION_LEGACY,
).items(),
)
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/tests/test_similarweb_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/tests/test_similarweb_source.py
index d89e3dbd64c1..09105dd4d796 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/tests/test_similarweb_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/tests/test_similarweb_source.py
@@ -15,6 +15,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.similarweb
CANONICAL_DESCRIPTIONS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.similarweb.settings import (
+ API_VERSION_LEGACY,
+ API_VERSION_V5,
ENDPOINTS,
MAX_DOMAINS,
SIMILARWEB_ENDPOINTS,
@@ -150,6 +152,27 @@ class TestSimilarwebSource:
assert response.sort_mode == "asc"
assert response.partition_keys == ([endpoint.partition_key] if endpoint.partition_key else None)
+ def test_declares_v5_as_default_over_legacy(self) -> None:
+ assert self.source.supported_versions == (API_VERSION_LEGACY, API_VERSION_V5)
+ assert self.source.default_version == API_VERSION_V5
+
+ @parameterized.expand(
+ [
+ ("unpinned_defaults_to_v5", None, API_VERSION_V5),
+ ("legacy_pin_preserved", API_VERSION_LEGACY, API_VERSION_LEGACY),
+ ("v5_pin_preserved", API_VERSION_V5, API_VERSION_V5),
+ ]
+ )
+ def test_source_for_pipeline_passes_the_resolved_api_version(
+ self, _name: str, pin: str | None, expected: str
+ ) -> None:
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ with mock.patch(f"{MODULE}.similarweb_source") as build:
+ self.source.source_for_pipeline(self.config, manager, _inputs(api_version=pin))
+
+ assert build.call_args.kwargs["api_version"] == expected
+
def test_source_for_pipeline_drops_the_watermark_on_a_full_refresh(self) -> None:
manager = mock.MagicMock(spec=ResumableSourceManager)
inputs = _inputs(should_use_incremental_field=False, db_incremental_field_last_value="2024-04")