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(data-warehouse): implement rki_covid import source (#72618)

Tom Owersf5c1334e96be
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 5e62cc5c8ad5..0d017af93790 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -455,6 +455,7 @@ the row lists both.
| retently | HTTP | requests | ✅ |
| revenuecat | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| rippling | HTTP | requests | ✅ |
+| rki_covid | HTTP | requests | ✅ |
| roark | HTTP | requests | ✅ |
| rocketlane | HTTP | requests | ✅ |
| rollbar | HTTP | requests | ✅ |
@@ -897,7 +898,6 @@ doesn't conflict with concurrent PRs.
- retently
- revolut_merchant
- ringcentral
-- rki_covid
- rocket_chat
- rocketlane
- rss
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rkicovid.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rkicovid.py
index 57d267308ea4..7eb50ddae806 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rkicovid.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rkicovid.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class RKICovidSourceConfig(config.Config):
- pass
+ history_days: int | None = config.value(converter=config.str_to_optional_int, default_factory=lambda: None)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/canonical_descriptions.py
new file mode 100644
index 000000000000..10077531177b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/canonical_descriptions.py
@@ -0,0 +1,151 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://api.corona-zahlen.org/docs/"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "germany": {
+ "description": "Current nationwide COVID-19 snapshot for Germany, replaced on every sync.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "cases": "Cumulative reported COVID-19 cases in Germany.",
+ "deaths": "Cumulative reported COVID-19 deaths in Germany.",
+ "recovered": "Cumulative recovered COVID-19 cases in Germany.",
+ "weekIncidence": "7-day incidence per 100,000 inhabitants.",
+ "casesPer100k": "Cumulative cases per 100,000 inhabitants.",
+ "casesPerWeek": "New cases reported in the last 7 days.",
+ "deathsPerWeek": "New deaths reported in the last 7 days.",
+ "delta": "Day-over-day change in cases, deaths, recovered, and week incidence.",
+ "r": "Reproduction (R) value estimates with their reference dates.",
+ "hospitalization": "Current 7-day hospitalization cases and incidence.",
+ "meta": "API metadata, including the last update timestamp of the underlying RKI data.",
+ },
+ },
+ "germany_age_groups": {
+ "description": "Nationwide cases, deaths, and hospitalization broken down by age group and sex.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "age_group": "Age band the row describes (e.g. A00-A04, A80+).",
+ "casesMale": "Cumulative cases among males in this age group.",
+ "casesFemale": "Cumulative cases among females in this age group.",
+ "deathsMale": "Cumulative deaths among males in this age group.",
+ "deathsFemale": "Cumulative deaths among females in this age group.",
+ "casesMalePer100k": "Cumulative cases among males per 100,000 inhabitants of this age group.",
+ "casesFemalePer100k": "Cumulative cases among females per 100,000 inhabitants of this age group.",
+ "deathsMalePer100k": "Cumulative deaths among males per 100,000 inhabitants of this age group.",
+ "deathsFemalePer100k": "Cumulative deaths among females per 100,000 inhabitants of this age group.",
+ "hospitalization": "Current 7-day hospitalization cases and incidence for this age group.",
+ },
+ },
+ "germany_history_cases": {
+ "description": "Daily new reported COVID-19 cases for Germany.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "date": "Reporting day.",
+ "cases": "New cases reported on this day.",
+ },
+ },
+ "germany_history_incidence": {
+ "description": "Daily 7-day incidence per 100,000 inhabitants for Germany.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "date": "Reporting day.",
+ "weekIncidence": "7-day incidence per 100,000 inhabitants on this day.",
+ },
+ },
+ "germany_history_deaths": {
+ "description": "Daily new reported COVID-19 deaths for Germany.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "date": "Reporting day.",
+ "deaths": "New deaths reported on this day.",
+ },
+ },
+ "germany_history_recovered": {
+ "description": "Daily newly recovered COVID-19 cases for Germany.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "date": "Reporting day.",
+ "recovered": "Cases newly counted as recovered on this day.",
+ },
+ },
+ "germany_history_frozen_incidence": {
+ "description": "Daily 7-day incidence for Germany as originally published on each day, without retroactive corrections.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "date": "Publication day.",
+ "weekIncidence": "7-day incidence per 100,000 inhabitants as published on this day.",
+ "dataSource": "Origin of the value (official RKI report or calculated from the daily RKI dump).",
+ },
+ },
+ "germany_history_hospitalization": {
+ "description": "Daily 7-day hospitalization figures for Germany, including reporting-delay adjusted values.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "date": "Reporting day.",
+ "cases7Days": "Hospitalized COVID-19 cases reported in the trailing 7 days.",
+ "incidence7Days": "7-day hospitalization incidence per 100,000 inhabitants.",
+ "fixedCases7Days": "7-day hospitalization cases as fixed after the reporting delay.",
+ "updatedCases7Days": "7-day hospitalization cases updated with late reports.",
+ "adjustedCases7Days": "Reporting-delay adjusted (nowcast) 7-day hospitalization cases.",
+ "adjustedLowerCases7Days": "Lower bound of the adjusted 7-day hospitalization cases.",
+ "adjustedUpperCases7Days": "Upper bound of the adjusted 7-day hospitalization cases.",
+ "fixedIncidence7Days": "7-day hospitalization incidence as fixed after the reporting delay.",
+ "updatedIncidence7Days": "7-day hospitalization incidence updated with late reports.",
+ "adjustedIncidence7Days": "Reporting-delay adjusted (nowcast) 7-day hospitalization incidence.",
+ "adjustedLowerIncidence7Days": "Lower bound of the adjusted 7-day hospitalization incidence.",
+ "adjustedUpperIncidence7Days": "Upper bound of the adjusted 7-day hospitalization incidence.",
+ },
+ },
+ "states": {
+ "description": "Current COVID-19 snapshot per German federal state (Bundesland).",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Numeric state identifier used by the RKI.",
+ "abbreviation": "Two-letter state abbreviation (e.g. BY for Bayern).",
+ "name": "State name.",
+ "population": "State population.",
+ "cases": "Cumulative reported cases in the state.",
+ "deaths": "Cumulative reported deaths in the state.",
+ "recovered": "Cumulative recovered cases in the state.",
+ "casesPerWeek": "New cases reported in the last 7 days.",
+ "deathsPerWeek": "New deaths reported in the last 7 days.",
+ "weekIncidence": "7-day incidence per 100,000 inhabitants.",
+ "casesPer100k": "Cumulative cases per 100,000 inhabitants.",
+ "delta": "Day-over-day change in cases, deaths, recovered, and week incidence.",
+ "hospitalization": "Current 7-day hospitalization cases and incidence for the state.",
+ },
+ },
+ "districts": {
+ "description": "Current COVID-19 snapshot per German district (Landkreis / kreisfreie Stadt).",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "ags": "Official municipality key (Allgemeiner Gemeindeschlüssel) identifying the district.",
+ "name": "District name.",
+ "county": "Full district label including its type (LK/SK prefix).",
+ "state": "Name of the federal state the district belongs to.",
+ "stateAbbreviation": "Two-letter abbreviation of the federal state.",
+ "population": "District population.",
+ "cases": "Cumulative reported cases in the district.",
+ "deaths": "Cumulative reported deaths in the district.",
+ "recovered": "Cumulative recovered cases in the district.",
+ "casesPerWeek": "New cases reported in the last 7 days.",
+ "deathsPerWeek": "New deaths reported in the last 7 days.",
+ "weekIncidence": "7-day incidence per 100,000 inhabitants.",
+ "casesPer100k": "Cumulative cases per 100,000 inhabitants.",
+ "delta": "Day-over-day change in cases, deaths, recovered, and week incidence.",
+ },
+ },
+ "testing_history": {
+ "description": "Weekly PCR testing figures for Germany.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "calendarWeek": "Calendar week the figures cover, formatted as WW/YYYY.",
+ "performedTests": "PCR tests performed in this calendar week.",
+ "positiveTests": "Positive PCR tests in this calendar week.",
+ "positivityRate": "Share of performed tests that were positive (0-1).",
+ "laboratoryCount": "Number of laboratories that reported figures for this week.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/rki_covid.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/rki_covid.py
new file mode 100644
index 000000000000..f1c238c91931
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/rki_covid.py
@@ -0,0 +1,156 @@
+from collections.abc import Iterator
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+
+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.rki_covid.settings import (
+ RKI_COVID_ENDPOINTS,
+ RKICovidEndpointConfig,
+)
+
+RKI_COVID_BASE_URL = "https://api.corona-zahlen.org"
+
+# Every dataset is bounded (the pandemic time series is a few thousand rows, districts ~400 rows),
+# so no history window cap is needed beyond the optional user-configured `history_days`.
+
+
+class RKICovidAPIError(Exception):
+ pass
+
+
+def build_url(config: RKICovidEndpointConfig, history_days: Optional[int]) -> str:
+ # History endpoints accept an optional `/:days` suffix that trims the returned window
+ # server-side (relative to today — not an absolute cursor, so tables stay full refresh).
+ if config.supports_days and history_days:
+ return f"{RKI_COVID_BASE_URL}{config.path}/{history_days}"
+ return f"{RKI_COVID_BASE_URL}{config.path}"
+
+
+def _fetch(session: requests.Session, url: str) -> dict[str, Any]:
+ # make_tracked_session already retries 429/5xx honoring Retry-After; no extra retry layer here.
+ response = session.get(url, timeout=60)
+ response.raise_for_status()
+
+ body = response.json()
+ if not isinstance(body, dict):
+ raise RKICovidAPIError("RKI COVID-19 API error [unexpected_response]: response was not a JSON object")
+
+ # The API signals some failures with HTTP 200 and an `error` envelope in the body.
+ if "error" in body:
+ raise RKICovidAPIError(f"RKI COVID-19 API error [error_response]: {body['error']}")
+
+ return body
+
+
+def _parse_snapshot(body: dict[str, Any], config: RKICovidEndpointConfig) -> Iterator[dict[str, Any]]:
+ yield body
+
+
+def _parse_dict_rows(body: dict[str, Any], config: RKICovidEndpointConfig) -> Iterator[dict[str, Any]]:
+ data = body.get("data")
+ if not isinstance(data, dict):
+ return
+ for value in data.values():
+ if isinstance(value, dict):
+ yield value
+
+
+def _parse_keyed_rows(body: dict[str, Any], config: RKICovidEndpointConfig) -> Iterator[dict[str, Any]]:
+ data = body.get("data")
+ if not isinstance(data, dict):
+ return
+ for key, value in data.items():
+ if isinstance(value, dict):
+ # The dict key (e.g. the age-group band) carries the row identity and is the primary key.
+ assert config.key_field is not None
+ yield {config.key_field: key, **value}
+
+
+def _parse_data_list(body: dict[str, Any], config: RKICovidEndpointConfig) -> Iterator[dict[str, Any]]:
+ data = body.get("data")
+ if not isinstance(data, list):
+ return
+ for row in data:
+ if isinstance(row, dict):
+ yield row
+
+
+def _parse_data_history(body: dict[str, Any], config: RKICovidEndpointConfig) -> Iterator[dict[str, Any]]:
+ data = body.get("data")
+ if not isinstance(data, dict):
+ return
+ history = data.get("history")
+ if not isinstance(history, list):
+ return
+ for row in history:
+ if isinstance(row, dict):
+ yield row
+
+
+_PARSERS = {
+ "snapshot": _parse_snapshot,
+ "dict_rows": _parse_dict_rows,
+ "keyed_rows": _parse_keyed_rows,
+ "data_list": _parse_data_list,
+ "data_history": _parse_data_history,
+}
+
+
+def get_rows(
+ endpoint: str,
+ history_days: Optional[int],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ config = RKI_COVID_ENDPOINTS[endpoint]
+ parser = _PARSERS[config.kind]
+ session = make_tracked_session()
+
+ body = _fetch(session, build_url(config, history_days))
+ rows = list(parser(body, config))
+ logger.debug(f"RKI COVID-19: fetched {len(rows)} rows for {endpoint}")
+ if rows:
+ yield rows
+
+
+def rki_covid_source(
+ endpoint: str,
+ history_days: Optional[int],
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ config = RKI_COVID_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(endpoint=endpoint, history_days=history_days, logger=logger),
+ 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,
+ )
+
+
+def validate_connection() -> bool:
+ """Confirm the public API is reachable by issuing one cheap probe request.
+
+ The API is unauthenticated, so this only verifies availability of the community-run service.
+ """
+ try:
+ session = make_tracked_session()
+ response = session.get(f"{RKI_COVID_BASE_URL}/germany", timeout=10)
+ except Exception:
+ return False
+
+ if response.status_code != 200:
+ return False
+
+ try:
+ body = response.json()
+ except ValueError:
+ return False
+
+ return isinstance(body, dict) and "error" not in body
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/settings.py
new file mode 100644
index 000000000000..26871c2d7fb3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/settings.py
@@ -0,0 +1,131 @@
+import dataclasses
+from typing import Literal, Optional
+
+# The RKI COVID-19 API (api.corona-zahlen.org) is a public, unauthenticated JSON wrapper over
+# published Robert Koch-Institut figures, maintained by Marlon Lückert. Every endpoint returns its
+# full dataset in a single response — no pagination and no server-side timestamp cursor (history
+# endpoints only take a relative `:days` window), so every table is full refresh only.
+#
+# Each endpoint returns a bespoke JSON shape, so endpoints are grouped by a `kind` that tells the
+# transport how to reshape the response into flat rows:
+# snapshot -> the response body is a single row (e.g. /germany)
+# dict_rows -> body["data"] is a dict whose values are self-describing rows (e.g. /states)
+# keyed_rows -> body["data"] is a dict whose keys carry the row identity and must be injected
+# into each row under `key_field` (e.g. /germany/age-groups)
+# data_list -> body["data"] is already a list of rows (e.g. /germany/history/cases)
+# data_history -> the rows live at body["data"]["history"] (e.g. /germany/history/frozen-incidence)
+ParseKind = Literal["snapshot", "dict_rows", "keyed_rows", "data_list", "data_history"]
+
+
+class RKICovidEndpointConfig:
+ name: str
+ path: str
+ kind: ParseKind
+ # Unique across the whole table. None for single-row snapshot tables that are replaced wholesale.
+ primary_keys: Optional[list[str]]
+ # Set for keyed_rows endpoints: the column the dict key is injected under.
+ key_field: Optional[str] = None
+ # A stable date column used for datetime partitioning. History rows are keyed by reporting day
+ # and never move to another day, so `date` is safe. None for snapshot tables.
+ partition_key: Optional[str] = None
+ # Whether the endpoint accepts the optional `/:days` path suffix to trim the returned history
+ # window server-side.
+ supports_days: bool = False
+ description: Optional[str] = None
+
+
+RKI_COVID_ENDPOINTS: dict[str, RKICovidEndpointConfig] = {
+ "germany": RKICovidEndpointConfig(
+ name="germany",
+ path="/germany",
+ kind="snapshot",
+ primary_keys=None,
+ description="Current nationwide COVID-19 snapshot for Germany: cumulative cases, deaths, recoveries, week incidence, R value, and hospitalization. One row, replaced on every sync.",
+ ),
+ "germany_age_groups": RKICovidEndpointConfig(
+ name="germany_age_groups",
+ path="/germany/age-groups",
+ kind="keyed_rows",
+ primary_keys=["age_group"],
+ key_field="age_group",
+ description="Nationwide cases, deaths, and hospitalization broken down by age group and sex. One row per age group. Full refresh.",
+ ),
+ "germany_history_cases": RKICovidEndpointConfig(
+ name="germany_history_cases",
+ path="/germany/history/cases",
+ kind="data_list",
+ primary_keys=["date"],
+ partition_key="date",
+ supports_days=True,
+ description="Daily new reported COVID-19 cases for Germany. One row per day. Full refresh.",
+ ),
+ "germany_history_incidence": RKICovidEndpointConfig(
+ name="germany_history_incidence",
+ path="/germany/history/incidence",
+ kind="data_list",
+ primary_keys=["date"],
+ partition_key="date",
+ supports_days=True,
+ description="Daily 7-day incidence per 100k inhabitants for Germany. One row per day. Full refresh.",
+ ),
+ "germany_history_deaths": RKICovidEndpointConfig(
+ name="germany_history_deaths",
+ path="/germany/history/deaths",
+ kind="data_list",
+ primary_keys=["date"],
+ partition_key="date",
+ supports_days=True,
+ description="Daily new reported COVID-19 deaths for Germany. One row per day. Full refresh.",
+ ),
+ "germany_history_recovered": RKICovidEndpointConfig(
+ name="germany_history_recovered",
+ path="/germany/history/recovered",
+ kind="data_list",
+ primary_keys=["date"],
+ partition_key="date",
+ supports_days=True,
+ description="Daily newly recovered COVID-19 cases for Germany. One row per day. Full refresh.",
+ ),
+ "germany_history_frozen_incidence": RKICovidEndpointConfig(
+ name="germany_history_frozen_incidence",
+ path="/germany/history/frozen-incidence",
+ kind="data_history",
+ primary_keys=["date"],
+ partition_key="date",
+ supports_days=True,
+ description="Daily 7-day incidence for Germany as originally published (not retroactively corrected). One row per day. Full refresh.",
+ ),
+ "germany_history_hospitalization": RKICovidEndpointConfig(
+ name="germany_history_hospitalization",
+ path="/germany/history/hospitalization",
+ kind="data_list",
+ primary_keys=["date"],
+ partition_key="date",
+ supports_days=True,
+ description="Daily 7-day hospitalization cases and incidence for Germany, including reporting-delay adjusted values. One row per day. Full refresh.",
+ ),
+ "states": RKICovidEndpointConfig(
+ name="states",
+ path="/states",
+ kind="dict_rows",
+ primary_keys=["abbreviation"],
+ description="Current COVID-19 snapshot per German federal state (Bundesland): cases, deaths, recoveries, week incidence, and hospitalization. One row per state. Full refresh.",
+ ),
+ "districts": RKICovidEndpointConfig(
+ name="districts",
+ path="/districts",
+ kind="dict_rows",
+ primary_keys=["ags"],
+ description="Current COVID-19 snapshot per German district (Landkreis), keyed by the official municipality key (AGS). One row per district. Full refresh.",
+ ),
+ "testing_history": RKICovidEndpointConfig(
+ name="testing_history",
+ path="/testing/history",
+ kind="data_history",
+ primary_keys=["calendarWeek"],
+ description="Weekly PCR testing figures for Germany: performed tests, positive tests, positivity rate, and reporting laboratories. One row per calendar week. Full refresh.",
+ ),
+}
+
+ENDPOINTS = tuple(RKI_COVID_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/source.py
index 2db2458b10c9..4693859ec063 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/source.py
@@ -1,32 +1,145 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
+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, SimpleSource
+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.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.rkicovid import (
RKICovidSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rki_covid.rki_covid import (
+ rki_covid_source,
+ validate_connection,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rki_covid.settings import RKI_COVID_ENDPOINTS
from products.warehouse_sources.backend.types import ExternalDataSourceType
+def validate_history_days(history_days: Optional[int]) -> str | None:
+ if history_days is not None and history_days < 1:
+ return "History window (days) must be a positive number, or left empty for the full history"
+ return None
+
+
@SourceRegistry.register
class RKICovidSource(SimpleSource[RKICovidSourceConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://api.corona-zahlen.org/docs/"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.RKICOVID
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # The API is community-maintained; a 404 means the endpoint was moved or removed
+ # upstream, which retrying can never fix.
+ "404 Client Error: Not Found for url: https://api.corona-zahlen.org": "The RKI COVID-19 API no longer serves this endpoint. The API is community-maintained and may have changed; check https://api.corona-zahlen.org/docs/ for its current status.",
+ "RKI COVID-19 API error [unexpected_response]": "The RKI COVID-19 API returned an unexpected response. The API is community-maintained; check https://api.corona-zahlen.org/docs/ for its current status.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.rki_covid.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: RKICovidSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # The API has no server-side timestamp cursor (history endpoints only take a relative
+ # `:days` window), so every table is full refresh only.
+ schemas = [
+ SourceSchema(
+ name=endpoint.name,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ detected_primary_keys=endpoint.primary_keys,
+ description=endpoint.description,
+ )
+ for endpoint in RKI_COVID_ENDPOINTS.values()
+ ]
+
+ 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: RKICovidSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ days_error = validate_history_days(config.history_days)
+ if days_error:
+ return False, days_error
+
+ if validate_connection():
+ return True, None
+
+ return (
+ False,
+ "The RKI COVID-19 API (api.corona-zahlen.org) is not reachable right now. It's a public community-run service; please try again later.",
+ )
+
+ def source_for_pipeline(self, config: RKICovidSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ days_error = validate_history_days(config.history_days)
+ if days_error:
+ raise ValueError(f"RKI COVID-19 source misconfigured: {days_error}")
+
+ return rki_covid_source(
+ endpoint=inputs.schema_name,
+ history_days=config.history_days,
+ logger=inputs.logger,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.RKI_COVID,
category=DataWarehouseSourceCategory.ANALYTICS,
- label="RKI Covid",
+ label="RKI COVID-19",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["covid", "corona", "coronavirus", "rki", "germany", "public health"],
+ caption="""Pull German COVID-19 statistics (nationwide, per state, and per district) into the PostHog Data warehouse from the public RKI COVID-19 API at [api.corona-zahlen.org](https://api.corona-zahlen.org).
+
+No credentials are needed. The API is a community-maintained wrapper (by Marlon Lückert) over published Robert Koch-Institut figures, not an official RKI service.
+
+Optionally limit the history tables to the last N days; leave empty to sync the full history.""",
iconPath="/static/services/rki_covid.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/rki-covid",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="history_days",
+ label="History window (days)",
+ type=SourceFieldInputConfigType.NUMBER,
+ required=False,
+ placeholder="Leave empty for full history",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/tests/test_rki_covid.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/tests/test_rki_covid.py
new file mode 100644
index 000000000000..03ada6053cf3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/tests/test_rki_covid.py
@@ -0,0 +1,222 @@
+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.rki_covid.rki_covid import (
+ RKICovidAPIError,
+ _fetch,
+ build_url,
+ get_rows,
+ rki_covid_source,
+ validate_connection,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rki_covid.settings import RKI_COVID_ENDPOINTS
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.rki_covid.rki_covid"
+
+
+def _response(*, body: Any = None, status: int = 200) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status
+ response.json.return_value = body if body is not None else {}
+ if status >= 400:
+ response.raise_for_status.side_effect = requests.HTTPError(f"{status} Client Error", response=response)
+ else:
+ response.raise_for_status.return_value = None
+ return response
+
+
+def _session_returning(response: MagicMock) -> MagicMock:
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+
+def _collect_rows(batches: Any) -> list[dict]:
+ rows: list[dict] = []
+ for batch in batches:
+ rows.extend(batch)
+ return rows
+
+
+class TestRKICovid:
+ @parameterized.expand(
+ [
+ (
+ "history_with_days",
+ "germany_history_cases",
+ 30,
+ "https://api.corona-zahlen.org/germany/history/cases/30",
+ ),
+ (
+ "history_without_days",
+ "germany_history_cases",
+ None,
+ "https://api.corona-zahlen.org/germany/history/cases",
+ ),
+ # Non-history endpoints must never grow a days suffix, even when the user configured one.
+ ("snapshot_ignores_days", "states", 30, "https://api.corona-zahlen.org/states"),
+ ]
+ )
+ def test_build_url_applies_days_only_where_supported(
+ self, _name: str, endpoint: str, days: int | None, expected: str
+ ) -> None:
+ assert build_url(RKI_COVID_ENDPOINTS[endpoint], days) == expected
+
+ def test_fetch_raises_on_error_envelope(self) -> None:
+ # The API signals some failures with HTTP 200 and an `error` body.
+ session = _session_returning(_response(body={"error": {"message": "wrong route"}}))
+ with pytest.raises(RKICovidAPIError, match="error_response"):
+ _fetch(session, "https://api.corona-zahlen.org/germany")
+
+ def test_fetch_raises_on_non_dict_body(self) -> None:
+ session = _session_returning(_response(body=["unexpected"]))
+ with pytest.raises(RKICovidAPIError, match="unexpected_response"):
+ _fetch(session, "https://api.corona-zahlen.org/germany")
+
+ def test_fetch_raises_on_http_error(self) -> None:
+ session = _session_returning(_response(status=404))
+ with pytest.raises(requests.HTTPError):
+ _fetch(session, "https://api.corona-zahlen.org/germany")
+
+ def test_germany_snapshot_yields_single_row(self) -> None:
+ body = {"cases": 100, "deaths": 5, "meta": {"lastUpdate": "2026-07-21T05:35:57.000Z"}}
+ with patch(f"{MODULE}.make_tracked_session", return_value=_session_returning(_response(body=body))):
+ rows = _collect_rows(get_rows("germany", None, MagicMock()))
+ assert rows == [body]
+
+ def test_age_groups_inject_dict_key_as_age_group_column(self) -> None:
+ # The age band only exists as the dict key; dropping it would leave rows with no identity.
+ body = {
+ "data": {
+ "A00-A04": {"casesMale": 1, "casesFemale": 2},
+ "A80+": {"casesMale": 3, "casesFemale": 4},
+ },
+ "meta": {},
+ }
+ with patch(f"{MODULE}.make_tracked_session", return_value=_session_returning(_response(body=body))):
+ rows = _collect_rows(get_rows("germany_age_groups", None, MagicMock()))
+ assert rows == [
+ {"age_group": "A00-A04", "casesMale": 1, "casesFemale": 2},
+ {"age_group": "A80+", "casesMale": 3, "casesFemale": 4},
+ ]
+
+ def test_states_yield_one_row_per_dict_value(self) -> None:
+ body = {
+ "data": {
+ "SH": {"id": 1, "abbreviation": "SH", "name": "Schleswig-Holstein", "cases": 10},
+ "HH": {"id": 2, "abbreviation": "HH", "name": "Hamburg", "cases": 20},
+ },
+ "meta": {},
+ }
+ with patch(f"{MODULE}.make_tracked_session", return_value=_session_returning(_response(body=body))):
+ rows = _collect_rows(get_rows("states", None, MagicMock()))
+ assert [r["abbreviation"] for r in rows] == ["SH", "HH"]
+
+ def test_history_list_yields_data_rows(self) -> None:
+ body = {
+ "data": [
+ {"cases": 0, "date": "2026-07-18T00:00:00.000Z"},
+ {"cases": 7, "date": "2026-07-20T00:00:00.000Z"},
+ ],
+ "meta": {},
+ }
+ with patch(f"{MODULE}.make_tracked_session", return_value=_session_returning(_response(body=body))):
+ rows = _collect_rows(get_rows("germany_history_cases", None, MagicMock()))
+ assert rows == body["data"]
+
+ @parameterized.expand(
+ [
+ (
+ "frozen_incidence",
+ "germany_history_frozen_incidence",
+ {
+ "data": {
+ "abbreviation": "Bund",
+ "name": "Bundesgebiet",
+ "history": [{"date": "2026-07-19T00:00:00.000Z", "weekIncidence": 0.07}],
+ },
+ "meta": {},
+ },
+ [{"date": "2026-07-19T00:00:00.000Z", "weekIncidence": 0.07}],
+ ),
+ (
+ "testing_history",
+ "testing_history",
+ {
+ "data": {"history": [{"calendarWeek": "10/2020", "performedTests": 69493}]},
+ "meta": {},
+ },
+ [{"calendarWeek": "10/2020", "performedTests": 69493}],
+ ),
+ ]
+ )
+ def test_nested_history_rows_are_unwrapped(
+ self, _name: str, endpoint: str, body: dict, expected: list[dict]
+ ) -> None:
+ with patch(f"{MODULE}.make_tracked_session", return_value=_session_returning(_response(body=body))):
+ rows = _collect_rows(get_rows(endpoint, None, MagicMock()))
+ assert rows == expected
+
+ @parameterized.expand(
+ [
+ ("missing_data", "states", {"meta": {}}),
+ ("wrong_data_type", "germany_history_cases", {"data": {"unexpected": "shape"}, "meta": {}}),
+ ("missing_history", "testing_history", {"data": {}, "meta": {}}),
+ ]
+ )
+ def test_malformed_data_yields_no_rows_instead_of_crashing(self, _name: str, endpoint: str, body: dict) -> None:
+ with patch(f"{MODULE}.make_tracked_session", return_value=_session_returning(_response(body=body))):
+ assert _collect_rows(get_rows(endpoint, None, MagicMock())) == []
+
+ def test_get_rows_requests_days_trimmed_url(self) -> None:
+ session = _session_returning(_response(body={"data": [], "meta": {}}))
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ _collect_rows(get_rows("germany_history_cases", 90, MagicMock()))
+ assert session.get.call_args.args[0] == "https://api.corona-zahlen.org/germany/history/cases/90"
+
+ @parameterized.expand(
+ [
+ ("germany", None, None),
+ ("germany_age_groups", ["age_group"], None),
+ ("germany_history_cases", ["date"], "date"),
+ ("germany_history_hospitalization", ["date"], "date"),
+ ("states", ["abbreviation"], None),
+ ("districts", ["ags"], None),
+ ("testing_history", ["calendarWeek"], None),
+ ]
+ )
+ def test_rki_covid_source_maps_primary_keys_and_partitioning(
+ self, endpoint: str, expected_keys: list[str] | None, partition_key: str | None
+ ) -> None:
+ response = rki_covid_source(endpoint, None, MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == expected_keys
+ if partition_key is None:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+ else:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+
+ @parameterized.expand(
+ [
+ ("reachable", 200, {"cases": 1}, True),
+ ("error_envelope", 200, {"error": {"message": "boom"}}, False),
+ ("server_error", 500, {}, False),
+ ]
+ )
+ def test_validate_connection(self, _name: str, status: int, body: dict, expected: bool) -> None:
+ session = _session_returning(_response(body=body, status=status))
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ assert validate_connection() is expected
+
+ def test_validate_connection_false_on_network_error(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ assert validate_connection() is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/tests/test_rki_covid_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/tests/test_rki_covid_source.py
new file mode 100644
index 000000000000..50100ee8cbce
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rki_covid/tests/test_rki_covid_source.py
@@ -0,0 +1,118 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.rki_covid.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.rki_covid.source import RKICovidSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.rki_covid.source"
+
+
+def _make_config(history_days: int | None = None) -> Any:
+ config = MagicMock()
+ config.history_days = history_days
+ return config
+
+
+class TestRKICovidSource:
+ def test_source_type(self) -> None:
+ assert RKICovidSource().source_type == ExternalDataSourceType.RKICOVID
+
+ def test_source_config_is_released_alpha(self) -> None:
+ config = RKICovidSource().get_source_config
+ # A finished source must stay visible: unreleasedSource hides it from every user.
+ assert not config.unreleasedSource
+ assert config.releaseStatus == "alpha"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/rki-covid"
+
+ def test_source_config_history_days_field_is_optional(self) -> None:
+ config = RKICovidSource().get_source_config
+ assert [f.name for f in config.fields] == ["history_days"]
+ field = config.fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.type == "number"
+ assert field.required is False
+ assert field.secret is False
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static endpoint catalog with no I/O, so the public docs can render tables.
+ assert RKICovidSource.lists_tables_without_credentials is True
+
+ def test_get_schemas_returns_every_endpoint_as_full_refresh(self) -> None:
+ schemas = RKICovidSource().get_schemas(_make_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # The API has no server-side timestamp cursor, so nothing supports incremental.
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_exposes_primary_keys(self) -> None:
+ schemas = {s.name: s for s in RKICovidSource().get_schemas(_make_config(), team_id=1)}
+ assert schemas["germany"].detected_primary_keys is None
+ assert schemas["germany_age_groups"].detected_primary_keys == ["age_group"]
+ assert schemas["states"].detected_primary_keys == ["abbreviation"]
+ assert schemas["districts"].detected_primary_keys == ["ags"]
+ assert schemas["germany_history_cases"].detected_primary_keys == ["date"]
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = RKICovidSource().get_schemas(_make_config(), team_id=1, names=["germany", "states"])
+ assert {s.name for s in schemas} == {"germany", "states"}
+
+ @parameterized.expand(
+ [
+ ("no_days_reachable", None, True, True),
+ ("valid_days_reachable", 90, True, True),
+ ("unreachable", None, False, False),
+ ]
+ )
+ def test_validate_credentials(self, _name: str, days: int | None, probe_result: bool, expected_ok: bool) -> None:
+ with patch(f"{MODULE}.validate_connection", return_value=probe_result):
+ ok, message = RKICovidSource().validate_credentials(_make_config(days), team_id=1)
+ assert ok is expected_ok
+ assert (message is None) is expected_ok
+
+ def test_validate_credentials_rejects_invalid_days_without_probing(self) -> None:
+ with patch(f"{MODULE}.validate_connection") as probe:
+ ok, message = RKICovidSource().validate_credentials(_make_config(0), team_id=1)
+ assert ok is False
+ assert message is not None and "History window" in message
+ probe.assert_not_called()
+
+ def test_source_for_pipeline_plumbs_endpoint_and_history_days(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "germany_history_cases"
+ inputs.logger = MagicMock()
+ with patch(f"{MODULE}.rki_covid_source") as source_fn:
+ RKICovidSource().source_for_pipeline(_make_config(30), inputs)
+ source_fn.assert_called_once()
+ kwargs = source_fn.call_args.kwargs
+ assert kwargs["endpoint"] == "germany_history_cases"
+ assert kwargs["history_days"] == 30
+
+ def test_source_for_pipeline_rejects_invalid_history_days(self) -> None:
+ # A previously-saved bad config must fail the run loudly instead of syncing a wrong window.
+ inputs = MagicMock()
+ inputs.schema_name = "germany_history_cases"
+ inputs.logger = MagicMock()
+ with patch(f"{MODULE}.rki_covid_source") as source_fn:
+ with pytest.raises(ValueError, match="History window"):
+ RKICovidSource().source_for_pipeline(_make_config(-1), inputs)
+ source_fn.assert_not_called()
+
+ def test_non_retryable_errors_cover_endpoint_drift(self) -> None:
+ errors = RKICovidSource().get_non_retryable_errors()
+ assert "404 Client Error: Not Found for url: https://api.corona-zahlen.org" in errors
+ assert "RKI COVID-19 API error [unexpected_response]" in errors
+
+ def test_canonical_descriptions_keyed_by_endpoint(self) -> None:
+ descriptions = RKICovidSource().get_canonical_descriptions()
+ # Every documented entry must map to a real endpoint or the docs render orphaned tables.
+ assert set(descriptions.keys()) <= set(ENDPOINTS)
+ assert "germany" in descriptions
+ assert "districts" in descriptions