: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(data-warehouse): implement news_api import source (#67814)
Tom Owers9d9040b92b02
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex d3a21b5a946b..da329134715e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -214,6 +214,7 @@ the row lists both.| mux | HTTP | requests | ✅ || mysql | DB protocol | pymysql | ➖ || new_york_times | HTTP | requests | ✅ |+| news_api | HTTP | requests | ✅ || okta | HTTP | requests | ✅ || nocrm | HTTP | requests | ✅ || northpass_lms | HTTP | requests | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex fe2ebe24ca17..e64754c54ad9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -2136,7 +2136,9 @@ class NewYorkTimesSourceConfig(config.Config):@config.configclass NewsApiSourceConfig(config.Config):- pass+ api_key: str+ query: str+ language: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/canonical_descriptions.pynew file mode 100644index 000000000000..34f33749fbc7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/canonical_descriptions.py@@ -0,0 +1,40 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_ARTICLE_COLUMNS = {+ "source": "The identifier and display name of the source this article came from, as {id, name}.",+ "author": "The author of the article.",+ "title": "The headline or title of the article.",+ "description": "A short description or snippet of the article.",+ "url": "The direct URL to the article. Unique per article and used as the primary key.",+ "urlToImage": "The URL to a relevant image for the article.",+ "publishedAt": "The date and time the article was published, in UTC ISO 8601.",+ "content": "The unformatted content of the article, truncated to around 200 characters on most plans.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "everything": {+ "description": "News and blog articles matching the configured search query, from NewsAPI's /v2/everything endpoint.",+ "docs_url": "https://newsapi.org/docs/endpoints/everything",+ "columns": _ARTICLE_COLUMNS,+ },+ "top_headlines": {+ "description": "Breaking-news headlines matching the configured search query, from NewsAPI's /v2/top-headlines endpoint.",+ "docs_url": "https://newsapi.org/docs/endpoints/top-headlines",+ "columns": _ARTICLE_COLUMNS,+ },+ "sources": {+ "description": "The publishers and blogs available through NewsAPI's top-headlines endpoint.",+ "docs_url": "https://newsapi.org/docs/endpoints/sources",+ "columns": {+ "id": "The unique identifier for the news source. Used as the primary key.",+ "name": "The display name of the news source.",+ "description": "A description of the news source.",+ "url": "The homepage URL of the news source.",+ "category": "The category the news source belongs to (e.g. business, technology).",+ "language": "The two-letter ISO-639-1 language code of the source.",+ "country": "The two-letter ISO 3166-1 country code of the source.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/news_api.py b/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/news_api.pynew file mode 100644index 000000000000..d1bcb56f2c3d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/news_api.py@@ -0,0 +1,255 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+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.news_api.settings import (+ NEWS_API_ENDPOINTS,+ NewsApiEndpointConfig,+)++NEWS_API_BASE_URL = "https://newsapi.org"++# NewsAPI caps pageSize at 100 and total reachable results per query window at 100. A page cap is a+# defensive backstop in case a paid plan lets pagination run further than expected.+PAGE_SIZE = 100+MAX_PAGES = 100++# NewsAPI error codes that are permanent config errors (not transient) — stop paginating without+# raising, so a full sync of the reachable window still completes.+_TERMINAL_RESULT_CODES = {"maximumResultsReached"}+++class NewsApiRetryableError(Exception):+ pass+++class NewsApiResumeConfig:+ # Next page number to request. Pagination is 1-indexed; resume picks up mid-endpoint after a+ # heartbeat timeout without restarting from page 1.+ next_page: int+++def _get_headers(api_key: str) -> dict[str, str]:+ # Header auth avoids leaking the key into request URLs / logs (the apiKey query param is the+ # documented alternative). `Accept` keeps NewsAPI on its JSON contract.+ return {"X-Api-Key": api_key, "Accept": "application/json"}+++def _format_from_value(value: Any) -> str | None:+ """Format an incremental cursor value for NewsAPI's `from` param (ISO 8601)."""+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")+ if isinstance(value, date):+ return value.isoformat()+ if isinstance(value, str) and value:+ return value+ return None+++def _build_params(+ config: NewsApiEndpointConfig,+ query: str,+ language: str | None,+ page: int,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, Any]:+ params: dict[str, Any] = {}++ # /v2/top-headlines/sources takes no query/pagination — only optional facet filters.+ if config.name == "sources":+ if language:+ params["language"] = language+ return params++ if query:+ params["q"] = query+ if config.paginated:+ params["pageSize"] = PAGE_SIZE+ params["page"] = page++ if config.name == "everything":+ # publishedAt is the only sort NewsAPI exposes for /v2/everything; it returns newest-first+ # (descending), which is why the SourceResponse below declares sort_mode="desc".+ params["sortBy"] = "publishedAt"+ # `language` is only a valid filter on /v2/everything (top-headlines uses country/category).+ if language:+ params["language"] = language+ if config.supports_incremental and should_use_incremental_field:+ from_value = _format_from_value(db_incremental_field_last_value)+ if from_value:+ params["from"] = from_value++ return params+++def validate_credentials(api_key: str) -> bool:+ # /v2/top-headlines/sources is the cheapest probe: it needs only a valid key (no query params),+ # so it confirms the token without spending a search request.+ url = f"{NEWS_API_BASE_URL}/v2/top-headlines/sources"+ try:+ session = make_tracked_session(headers=_get_headers(api_key), redact_values=(api_key,))+ response = session.get(url, timeout=10)+ return response.status_code == 200+ except Exception:+ return False+++@retry(+ retry=retry_if_exception_type(+ (+ NewsApiRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict[str, Any]:+ response = session.get(url, headers=headers, timeout=60)++ # NewsAPI rate-limits with 429 and returns 5xx on transient outages — both worth retrying.+ if response.status_code == 429 or response.status_code >= 500:+ raise NewsApiRetryableError(f"NewsAPI error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"NewsAPI error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def get_rows(+ api_key: str,+ endpoint: str,+ query: str,+ language: str | None,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NewsApiResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = NEWS_API_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ # redact_values scrubs the key from tracked telemetry / captured samples — the X-Api-Key header+ # value isn't reliably redacted by header name alone.+ session = make_tracked_session(redact_values=(api_key,))++ # Non-paginated endpoints (sources) return everything in one response — no resume state.+ if not config.paginated:+ url = f"{NEWS_API_BASE_URL}{config.path}"+ params = _build_params(+ config, query, language, 1, should_use_incremental_field, db_incremental_field_last_value+ )+ if params:+ url = f"{url}?{urlencode(params)}"+ data = _fetch_page(session, url, headers, logger)+ rows = data.get(config.data_key, [])+ if rows:+ yield rows+ return++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.next_page if resume else 1++ while page <= MAX_PAGES:+ params = _build_params(+ config, query, language, page, should_use_incremental_field, db_incremental_field_last_value+ )+ url = f"{NEWS_API_BASE_URL}{config.path}?{urlencode(params)}"++ try:+ data = _fetch_page(session, url, headers, logger)+ except requests.HTTPError as exc:+ # NewsAPI returns 426 with code `maximumResultsReached` once pagination hits the reachable+ # cap. That's a normal terminal condition for the query window, not a failure — stop cleanly.+ code = _error_code(exc)+ if code in _TERMINAL_RESULT_CODES:+ logger.info(f"NewsAPI: reached result cap for endpoint={endpoint} at page={page}, stopping")+ break+ raise++ rows = data.get(config.data_key, [])+ if not rows:+ break++ yield rows++ total_results = data.get("totalResults") or 0+ # Stop when we've drained the reachable set: a short final page, or (when the API reports a+ # positive total) we've paged past it. Guard on `total_results` so a missing/zero total on a+ # full page doesn't stop us early and silently drop later pages — the short-page check,+ # MAX_PAGES cap, and `maximumResultsReached` still bound the walk.+ if len(rows) < PAGE_SIZE or (total_results and page * PAGE_SIZE >= total_results):+ break++ page += 1+ # Save AFTER yielding so a crash re-yields the last page (merge dedupes on the primary key)+ # rather than skipping it.+ resumable_source_manager.save_state(NewsApiResumeConfig(next_page=page))+++def _error_code(exc: requests.HTTPError) -> str | None:+ """Pull NewsAPI's machine-readable `code` out of an error response body, if present."""+ # `HTTPError.response` is typed non-optional but is None at runtime when the error carries no+ # response, so read it defensively via getattr rather than trusting the annotation.+ response = getattr(exc, "response", None)+ if response is None:+ return None+ try:+ return response.json().get("code")+ except ValueError:+ return None+++def news_api_source(+ api_key: str,+ endpoint: str,+ query: str,+ language: str | None,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NewsApiResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = NEWS_API_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ query=query,+ language=language,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # /v2/everything returns newest-first, so the incremental endpoint must declare desc or the+ # pipeline would corrupt the watermark. The full-refresh endpoints don't track a watermark,+ # so their arrival order is immaterial — leave them on the default.+ sort_mode="desc" if config.supports_incremental else "asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/settings.pynew file mode 100644index 000000000000..ad60cc9eac4f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/settings.py@@ -0,0 +1,75 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class NewsApiEndpointConfig:+ name: str+ path: str+ # Key in the JSON response body that holds the row list ("articles" or "sources").+ data_key: str+ primary_keys: list[str]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable datetime field to partition by. `publishedAt` never changes once an article is+ # published, so it is safe for partitioning; `sources` has no timestamp so it is unpartitioned.+ partition_key: Optional[str] = None+ # True only where the API exposes a genuine server-side timestamp filter (`from`/`to` on+ # /v2/everything). Full-refresh endpoints leave this False.+ supports_incremental: bool = False+ # Whether the endpoint paginates via page/pageSize. /v2/top-headlines/sources returns the full+ # publisher list in one response.+ paginated: bool = True+ should_sync_default: bool = True+++_PUBLISHED_AT_INCREMENTAL: list[IncrementalField] = [+ {+ "label": "publishedAt",+ "type": IncrementalFieldType.DateTime,+ "field": "publishedAt",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++NEWS_API_ENDPOINTS: dict[str, NewsApiEndpointConfig] = {+ # Full article search. `from`/`to` filter server-side on publishedAt, so this is the only+ # endpoint that supports incremental sync. NewsAPI caps reachable results per query window at+ # 100 (deep history requires narrowing the date window, not deep pagination), so incremental+ # syncs advance the `from` cursor on publishedAt each run.+ "everything": NewsApiEndpointConfig(+ name="everything",+ path="/v2/everything",+ data_key="articles",+ primary_keys=["url"],+ partition_key="publishedAt",+ supports_incremental=True,+ incremental_fields=_PUBLISHED_AT_INCREMENTAL,+ ),+ # Curated breaking-news headlines. No date filter is available, so full refresh only.+ "top_headlines": NewsApiEndpointConfig(+ name="top_headlines",+ path="/v2/top-headlines",+ data_key="articles",+ primary_keys=["url"],+ partition_key="publishedAt",+ supports_incremental=False,+ ),+ # The publisher catalog behind top-headlines. Small, static-ish list returned in one response.+ "sources": NewsApiEndpointConfig(+ name="sources",+ path="/v2/top-headlines/sources",+ data_key="sources",+ primary_keys=["id"],+ supports_incremental=False,+ paginated=False,+ ),+}++ENDPOINTS = tuple(NEWS_API_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in NEWS_API_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/source.pyindex c1085f1ea585..424def5c320a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/source.py@@ -1,19 +1,45 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import NewsApiSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.news_api.news_api import (+ NewsApiResumeConfig,+ news_api_source,+ validate_credentials as validate_news_api_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.news_api.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ NEWS_API_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class NewsApiSource(SimpleSource[NewsApiSourceConfig]):+class NewsApiSource(ResumableSource[NewsApiSourceConfig, NewsApiResumeConfig]):+ # get_schemas iterates a static endpoint catalog with no I/O, so the table list is safe to+ # render in public docs without credentials.+ lists_tables_without_credentials = True+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.NEWSAPI@@ -24,7 +50,123 @@ class NewsApiSource(SimpleSource[NewsApiSourceConfig]):name=SchemaExternalDataSourceType.NEWS_API,category=DataWarehouseSourceCategory.ANALYTICS,label="NewsAPI",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["newsapi", "news api"],+ caption="""Enter your NewsAPI key to pull live and historical news articles into the PostHog Data warehouse.++Create a free API key at [newsapi.org](https://newsapi.org/register). The search query drives the `everything` and `top_headlines` tables; the `sources` table lists available publishers.++Note: NewsAPI's free Developer plan is limited to articles from the last month and is for development/testing only — a paid plan is required for production use and older articles.""",iconPath="/static/services/news_api.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/news-api",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="query",+ label="Search query",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="e.g. bitcoin OR ethereum",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="language",+ label="Language (optional, 2-letter code)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="e.g. en",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.news_api.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked NewsAPI key returns 401. Retrying can never satisfy a credential+ # problem, so stop the sync. Match the stable status text, not the per-request path/query.+ "401 Client Error": "Your NewsAPI key is invalid or has been revoked. Create a new key at newsapi.org and reconnect.",+ "426 Client Error": "This request requires a paid NewsAPI plan (e.g. articles older than one month, or beyond the free-tier result limit). Upgrade your plan at newsapi.org and reconnect.",+ }++ def get_schemas(+ self,+ config: NewsApiSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _description(endpoint: str) -> str | None:+ if endpoint == "everything":+ return "Full article search. Incremental sync windows on publishedAt; NewsAPI caps reachable results per window at 100"+ if endpoint == "top_headlines":+ return "Curated breaking-news headlines. Full refresh only (no date filter)"+ if endpoint == "sources":+ return "The publisher catalog behind top-headlines. Full refresh only"+ return None++ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = NEWS_API_ENDPOINTS[endpoint]+ has_incremental = endpoint_config.supports_incremental and bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ description=_description(endpoint),+ detected_primary_keys=endpoint_config.primary_keys,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: NewsApiSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_news_api_credentials(config.api_key):+ return True, None++ return False, "Invalid NewsAPI key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[NewsApiResumeConfig]:+ return ResumableSourceManager[NewsApiResumeConfig](inputs, NewsApiResumeConfig)++ def source_for_pipeline(+ self,+ config: NewsApiSourceConfig,+ resumable_source_manager: ResumableSourceManager[NewsApiResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return news_api_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ query=config.query,+ language=config.language or None,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ 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+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/tests/test_news_api.py b/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/tests/test_news_api.pynew file mode 100644index 000000000000..1d664f449bae--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/tests/test_news_api.py@@ -0,0 +1,345 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.news_api import news_api+from products.warehouse_sources.backend.temporal.data_imports.sources.news_api.news_api import (+ PAGE_SIZE,+ NewsApiResumeConfig,+ _build_params,+ _error_code,+ _format_from_value,+ get_rows,+ news_api_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.news_api.settings import NEWS_API_ENDPOINTS+++class TestFormatFromValue:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14"),+ ("naive_datetime_assumed_utc", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14"),+ ("date_value", date(2026, 3, 4), "2026-03-04"),+ ("string_passthrough", "2026-03-04T00:00:00", "2026-03-04T00:00:00"),+ ("empty_string", "", None),+ ("none", None, None),+ ]+ )+ def test_format_from_value(self, _name: str, value: Any, expected: str | None) -> None:+ assert _format_from_value(value) == expected+++class TestBuildParams:+ def test_everything_incremental_includes_from_and_sort(self) -> None:+ params = _build_params(+ NEWS_API_ENDPOINTS["everything"],+ query="bitcoin",+ language="en",+ page=1,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )+ assert params["q"] == "bitcoin"+ assert params["sortBy"] == "publishedAt"+ assert params["pageSize"] == PAGE_SIZE+ assert params["page"] == 1+ assert params["language"] == "en"+ assert params["from"] == "2026-03-04T02:58:14"++ def test_everything_without_incremental_omits_from(self) -> None:+ # A full refresh (or first sync) must not send a `from` filter, or it would clip history.+ params = _build_params(+ NEWS_API_ENDPOINTS["everything"],+ query="bitcoin",+ language=None,+ page=2,+ should_use_incremental_field=False,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ assert "from" not in params+ assert "language" not in params+ assert params["page"] == 2++ def test_top_headlines_has_no_date_filter_or_language(self) -> None:+ # top-headlines exposes no `from`/`to` and no `language` param, so neither should leak in even+ # when a cursor value / language is supplied.+ params = _build_params(+ NEWS_API_ENDPOINTS["top_headlines"],+ query="bitcoin",+ language="en",+ page=1,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ assert params["q"] == "bitcoin"+ assert params["pageSize"] == PAGE_SIZE+ assert "from" not in params+ assert "sortBy" not in params+ assert "language" not in params++ def test_sources_ignores_query_and_pagination(self) -> None:+ # /v2/top-headlines/sources takes neither q nor pagination; only optional facet filters.+ params = _build_params(+ NEWS_API_ENDPOINTS["sources"],+ query="bitcoin",+ language="en",+ page=1,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ assert params == {"language": "en"}+++class TestErrorCode:+ def test_extracts_code_from_body(self) -> None:+ resp = MagicMock()+ resp.json.return_value = {"status": "error", "code": "maximumResultsReached"}+ assert _error_code(requests.HTTPError(response=resp)) == "maximumResultsReached"++ def test_returns_none_when_body_not_json(self) -> None:+ resp = MagicMock()+ resp.json.side_effect = ValueError("no json")+ assert _error_code(requests.HTTPError(response=resp)) is None++ def test_returns_none_without_response(self) -> None:+ assert _error_code(requests.HTTPError(response=None)) is None # type: ignore[arg-type]+++class TestFetchPageRetry:+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])+ def test_retryable_status_codes_retry(self, _name: str, status_code: int) -> None:+ retryable = MagicMock(status_code=status_code)+ good = MagicMock(status_code=200, ok=True)+ good.json.return_value = {"articles": []}++ session = MagicMock()+ session.get.side_effect = [retryable, good]++ with patch.object(news_api._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = news_api._fetch_page(session, "https://newsapi.org/v2/everything", {}, MagicMock())++ assert result == {"articles": []}+ assert session.get.call_count == 2++ def test_client_error_raises_immediately(self) -> None:+ # A 401 is a permanent credential failure — it must surface at once, not burn retries.+ resp = MagicMock(status_code=401, ok=False, text="unauthorized")+ resp.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=resp)+ session = MagicMock()+ session.get.return_value = resp++ with pytest.raises(requests.HTTPError):+ news_api._fetch_page(session, "https://newsapi.org/v2/everything", {}, MagicMock())++ assert session.get.call_count == 1+++class _FakeResumableManager:+ def __init__(self, state: NewsApiResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[NewsApiResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> NewsApiResumeConfig | None:+ return self._state++ def save_state(self, data: NewsApiResumeConfig) -> None:+ self.saved.append(data)+++def _collect(+ endpoint: str, pages_by_url: dict[str, Any], manager: _FakeResumableManager, monkeypatch: Any+) -> list[dict]:+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ result = pages_by_url[url]+ if isinstance(result, Exception):+ raise result+ return result++ monkeypatch.setattr(news_api, "_fetch_page", fake_fetch)+ monkeypatch.setattr(news_api, "make_tracked_session", lambda **_: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="k",+ endpoint=endpoint,+ query="bitcoin",+ language=None,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows+++class TestGetRows:+ def test_sources_endpoint_yields_once_without_resume(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ "https://newsapi.org/v2/top-headlines/sources": {+ "status": "ok",+ "sources": [{"id": "bbc-news"}, {"id": "wired"}],+ }+ }+ rows = _collect("sources", pages, manager, monkeypatch)+ assert [r["id"] for r in rows] == ["bbc-news", "wired"]+ # Non-paginated endpoints never checkpoint — there's nothing to resume.+ assert manager.saved == []++ def test_short_page_terminates_pagination(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ "https://newsapi.org/v2/everything?q=bitcoin&pageSize=100&page=1&sortBy=publishedAt": {+ "status": "ok",+ "totalResults": 2,+ "articles": [{"url": "a"}, {"url": "b"}],+ }+ }+ rows = _collect("everything", pages, manager, monkeypatch)+ assert [r["url"] for r in rows] == ["a", "b"]+ assert manager.saved == []++ def test_walks_multiple_pages_and_checkpoints_after_each(self, monkeypatch: Any) -> None:+ full_page = [{"url": f"u{i}"} for i in range(PAGE_SIZE)]+ pages = {+ "https://newsapi.org/v2/everything?q=bitcoin&pageSize=100&page=1&sortBy=publishedAt": {+ "totalResults": 150,+ "articles": full_page,+ },+ "https://newsapi.org/v2/everything?q=bitcoin&pageSize=100&page=2&sortBy=publishedAt": {+ "totalResults": 150,+ "articles": [{"url": "last"}],+ },+ }+ manager = _FakeResumableManager()+ rows = _collect("everything", pages, manager, monkeypatch)++ assert len(rows) == PAGE_SIZE + 1+ # State is saved AFTER the first page is yielded so a crash re-yields it (merge dedupes),+ # and it points at the next page to fetch. The short final page ends the walk with no save.+ assert manager.saved == [NewsApiResumeConfig(next_page=2)]++ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(state=NewsApiResumeConfig(next_page=2))+ pages = {+ "https://newsapi.org/v2/everything?q=bitcoin&pageSize=100&page=2&sortBy=publishedAt": {+ "totalResults": 150,+ "articles": [{"url": "resumed"}],+ }+ }+ rows = _collect("everything", pages, manager, monkeypatch)+ # It must start at page 2 (not page 1); page-1 URL isn't in `pages`, so a KeyError would+ # signal a regression that ignored the saved cursor.+ assert [r["url"] for r in rows] == ["resumed"]++ def test_full_page_with_missing_total_keeps_paging(self, monkeypatch: Any) -> None:+ # A full page with `totalResults` absent must not stop the walk — otherwise `page*PAGE_SIZE >= 0`+ # would truncate after page 1 and silently drop later pages. The short page 2 ends it.+ pages = {+ "https://newsapi.org/v2/everything?q=bitcoin&pageSize=100&page=1&sortBy=publishedAt": {+ "articles": [{"url": f"u{i}"} for i in range(PAGE_SIZE)],+ },+ "https://newsapi.org/v2/everything?q=bitcoin&pageSize=100&page=2&sortBy=publishedAt": {+ "articles": [{"url": "tail"}],+ },+ }+ manager = _FakeResumableManager()+ rows = _collect("everything", pages, manager, monkeypatch)+ assert len(rows) == PAGE_SIZE + 1++ def test_maximum_results_reached_stops_cleanly(self, monkeypatch: Any) -> None:+ # NewsAPI returns 426 `maximumResultsReached` past the reachable cap. That's a normal end of+ # the window, so the sync keeps the rows it already has instead of failing.+ cap_response = MagicMock()+ cap_response.json.return_value = {"status": "error", "code": "maximumResultsReached"}+ pages = {+ "https://newsapi.org/v2/everything?q=bitcoin&pageSize=100&page=1&sortBy=publishedAt": {+ "totalResults": 500,+ "articles": [{"url": f"u{i}"} for i in range(PAGE_SIZE)],+ },+ "https://newsapi.org/v2/everything?q=bitcoin&pageSize=100&page=2&sortBy=publishedAt": requests.HTTPError(+ response=cap_response+ ),+ }+ manager = _FakeResumableManager()+ rows = _collect("everything", pages, manager, monkeypatch)+ assert len(rows) == PAGE_SIZE++ def test_other_http_error_propagates(self, monkeypatch: Any) -> None:+ resp = MagicMock()+ resp.json.return_value = {"status": "error", "code": "parameterInvalid"}+ pages = {+ "https://newsapi.org/v2/everything?q=bitcoin&pageSize=100&page=1&sortBy=publishedAt": requests.HTTPError(+ response=resp+ ),+ }+ manager = _FakeResumableManager()+ with pytest.raises(requests.HTTPError):+ _collect("everything", pages, manager, monkeypatch)+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False)])+ def test_status_maps_to_bool(self, _name: str, status_code: int, expected: bool) -> None:+ session = MagicMock()+ session.get.return_value = MagicMock(status_code=status_code)+ with patch.object(news_api, "make_tracked_session", return_value=session):+ assert validate_credentials("k") is expected++ def test_network_failure_is_invalid(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(news_api, "make_tracked_session", return_value=session):+ assert validate_credentials("k") is False+++class TestSourceResponse:+ @parameterized.expand(+ [+ # Only the incremental endpoint declares desc — the full-refresh tables have no watermark+ # to protect, so their arrival order stays on the default.+ ("everything", ["url"], "desc"),+ ("top_headlines", ["url"], "asc"),+ ("sources", ["id"], "asc"),+ ]+ )+ def test_primary_keys_and_sort_mode_per_endpoint(+ self, endpoint: str, expected_keys: list[str], expected_sort: str+ ) -> None:+ response = news_api_source(+ api_key="k",+ endpoint=endpoint,+ query="bitcoin",+ language=None,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == expected_keys+ assert response.sort_mode == expected_sort++ @parameterized.expand([("everything", "publishedAt"), ("top_headlines", "publishedAt"), ("sources", None)])+ def test_partition_key_per_endpoint(self, endpoint: str, expected_partition: str | None) -> None:+ response = news_api_source(+ api_key="k",+ endpoint=endpoint,+ query="bitcoin",+ language=None,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ if expected_partition is None:+ assert response.partition_keys is None+ assert response.partition_mode is None+ else:+ assert response.partition_keys == [expected_partition]+ assert response.partition_mode == "datetime"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/tests/test_news_api_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/tests/test_news_api_source.pynew file mode 100644index 000000000000..f7a0c06392dc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/news_api/tests/test_news_api_source.py@@ -0,0 +1,147 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import NewsApiSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.news_api.news_api import NewsApiResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.news_api.source import NewsApiSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(language: str | None = None) -> NewsApiSourceConfig:+ return NewsApiSourceConfig(api_key="k", query="bitcoin", language=language)+++class TestNewsApiSource:+ def setup_method(self) -> None:+ self.source = NewsApiSource()+ self.team_id = 123++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.NEWSAPI++ def test_lists_tables_without_credentials(self) -> None:+ # get_schemas is a static, no-I/O catalog, so the public docs render the table list.+ assert self.source.lists_tables_without_credentials is True++ @parameterized.expand([("401 Client Error",), ("426 Client Error",)])+ def test_non_retryable_error_keys(self, expected_key: str) -> None:+ assert expected_key in self.source.get_non_retryable_errors()++ def test_source_config_required_fields(self) -> None:+ fields = {f.name: f for f in self.source.get_source_config.fields if isinstance(f, SourceFieldInputConfig)}+ assert set(fields) == {"api_key", "query", "language"}+ assert fields["api_key"].required is True+ assert fields["api_key"].secret is True+ assert fields["query"].required is True+ # The search query drives the article endpoints — a source with no query can't sync them.+ assert fields["language"].required is False++ @parameterized.expand(+ [+ ("everything", True),+ ("top_headlines", False),+ ("sources", False),+ ]+ )+ def test_schema_incremental_support(self, endpoint: str, expected_incremental: bool) -> None:+ # Only /v2/everything exposes a server-side date filter, so it's the only incremental table.+ schemas = {s.name: s for s in self.source.get_schemas(_config(), team_id=self.team_id)}+ assert schemas[endpoint].supports_incremental is expected_incremental+ assert schemas[endpoint].supports_append is expected_incremental++ def test_get_schemas_names_filter(self) -> None:+ schemas = self.source.get_schemas(_config(), team_id=self.team_id, names=["sources"])+ assert [s.name for s in schemas] == ["sources"]++ def test_everything_incremental_field_is_published_at(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(_config(), team_id=self.team_id)}+ fields = [f["field"] for f in schemas["everything"].incremental_fields]+ assert fields == ["publishedAt"]++ def test_validate_credentials_success(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.news_api.source.validate_news_api_credentials",+ return_value=True,+ ):+ assert self.source.validate_credentials(_config(), self.team_id) == (True, None)++ def test_validate_credentials_failure_message(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.news_api.source.validate_news_api_credentials",+ return_value=False,+ ):+ valid, message = self.source.validate_credentials(_config(), self.team_id)+ assert valid is False+ assert message == "Invalid NewsAPI key"++ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:+ inputs = MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is NewsApiResumeConfig++ def test_source_for_pipeline_plumbs_query_and_language(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "everything"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-03-04T00:00:00"++ captured: dict[str, Any] = {}+ sentinel = MagicMock()++ def fake_source(**kwargs: Any) -> Any:+ captured.update(kwargs)+ return sentinel++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.news_api.source.news_api_source",+ side_effect=fake_source,+ ):+ result = self.source.source_for_pipeline(_config(language="en"), MagicMock(), inputs)++ assert result is sentinel+ assert captured["endpoint"] == "everything"+ assert captured["query"] == "bitcoin"+ assert captured["language"] == "en"+ assert captured["db_incremental_field_last_value"] == "2026-03-04T00:00:00"++ def test_source_for_pipeline_drops_cursor_on_full_refresh(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "top_headlines"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-03-04T00:00:00"++ captured: dict[str, Any] = {}++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.news_api.source.news_api_source",+ side_effect=lambda **kwargs: captured.update(kwargs),+ ):+ self.source.source_for_pipeline(_config(), MagicMock(), inputs)++ # A full-refresh sync must not forward a stale watermark as `from`.+ assert captured["db_incremental_field_last_value"] is None++ def test_empty_language_becomes_none(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "everything"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = None++ captured: dict[str, Any] = {}+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.news_api.source.news_api_source",+ side_effect=lambda **kwargs: captured.update(kwargs),+ ):+ self.source.source_for_pipeline(_config(language=""), MagicMock(), inputs)++ assert captured["language"] is None++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ canonical = self.source.get_canonical_descriptions()+ schema_names = {s.name for s in self.source.get_schemas(_config(), team_id=self.team_id)}+ assert schema_names <= set(canonical)