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): add 4 missing tables to the Serpstat source (#123781)

Tom Owers0c045715a8ec
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index a7495df8a75e..bc71dfaa68be 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -10826,10 +10826,10 @@ Today (5): `project_keywords`, `project_positions`, `project_regions`, `project_
Diffed against: <https://raw.githubusercontent.com/SerpstatGlobal/serpstat-mcp-server-java/main/doc/openapi_spec/Serpstat-Domain-Analysis-API.json>
-- [ ] `getDomainKeywords (POST /v4/, JSON-RPC SerpstatDomainProcedure.getDomainKeywords)` — analyze organic keywords, ranking URLs, search volumes, and traffic beyond the manually tracked project keywords (high)
-- [ ] `getDomainsInfo (POST /v4/, JSON-RPC SerpstatDomainProcedure.getDomainsInfo)` — compare headline domain visibility, estimated traffic, and organic keyword counts (high)
-- [ ] `getNewBacklinks (POST /v4/, JSON-RPC SerpstatBacklinksProcedure.getNewBacklinks)` — analyze active backlinks, source pages, and link acquisition (high)
-- [ ] `getDomainsHistory (POST /v4/, JSON-RPC SerpstatDomainProcedure.getDomainsHistory)` — track historical visibility, keyword counts, and traffic changes (medium)
+- [x] `getDomainKeywords (POST /v4/, JSON-RPC SerpstatDomainProcedure.getDomainKeywords)` — analyze organic keywords, ranking URLs, search volumes, and traffic beyond the manually tracked project keywords (high)
+- [x] `getDomainsInfo (POST /v4/, JSON-RPC SerpstatDomainProcedure.getDomainsInfo)` — compare headline domain visibility, estimated traffic, and organic keyword counts (high)
+- [x] `getNewBacklinks (POST /v4/, JSON-RPC SerpstatBacklinksProcedure.getNewBacklinks)` — analyze active backlinks, source pages, and link acquisition (high)
+- [x] `getDomainsHistory (POST /v4/, JSON-RPC SerpstatDomainProcedure.getDomainsHistory)` — track historical visibility, keyword counts, and traffic changes (medium)
- [ ] `getRefDomains (POST /v4/, JSON-RPC SerpstatBacklinksProcedure.getRefDomains)` — compare referring domains and the strength of the domain link profile (medium)
- [ ] `getLostBacklinks (POST /v4/, JSON-RPC SerpstatBacklinksProcedure.getLostBacklinks)` — identify lost links and measure changes in link retention (medium)
- [ ] `getCompetitors (POST /v4/, JSON-RPC SerpstatDomainProcedure.getCompetitors)` — compare competing domains and shared organic keywords (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/serpstat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/serpstat.py
index dd58018d1567..3a47d5a21d9b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/serpstat.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/serpstat.py
@@ -9,3 +9,5 @@ class SerpstatSourceConfig(config.Config):
api_key: str
project_id: str
project_region_id: str
+ domain: str | None = None
+ search_engine: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/canonical_descriptions.py
index 415dfc06ac3f..6b882b6c2f41 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/canonical_descriptions.py
@@ -1,12 +1,12 @@
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.settings import DOCS_BASE, ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.settings import ENDPOINTS
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"projects": {
"description": "Projects available to the Serpstat account.",
- "docs_url": DOCS_BASE + ENDPOINTS["projects"].docs_slug,
+ "docs_url": ENDPOINTS["projects"].docs_url,
"columns": {
"project_id": "The project identifier.",
"project_name": "The project name.",
@@ -18,7 +18,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
},
"project_keywords": {
"description": "Keywords configured for the selected Rank Tracker project.",
- "docs_url": DOCS_BASE + ENDPOINTS["project_keywords"].docs_slug,
+ "docs_url": ENDPOINTS["project_keywords"].docs_url,
"columns": {
"project_id": "The configured project identifier.",
"id": "The internal identifier for the project keyword.",
@@ -32,7 +32,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
},
"project_regions": {
"description": "Search regions and their status for the selected Rank Tracker project.",
- "docs_url": DOCS_BASE + ENDPOINTS["project_regions"].docs_slug,
+ "docs_url": ENDPOINTS["project_regions"].docs_url,
"columns": {
"project_id": "The configured project identifier.",
"id": "The project region identifier.",
@@ -48,7 +48,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
},
"project_tags": {
"description": "Tags created in the selected Rank Tracker project.",
- "docs_url": DOCS_BASE + ENDPOINTS["project_tags"].docs_slug,
+ "docs_url": ENDPOINTS["project_tags"].docs_url,
"columns": {
"project_id": "The configured project identifier.",
"tag_uuid": "The unique tag identifier.",
@@ -57,7 +57,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
},
"project_positions": {
"description": "Keyword positions for the configured project region during the last seven days, grouped by keyword.",
- "docs_url": DOCS_BASE + ENDPOINTS["project_positions"].docs_slug,
+ "docs_url": ENDPOINTS["project_positions"].docs_url,
"columns": {
"project_id": "The configured project identifier.",
"keyword_id": "The keyword identifier.",
@@ -67,4 +67,81 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"tags": "Tag names associated with the keyword.",
},
},
+ "domain_info": {
+ "description": "Summary SEO metrics for the configured domain in the selected search engine database.",
+ "docs_url": ENDPOINTS["domain_info"].docs_url,
+ "columns": {
+ "domain": "The domain name.",
+ "visible": "The site visibility.",
+ "keywords": "The number of keywords found in the selected search engine.",
+ "traff": "The estimated search traffic, based on keyword positions and search volume.",
+ "visible_dynamic": "The change in visibility since the last monitoring.",
+ "keywords_dynamic": "The change in the number of keywords since the last monitoring.",
+ "traff_dynamic": "The change in traffic since the last monitoring.",
+ "ads_dynamic": "The change in the number of PPC ads.",
+ "new_keywords": "The number of new keywords for the domain since the last monitoring.",
+ "out_keywords": "The number of keywords that the domain lost since the last monitoring.",
+ "rised_keywords": "The number of keywords with improved positions since the last monitoring.",
+ "down_keywords": "The number of keywords with dropped positions since the last monitoring.",
+ "ad_keywords": "The number of keywords in PPC.",
+ "ads": "The number of PPC ads.",
+ "prev_date": "The date of the previous check.",
+ },
+ },
+ "domain_history": {
+ "description": "Historical keyword counts, visibility, and traffic for the configured domain.",
+ "docs_url": ENDPOINTS["domain_history"].docs_url,
+ "columns": {
+ "domain": "The domain name.",
+ "date": "The date when Serpstat recorded the metrics.",
+ "keywords": "The number of keywords seen in search results for the selected search engine.",
+ "traff": "The estimated search traffic, based on keyword positions and search volume.",
+ "visible": "The site visibility.",
+ "visible_static": "The static visibility.",
+ "new_keywords": "The number of new keywords in the period.",
+ "out_keywords": "The number of lost keywords in the period.",
+ "rised_keywords": "The number of keywords with improved positions in the period.",
+ "down_keywords": "The number of keywords with dropped positions in the period.",
+ "ad_keywords": "The number of keywords in PPC.",
+ "ads": "The number of PPC ads.",
+ },
+ },
+ "domain_keywords": {
+ "description": "Organic keywords for which the configured domain ranks in the Google top 100.",
+ "docs_url": ENDPOINTS["domain_keywords"].docs_url,
+ "columns": {
+ "domain": "The analyzed domain.",
+ "subdomain": "The subdomain that appears in search results for the keyword.",
+ "keyword": "The keyword for which the domain ranks.",
+ "keyword_length": "The number of words in the keyword.",
+ "url": "The URL that appears in the search result for the keyword.",
+ "position": "The position of the domain for the keyword.",
+ "types": "Special elements shown in the search results page, for example video or map.",
+ "found_results": "The number of results found for the keyword.",
+ "cost": "The cost per click, in US dollars.",
+ "concurrency": "The keyword competition in PPC, from 0 to 100.",
+ "region_queries_count": "The search volume in the selected region.",
+ "region_queries_count_wide": "The search volume in broad match in the selected database.",
+ "geo_names": "Place names found in the keyword.",
+ "traff": "The approximate traffic for the keyword, based on its volume and position.",
+ "difficulty": "How difficult it is to rank in the organic top 10 for the keyword, from 0 to 100.",
+ "dynamic": "The change in position for the keyword.",
+ "intents": "The intents of the keyword.",
+ },
+ },
+ "backlinks": {
+ "description": "Active backlinks to the configured domain and its subdomains, most recently found first.",
+ "docs_url": ENDPOINTS["backlinks"].docs_url,
+ "columns": {
+ "url_from": "The page that contains the link.",
+ "url_to": "The target page of the link.",
+ "nofollow": "The link attributes, for example follow, nofollow, UGC, or sponsored.",
+ "link_type": "The link type, for example href, image, or redirect.",
+ "links_ext": "The number of external links on the referring page.",
+ "link_text": "The link anchor text.",
+ "first_seen": "The date when Serpstat first found the link.",
+ "last_visited": "The date and time of the last crawl.",
+ "domain_rank": "The Serpstat Domain Rank (SDR) of the referring domain.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/serpstat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/serpstat.py
index 60df4f81216a..163b241d8253 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/serpstat.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/serpstat.py
@@ -20,6 +20,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
SerpstatSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.settings import (
+ DEFAULT_SEARCH_ENGINE,
+ DOMAIN_ERROR,
+ DOMAIN_HISTORY_PAGE_SIZE,
+ DOMAIN_RESPONSE_ACTIONS,
ENDPOINTS,
MAX_PAGES,
PAGE_SIZE,
@@ -38,6 +42,10 @@ class SerpstatResumeConfig:
class SerpstatPaginator(PageNumberPaginator):
+ def __init__(self, *, page_size: int | None = None, **kwargs: Any) -> None:
+ super().__init__(**kwargs)
+ self.page_size = page_size
+
def init_request(self, request: Request) -> None:
# JSON-RPC puts pagination inside params, rather than at the body root.
request.json["params"]["page"] = self.page
@@ -48,10 +56,17 @@ class SerpstatPaginator(PageNumberPaginator):
def update_state(self, response: Response, data: list[Any] | None = None) -> None:
super().update_state(response, data)
+ if self.page_size is not None and data is not None and len(data) < self.page_size:
+ self._has_next_page = False
if self.maximum_page == MAX_PAGES and self.page > MAX_PAGES and data:
logger.info("serpstat_page_cap_reached", maximum_page=self.maximum_page)
+def normalize_domain(value: str | None) -> str:
+ domain = (value or "").strip().lower().removeprefix("https://").removeprefix("http://")
+ return domain.split("/", 1)[0]
+
+
def serpstat_resource(
config: SerpstatSourceConfig,
endpoint: str,
@@ -60,6 +75,7 @@ def serpstat_resource(
api_version: str,
manager: ResumableSourceManager[SerpstatResumeConfig] | None = None,
credential_check: bool = False,
+ date_from: str | None = None,
) -> Resource:
settings = ENDPOINTS[endpoint]
resume = manager.load_state() if manager is not None and manager.can_resume() else None
@@ -67,7 +83,14 @@ def serpstat_resource(
params: dict[str, Any] = {}
if settings.project_param:
params[settings.project_param] = int(config.project_id)
- if settings.total_pages_path:
+ if settings.domain_param:
+ domain = normalize_domain(config.domain)
+ if not domain:
+ raise ValueError(DOMAIN_ERROR)
+ params[settings.domain_param] = [domain] if settings.domain_param == "domains" else domain
+ if settings.search_engine:
+ params["se"] = (config.search_engine or "").strip() or DEFAULT_SEARCH_ENGINE
+ if settings.paginated:
params[settings.size_param] = 20 if credential_check else PAGE_SIZE
if endpoint in ("project_keywords", "project_positions"):
params.update(sort="added", order="asc")
@@ -77,6 +100,12 @@ def serpstat_resource(
date_from=(date.fromisoformat(date_to) - timedelta(days=POSITION_HISTORY_DAYS - 1)).isoformat(),
date_to=date_to,
)
+ if endpoint == "domain_history":
+ params.update(during_all_time=True, sort={"date": "asc"}, size=DOMAIN_HISTORY_PAGE_SIZE)
+ if date_from:
+ params["filters"] = {"date_from": date_from}
+ if endpoint == "backlinks":
+ params.update(searchType="domain_with_subdomains", sort="add", order="desc")
rest_config: RESTAPIConfig = {
"client": {
@@ -102,10 +131,11 @@ def serpstat_resource(
base_page=1,
total_path=settings.total_pages_path,
maximum_page=1 if credential_check else MAX_PAGES,
+ page_size=PAGE_SIZE if settings.stop_on_short_page else None,
)
- if settings.total_pages_path
+ if settings.paginated
else "single_page",
- "response_actions": RESPONSE_ACTIONS,
+ "response_actions": DOMAIN_RESPONSE_ACTIONS if settings.domain_param else RESPONSE_ACTIONS,
},
}
],
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/settings.py
index ef30a0da6a05..581458f9cc49 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/settings.py
@@ -1,31 +1,50 @@
+from dataclasses import field
+
from posthog.dataclasses import frozen
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseAction
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
PAGE_SIZE = 100
MAX_PAGES = 5
POSITION_HISTORY_DAYS = 7
REQUEST_INTERVAL_SECONDS = 1.0
DOCS_BASE = "https://api-docs.serpstat.com/docs/serpstat-public-api/"
+SPEC_BASE = "https://raw.githubusercontent.com/SerpstatGlobal/serpstat-mcp-server-java/main/doc/openapi_spec/"
+DOMAIN_ANALYSIS_DOCS_URL = SPEC_BASE + "Serpstat-Domain-Analysis-API.json"
+BACKLINKS_DOCS_URL = SPEC_BASE + "Serpstat-Backlinks-API.json"
+DEFAULT_SEARCH_ENGINE = "g_us"
+# getDomainsHistory has no page parameter, so one request at the maximum size reads the whole history.
+DOMAIN_HISTORY_PAGE_SIZE = 1000
@frozen
class SerpstatEndpoint:
method: str
primary_keys: tuple[str, ...]
- docs_slug: str
+ docs_url: str
selector: str = "result.data"
project_param: str | None = "project_id"
+ domain_param: str | None = None
+ search_engine: bool = False
total_pages_path: str | None = None
+ # For methods that return a row total instead of a page total: a short page is the last page.
+ stop_on_short_page: bool = False
size_param: str = "size"
partition_key: str | None = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+
+ @property
+ def paginated(self) -> bool:
+ return self.total_pages_path is not None or self.stop_on_short_page
ENDPOINTS = {
"projects": SerpstatEndpoint(
method="ProjectProcedure.getProjects",
primary_keys=("project_id",),
- docs_slug="3ezca25cnkqw5-get-projects",
+ docs_url=DOCS_BASE + "3ezca25cnkqw5-get-projects",
project_param=None,
total_pages_path="result.summary_info.page_total",
partition_key="created_at",
@@ -33,35 +52,71 @@ ENDPOINTS = {
"project_keywords": SerpstatEndpoint(
method="RtApiProcedure.getProjectKeywords",
primary_keys=("project_id", "id"),
- docs_slug="c0a938de406c8-get-project-keywords",
+ docs_url=DOCS_BASE + "c0a938de406c8-get-project-keywords",
total_pages_path="result.summary_info.pages_count",
partition_key="added",
),
"project_regions": SerpstatEndpoint(
method="RtApiSearchEngineProcedure.getProjectRegions",
primary_keys=("project_id", "id"),
- docs_slug="f57863602271e-get-project-regions",
+ docs_url=DOCS_BASE + "f57863602271e-get-project-regions",
selector="result.regions",
project_param="projectId",
),
"project_tags": SerpstatEndpoint(
method="RtApiProcedure.getProjectTags",
primary_keys=("project_id", "tag_uuid"),
- docs_slug="233a6b97f4943-get-project-tags",
+ docs_url=DOCS_BASE + "233a6b97f4943-get-project-tags",
),
"project_positions": SerpstatEndpoint(
method="RtApiProcedure.getProjectPositions",
primary_keys=("project_id", "keyword_id"),
- docs_slug="e78a1e5708d44-get-project-positions",
+ docs_url=DOCS_BASE + "e78a1e5708d44-get-project-positions",
total_pages_path="result.summary_info.pages_count",
size_param="page_size",
partition_key="added",
),
+ "domain_info": SerpstatEndpoint(
+ method="SerpstatDomainProcedure.getDomainsInfo",
+ primary_keys=("domain",),
+ docs_url=DOMAIN_ANALYSIS_DOCS_URL,
+ project_param=None,
+ domain_param="domains",
+ search_engine=True,
+ ),
+ "domain_history": SerpstatEndpoint(
+ method="SerpstatDomainProcedure.getDomainsHistory",
+ primary_keys=("domain", "date"),
+ docs_url=DOMAIN_ANALYSIS_DOCS_URL,
+ project_param=None,
+ domain_param="domain",
+ search_engine=True,
+ partition_key="date",
+ incremental_fields=[incremental_field("date", IncrementalFieldType.Date)],
+ ),
+ "domain_keywords": SerpstatEndpoint(
+ method="SerpstatDomainProcedure.getDomainKeywords",
+ primary_keys=("domain", "keyword", "url"),
+ docs_url=DOMAIN_ANALYSIS_DOCS_URL,
+ project_param=None,
+ domain_param="domain",
+ search_engine=True,
+ stop_on_short_page=True,
+ ),
+ "backlinks": SerpstatEndpoint(
+ method="SerpstatBacklinksProcedure.getNewBacklinks",
+ primary_keys=("url_from", "url_to", "link_type", "link_text"),
+ docs_url=BACKLINKS_DOCS_URL,
+ project_param=None,
+ domain_param="query",
+ stop_on_short_page=True,
+ ),
}
AUTH_ERROR = "Serpstat authentication failed. Check your API token and API access for your plan."
QUOTA_ERROR = "Serpstat API credits are exhausted. Add credits or wait for your allowance to reset."
REQUEST_ERROR = "Serpstat rejected the request. Check your project ID, region ID, and API access."
+DOMAIN_ERROR = "Enter a domain in the Serpstat source settings to sync the domain and backlink tables."
_RATE_LIMIT_RESPONSE_ACTIONS: list[ResponseAction] = [
{"content": message, "action": "retry", "message": "Serpstat request rate exceeded. Try again later."}
@@ -86,3 +141,9 @@ RESPONSE_ACTIONS: list[ResponseAction] = [
{"status_code": 400, "action": "raise", "message": REQUEST_ERROR},
{"content": '"error"', "action": "raise", "message": REQUEST_ERROR},
]
+
+# Serpstat answers "Data not found" when a domain or an incremental window has no rows.
+DOMAIN_RESPONSE_ACTIONS: list[ResponseAction] = [
+ {"json_field": "error.code", "json_values": [32017, -32017], "action": "ignore"},
+ *RESPONSE_ACTIONS,
+]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/source.py
index 9443ba7cbf11..30d44e1079ff 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/source.py
@@ -1,4 +1,5 @@
-from typing import cast
+from datetime import date, datetime
+from typing import Any, cast
from requests import RequestException
@@ -33,7 +34,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.s
)
from products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.settings import (
AUTH_ERROR,
+ DEFAULT_SEARCH_ENGINE,
DOCS_BASE,
+ DOMAIN_ERROR,
ENDPOINTS,
QUOTA_ERROR,
REQUEST_ERROR,
@@ -55,7 +58,7 @@ class SerpstatSource(ResumableSource[SerpstatSourceConfig, SerpstatResumeConfig]
return ExternalDataSourceType.SERPSTAT
def get_non_retryable_errors(self) -> dict[str, str | None]:
- return {message: message for message in (AUTH_ERROR, QUOTA_ERROR, REQUEST_ERROR)}
+ return {message: message for message in (AUTH_ERROR, QUOTA_ERROR, REQUEST_ERROR, DOMAIN_ERROR)}
def get_canonical_descriptions(self) -> CanonicalDescriptions:
return CANONICAL_DESCRIPTIONS
@@ -72,8 +75,9 @@ class SerpstatSource(ResumableSource[SerpstatSourceConfig, SerpstatResumeConfig]
return [
SourceSchema(
name=name,
- supports_incremental=False,
+ supports_incremental=bool(endpoint.incremental_fields),
supports_append=False,
+ incremental_fields=endpoint.incremental_fields,
detected_primary_keys=list(endpoint.primary_keys),
description=CANONICAL_DESCRIPTIONS[name]["description"],
)
@@ -124,6 +128,9 @@ class SerpstatSource(ResumableSource[SerpstatSourceConfig, SerpstatResumeConfig]
inputs.job_id,
self.resolve_api_version(inputs.api_version),
resumable_source_manager,
+ date_from=_date_from(inputs.db_incremental_field_last_value)
+ if inputs.should_use_incremental_field
+ else None,
)
return SourceResponse(
name=resource.name,
@@ -148,7 +155,8 @@ class SerpstatSource(ResumableSource[SerpstatSourceConfig, SerpstatResumeConfig]
"Create an API token on your [Serpstat profile](https://serpstat.com/users/profile/). "
"API access requires the Team plan or higher. "
"Syncs use your account's API units when Serpstat applies a charge. "
- "Serpstat lists these methods as free of API credit charges. "
+ "Serpstat lists the project methods as free of API credit charges. "
+ "The domain and backlink tables use API credits for each returned row, and they need a domain. "
"Paginated tables include up to 500 records. Positions cover the last seven days for one project region."
),
fields=cast(
@@ -180,6 +188,38 @@ class SerpstatSource(ResumableSource[SerpstatSourceConfig, SerpstatResumeConfig]
secret=False,
caption="Use the region ID from the Serpstat getProjectRegions method.",
),
+ SourceFieldInputConfig(
+ name="domain",
+ label="Domain",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="example.com",
+ secret=False,
+ caption="The domain to analyze for the domain and backlink tables.",
+ ),
+ SourceFieldInputConfig(
+ name="search_engine",
+ label="Search engine database",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder=DEFAULT_SEARCH_ENGINE,
+ secret=False,
+ caption=(
+ "The Serpstat database code for the domain tables, for example `g_us` for Google US. "
+ f"Leave blank to use `{DEFAULT_SEARCH_ENGINE}`. See the "
+ f"[database list]({DOCS_BASE}ba97ni814ao9p-search-engine-short-names)."
+ ),
+ ),
],
),
)
+
+
+def _date_from(value: Any) -> str | None:
+ if isinstance(value, datetime):
+ return value.date().isoformat()
+ if isinstance(value, date):
+ return value.isoformat()
+ if isinstance(value, str) and value:
+ return value[:10]
+ return None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/tests/test_serpstat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/tests/test_serpstat.py
index 44c948b7a23c..c85148d51e3e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/tests/test_serpstat.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/tests/test_serpstat.py
@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.serpstat import SerpstatResumeConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.settings import (
AUTH_ERROR,
+ DOMAIN_ERROR,
MAX_PAGES,
PAGE_SIZE,
QUOTA_ERROR,
@@ -21,7 +22,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.s
)
from products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.source import SerpstatSource
-CONFIG = SerpstatSourceConfig(api_key="example-token+/", project_id="123", project_region_id="456")
+CONFIG = SerpstatSourceConfig(
+ api_key="example-token+/", project_id="123", project_region_id="456", domain="example.com"
+)
def request_json(request: RecordedRequest) -> dict[str, Any]:
@@ -32,8 +35,13 @@ def reply(status: int, body: dict[str, Any]) -> ScriptedResponse:
return ScriptedResponse(status=status, json=body)
-def drive(endpoint: str, script: list[ScriptedResponse], resume: SerpstatResumeConfig | None = None) -> Any:
- return SourceDriver(SerpstatSource(), CONFIG).run(endpoint, script, resume_state=resume)
+def drive(
+ endpoint: str,
+ script: list[ScriptedResponse],
+ resume: SerpstatResumeConfig | None = None,
+ config: SerpstatSourceConfig = CONFIG,
+) -> Any:
+ return SourceDriver(SerpstatSource(), config).run(endpoint, script, resume_state=resume)
@pytest.mark.parametrize(
@@ -86,6 +94,41 @@ def drive(endpoint: str, script: list[ScriptedResponse], resume: SerpstatResumeC
},
{"keyword_id": 8, "project_id": 123, "regions": [{"project_region_id": 456, "positions": []}]},
),
+ (
+ "domain_info",
+ "SerpstatDomainProcedure.getDomainsInfo",
+ {"domains": ["example.com"], "se": "g_us"},
+ {"data": [{"domain": "example.com", "keywords": 10}], "summary_info": {"page": 1}},
+ {"domain": "example.com", "keywords": 10},
+ ),
+ (
+ "domain_history",
+ "SerpstatDomainProcedure.getDomainsHistory",
+ {"domain": "example.com", "se": "g_us", "during_all_time": True, "sort": {"date": "asc"}, "size": 1000},
+ {"data": [{"domain": "example.com", "date": "2026-01-05"}], "summary_info": {"total": 1}},
+ {"domain": "example.com", "date": "2026-01-05"},
+ ),
+ (
+ "domain_keywords",
+ "SerpstatDomainProcedure.getDomainKeywords",
+ {"domain": "example.com", "se": "g_us", "size": 100, "page": 1},
+ {"data": [{"domain": "example.com", "keyword": "example", "url": "https://example.com/"}]},
+ {"domain": "example.com", "keyword": "example", "url": "https://example.com/"},
+ ),
+ (
+ "backlinks",
+ "SerpstatBacklinksProcedure.getNewBacklinks",
+ {
+ "query": "example.com",
+ "searchType": "domain_with_subdomains",
+ "sort": "add",
+ "order": "desc",
+ "size": 100,
+ "page": 1,
+ },
+ {"data": [{"url_from": "https://example.org/", "url_to": "https://example.com/"}]},
+ {"url_from": "https://example.org/", "url_to": "https://example.com/"},
+ ),
],
)
def test_request_and_rows(
@@ -136,6 +179,67 @@ def test_pagination_resume_and_caps(endpoint: str, total_key: str, start_page: i
assert run.saved_states[-1].page == start_page + 1
[email protected]("endpoint", ["domain_keywords", "backlinks"])
+ "page_sizes,expected_pages",
+ [
+ ([PAGE_SIZE, 3], [1, 2]),
+ ([PAGE_SIZE, PAGE_SIZE, 0], [1, 2, 3]),
+ ([PAGE_SIZE] * MAX_PAGES, list(range(1, MAX_PAGES + 1))),
+ ],
+)
+def test_row_total_endpoints_stop_on_short_page(
+ endpoint: str, page_sizes: list[int], expected_pages: list[int]
+) -> None:
+ script = [
+ reply(200, {"result": {"data": [{"url_from": "a"}] * size, "summary_info": {"total": 10_000}}})
+ for size in page_sizes
+ ]
+ run = drive(endpoint, script)
+ assert run.raised is None
+ assert [request_json(request)["params"]["page"] for request in run.requests] == expected_pages
+ assert len(run.rows) == sum(page_sizes)
+
+
+ "domain,search_engine,expected_domain,expected_se",
+ [
+ (" https://WWW.Example.com/blog/ ", None, "www.example.com", "g_us"),
+ ("http://example.com", " ", "example.com", "g_us"),
+ ("example.com", "g_uk", "example.com", "g_uk"),
+ ],
+)
+def test_domain_and_search_engine_inputs(
+ domain: str, search_engine: str | None, expected_domain: str, expected_se: str
+) -> None:
+ config = SerpstatSourceConfig(
+ api_key="example-token", project_id="123", project_region_id="456", domain=domain, search_engine=search_engine
+ )
+ run = drive("domain_keywords", [reply(200, {"result": {"data": []}})], config=config)
+ assert run.raised is None
+ params = request_json(run.requests[0])["params"]
+ assert (params["domain"], params["se"]) == (expected_domain, expected_se)
+
+
[email protected]("domain", [None, "", " ", "https://"])
[email protected]("endpoint", ["domain_info", "domain_history", "domain_keywords", "backlinks"])
+def test_domain_tables_fail_without_domain_before_any_request(endpoint: str, domain: str | None) -> None:
+ config = SerpstatSourceConfig(api_key="example-token", project_id="123", project_region_id="456", domain=domain)
+ run = drive(endpoint, [], config=config)
+ assert isinstance(run.raised, ValueError)
+ assert str(run.raised) == DOMAIN_ERROR
+ assert run.requests == []
+
+
[email protected]("code", [32017, -32017])
[email protected]("endpoint", ["domain_info", "domain_history", "domain_keywords", "backlinks"])
+def test_domain_tables_treat_data_not_found_as_empty(endpoint: str, code: int) -> None:
+ run = drive(endpoint, [reply(200, {"id": "posthog", "error": {"code": code, "message": "Data not found"}})])
+ assert run.raised is None
+ assert run.rows == []
+ assert len(run.requests) == 1
+
+
def test_positions_resume_keeps_original_date_window() -> None:
run = drive(
"project_positions",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/tests/test_serpstat_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/tests/test_serpstat_source.py
index c1d86879aec6..08462cb71b83 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/tests/test_serpstat_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/tests/test_serpstat_source.py
@@ -1,3 +1,6 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
import pytest
from unittest.mock import patch
@@ -67,3 +70,32 @@ def test_pipeline_does_not_apply_unavailable_incremental_filter(incremental: boo
assert result.response.primary_keys == ["project_id", "id"]
assert result.response.partition_keys == ["added"]
assert result.response.sort_mode == "asc"
+
+
+ "incremental,last_value,expected_filters",
+ [
+ (False, None, None),
+ (False, "2026-01-01", None),
+ (True, None, None),
+ (True, "2026-01-01", {"date_from": "2026-01-01"}),
+ (True, date(2026, 2, 3), {"date_from": "2026-02-03"}),
+ (True, datetime(2026, 3, 4, 5, 6, tzinfo=UTC), {"date_from": "2026-03-04"}),
+ ],
+)
+def test_domain_history_filters_from_watermark(
+ incremental: bool, last_value: Any, expected_filters: dict[str, str] | None
+) -> None:
+ config = SerpstatSourceConfig(
+ api_key="example-token", project_id="123", project_region_id="456", domain="example.com"
+ )
+ result = SourceDriver(SerpstatSource(), config).run(
+ "domain_history",
+ [ScriptedResponse(json={"result": {"data": [{"domain": "example.com", "date": "2026-03-10"}]}})],
+ should_use_incremental_field=incremental,
+ db_incremental_field_last_value=last_value,
+ )
+ assert result.raised is None
+ params = result.requests[0].json()["params"]
+ assert params.get("filters") == expected_filters
+ assert params["sort"] == {"date": "asc"}