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 the semrush import source (#111910)

Tom Owers09fdb7980cff
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 31b135c4e192..949f55fc861c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -678,6 +678,7 @@ the row lists both.
| select_star | HTTP | requests + `rest_source.RESTClient` | ✅ |
| semantic_scholar | HTTP | requests + `rest_source.RESTClient` | ✅ |
| semgrep | HTTP | requests | ✅ |
+| semrush | HTTP | requests | ✅ |
| sendgrid | HTTP | requests | ✅ |
| sendowl | HTTP | requests | ✅ |
| sentinelone | HTTP | requests | ✅ |
@@ -1378,7 +1379,6 @@ doesn't conflict with concurrent PRs.
- sec_edgar
- secureframe
- semaphore
-- semrush
- sendpulse
- senseforce
- service_fusion
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/semrush.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/semrush.py
index 6865318d589b..dbd0c7f4f64e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/semrush.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/semrush.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class SemrushSourceConfig(config.Config):
- pass
+ api_key: str
+ project_id: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semrush/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semrush/canonical_descriptions.py
new file mode 100644
index 000000000000..445dba910639
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semrush/canonical_descriptions.py
@@ -0,0 +1,45 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semrush.settings import API_DOCS_URL
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "site_audit": {
+ "description": "Summary of the latest Site Audit for the configured Semrush project.",
+ "docs_url": API_DOCS_URL + "#get-information-about-campaign",
+ "columns": {
+ "project_id": "Project ID supplied in the source configuration.",
+ "id": "Semrush project ID.",
+ "url": "Project URL.",
+ "name": "Project name.",
+ "status": "Current audit status.",
+ "errors": "Number of errors found during the latest audit.",
+ "warnings": "Number of warnings found during the latest audit.",
+ "notices": "Number of notices found during the latest audit.",
+ "pages_crawled": "Number of pages crawled.",
+ "last_audit": "Date of the latest audit.",
+ "defects": "Detected issue IDs and their counts.",
+ },
+ },
+ "site_audit_snapshots": {
+ "description": "Completed audit IDs and completion dates for the configured Semrush project.",
+ "docs_url": API_DOCS_URL + "#get-list-of-campaign-snapshots",
+ "columns": {
+ "project_id": "Project ID supplied in the source configuration.",
+ "snapshot_id": "Audit snapshot ID.",
+ "finish_date": "Audit completion time in Unix milliseconds.",
+ },
+ },
+ "site_audit_issue_descriptions": {
+ "description": "Issue descriptions for Site Audit reports.",
+ "docs_url": API_DOCS_URL + "#get-text-descriptions-about-issues",
+ "columns": {
+ "project_id": "Project ID supplied in the source configuration.",
+ "id": "Issue type ID.",
+ "title": "Issue title.",
+ "title_page": "Issue title for the page report.",
+ "url_column": "Label for the affected URL column.",
+ "info_column": "Label for the issue information column.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semrush/semrush.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semrush/semrush.py
new file mode 100644
index 000000000000..c6a6fe004741
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semrush/semrush.py
@@ -0,0 +1,97 @@
+import re
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+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 schema_for_resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.semrush.settings import (
+ ACCESS_ERROR,
+ AUTH_ERROR,
+ BASE_URL,
+ ENDPOINTS,
+ ERROR_MESSAGES,
+ MAX_REQUEST_ATTEMPTS,
+ PROJECT_ID_ERROR,
+ REQUEST_ERROR,
+)
+
+
+def validate_project_id(project_id: str) -> None:
+ if re.fullmatch(r"[0-9]+", project_id) is None:
+ raise ValueError(PROJECT_ID_ERROR)
+
+
+def normalize_row(row: dict[str, object], project_id: str, primary_key: str) -> dict[str, object]:
+ if row.get(primary_key) is None:
+ raise ValueError("Semrush returned a record without its ID.")
+ return {**row, "project_id": project_id}
+
+
+def semrush_resource(api_key: str, project_id: str, endpoint: str, team_id: int, job_id: str) -> Resource:
+ validate_project_id(project_id)
+ settings = schema_for_resource(ENDPOINTS, endpoint)
+ error_actions: list[ResponseAction] = [
+ {"json_field": "code", "json_values": [code, str(code)], "action": "raise", "message": message}
+ for code, message in ERROR_MESSAGES.items()
+ ]
+ client_error_actions: list[ResponseAction] = [
+ {"status_code": status, "action": "raise", "message": REQUEST_ERROR}
+ for status in range(400, 500)
+ if status != 429
+ ]
+ actions: list[ResponseAction] = [
+ {"status_code": 401, "action": "raise", "message": AUTH_ERROR},
+ {"status_code": 403, "action": "raise", "message": ACCESS_ERROR},
+ *error_actions,
+ {"json_field": "code", "json_values": [511, "511"], "action": "retry", "message": "Semrush temporary error."},
+ *client_error_actions,
+ ]
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": BASE_URL,
+ "auth": {"type": "api_key", "name": "key", "api_key": api_key, "location": "query"},
+ "paginator": "single_page",
+ "max_retries": MAX_REQUEST_ATTEMPTS,
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ "request_timeout": (10, 30),
+ },
+ "resources": [
+ {
+ "name": endpoint,
+ "write_disposition": "replace",
+ "endpoint": {
+ "path": f"{project_id}/siteaudit/{settings['path']}",
+ "data_selector": settings["selector"],
+ "data_selector_required": True,
+ "response_actions": actions,
+ },
+ "data_map": lambda row: normalize_row(row, project_id, settings["primary_key"]),
+ }
+ ],
+ }
+ return rest_api_resource(config, team_id, job_id, None)
+
+
+def validate_credentials(api_key: str, project_id: str, team_id: int) -> tuple[bool, str | None]:
+ try:
+ list(semrush_resource(api_key, project_id, "site_audit", team_id, ""))
+ except ValueError as error:
+ message = str(error)
+ if message in {*ERROR_MESSAGES.values(), PROJECT_ID_ERROR, REQUEST_ERROR}:
+ return False, message
+ raise
+ return True, None
+
+
+def semrush_source(api_key: str, project_id: str, endpoint: str, team_id: int, job_id: str) -> SourceResponse:
+ resource = semrush_resource(api_key, project_id, endpoint, team_id, job_id)
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=["project_id", ENDPOINTS[endpoint]["primary_key"]],
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semrush/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semrush/settings.py
new file mode 100644
index 000000000000..25c42f23e453
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semrush/settings.py
@@ -0,0 +1,38 @@
+from typing import TypedDict
+
+
+class SemrushEndpoint(TypedDict):
+ path: str
+ selector: str
+ primary_key: str
+
+
+API_VERSION = "v1"
+BASE_URL = f"https://api.semrush.com/reports/{API_VERSION}/projects/"
+API_DOCS_URL = "https://developer.semrush.com/api/v3/projects/site-audit/"
+MAX_REQUEST_ATTEMPTS = 3
+
+ENDPOINTS: dict[str, SemrushEndpoint] = {
+ "site_audit": {"path": "info", "selector": "$", "primary_key": "id"},
+ "site_audit_snapshots": {"path": "snapshots", "selector": "snapshots", "primary_key": "snapshot_id"},
+ "site_audit_issue_descriptions": {"path": "meta/issues", "selector": "issues", "primary_key": "id"},
+}
+
+AUTH_ERROR = "Semrush authentication failed. Check your v3 API key in your Semrush profile."
+ACCESS_ERROR = "Semrush API access is disabled. Check your SEO Business subscription and project access."
+QUOTA_ERROR = "Semrush API units or request limits are exhausted. Add API units or contact Semrush support."
+PROJECT_ERROR = "Semrush could not find this project. Check the project ID and your access to it."
+PROJECT_ID_ERROR = "Enter the numeric project ID from your Semrush project URL."
+REQUEST_ERROR = "Semrush rejected the request. Check your project ID, Site Audit setup, and API access."
+
+ERROR_MESSAGES = {
+ 70: AUTH_ERROR,
+ 120: AUTH_ERROR,
+ 121: AUTH_ERROR,
+ 122: AUTH_ERROR,
+ 130: ACCESS_ERROR,
+ 131: QUOTA_ERROR,
+ 132: QUOTA_ERROR,
+ 134: QUOTA_ERROR,
+ 512: PROJECT_ERROR,
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semrush/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semrush/source.py
index 5d2a93e03fc6..21c0f498f2c4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/semrush/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semrush/source.py
@@ -1,27 +1,124 @@
from typing import cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ 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.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,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.semrush import (
SemrushSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semrush.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semrush.semrush import (
+ semrush_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semrush.settings import (
+ ACCESS_ERROR,
+ API_DOCS_URL,
+ API_VERSION,
+ AUTH_ERROR,
+ ENDPOINTS,
+ ERROR_MESSAGES,
+ PROJECT_ID_ERROR,
+ REQUEST_ERROR,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class SemrushSource(SimpleSource[SemrushSourceConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = (API_VERSION,)
+ default_version = API_VERSION
+ api_docs_url = API_DOCS_URL
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SEMRUSH
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ **{message: message for message in ERROR_MESSAGES.values()},
+ PROJECT_ID_ERROR: PROJECT_ID_ERROR,
+ REQUEST_ERROR: REQUEST_ERROR,
+ "401 Client Error": AUTH_ERROR,
+ "403 Client Error": ACCESS_ERROR,
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: SemrushSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, {}, names)
+
+ def validate_credentials(
+ self,
+ config: SemrushSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_credentials(config.api_key, config.project_id, team_id)
+
+ def source_for_pipeline(self, config: SemrushSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return semrush_source(config.api_key, config.project_id, inputs.schema_name, inputs.team_id, inputs.job_id)
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.SEMRUSH,
- category=DataWarehouseSourceCategory.MARKETING___EMAIL,
+ category=DataWarehouseSourceCategory.ANALYTICS,
label="Semrush",
+ caption=(
+ "Requires an SEO Business subscription and a project with Site Audit enabled. "
+ "Find your v3 API key under [API keys](https://www.semrush.com/accounts/api-keys/active) in your Semrush profile. "
+ "Syncs use your account's API units: 100 units per table request. Retries can use more units. "
+ "Connection validation also uses 100 units."
+ ),
iconPath="/static/services/semrush.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key (v3)",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="project_id",
+ label="Project ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="123456",
+ secret=False,
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semrush/tests/test_semrush.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semrush/tests/test_semrush.py
new file mode 100644
index 000000000000..fd4cf1cb5470
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semrush/tests/test_semrush.py
@@ -0,0 +1,153 @@
+import json
+from collections.abc import Iterable
+from typing import Any, cast
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+from unittest.mock import patch
+
+from requests import Response, Session
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
+ RESTClientRetryableError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import UnknownResourceError
+from products.warehouse_sources.backend.temporal.data_imports.sources.semrush.semrush import (
+ semrush_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semrush.settings import (
+ ACCESS_ERROR,
+ AUTH_ERROR,
+ PROJECT_ERROR,
+ PROJECT_ID_ERROR,
+ QUOTA_ERROR,
+ REQUEST_ERROR,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semrush.source import SemrushSource
+
+
+def response(body: object, status: int = 200) -> Response:
+ result = Response()
+ result.status_code = status
+ result._content = json.dumps(body).encode()
+ result.headers["Content-Type"] = "application/json"
+ return result
+
+
+ "endpoint,path,body,expected",
+ [
+ ("site_audit", "info", {"id": 123, "errors": 2}, [{"id": 123, "errors": 2, "project_id": "123"}]),
+ (
+ "site_audit_snapshots",
+ "snapshots",
+ {"snapshots": [{"snapshot_id": "snapshot-a", "finish_date": 1700000000000}]},
+ [{"snapshot_id": "snapshot-a", "finish_date": 1700000000000, "project_id": "123"}],
+ ),
+ (
+ "site_audit_issue_descriptions",
+ "meta/issues",
+ {"issues": [{"id": 1, "title": "Server errors"}]},
+ [{"id": 1, "title": "Server errors", "project_id": "123"}],
+ ),
+ ("site_audit_snapshots", "snapshots", {"snapshots": []}, []),
+ ("site_audit_issue_descriptions", "meta/issues", {"issues": []}, []),
+ ],
+)
+def test_requests_and_terminal_page(endpoint: str, path: str, body: object, expected: list[dict[str, object]]) -> None:
+ with patch.object(Session, "send", return_value=response(body)) as send:
+ source = semrush_source("fake-api-key", "123", endpoint, 1, "job")
+ rows = [row for page in cast(Iterable[Any], source.items()) for row in page]
+
+ assert rows == expected
+ assert send.call_count == 1
+ request = send.call_args.args[0]
+ url = urlsplit(request.url)
+ assert url.scheme == "https"
+ assert url.netloc == "api.semrush.com"
+ assert url.path == f"/reports/v1/projects/123/siteaudit/{path}"
+ assert parse_qs(url.query) == {"key": ["fake-api-key"]}
+ assert "Authorization" not in request.headers
+ assert request.method == "GET"
+ assert send.call_args.kwargs["allow_redirects"] is False
+
+
+ "status,body,message",
+ [
+ (401, "Unauthorized", AUTH_ERROR),
+ (403, "Forbidden", ACCESS_ERROR),
+ (400, {"code": 70, "message": "API key hash failure"}, AUTH_ERROR),
+ (400, {"code": 120, "message": "Wrong key-ID pair"}, AUTH_ERROR),
+ (400, {"code": 121, "message": "Wrong format or empty hash"}, AUTH_ERROR),
+ (400, {"code": 122, "message": "Wrong format or empty key"}, AUTH_ERROR),
+ (400, {"code": 130, "message": "API disabled"}, ACCESS_ERROR),
+ (400, {"code": 131, "message": "Limit exceeded"}, QUOTA_ERROR),
+ (400, {"code": 132, "message": "API units balance is zero"}, QUOTA_ERROR),
+ (400, {"code": 134, "message": "Total limit exceeded"}, QUOTA_ERROR),
+ (400, {"code": 512, "message": "Can't find project with project_id 123"}, PROJECT_ERROR),
+ (200, {"code": "132", "message": "API units balance is zero"}, QUOTA_ERROR),
+ (400, {"code": 519, "message": "Missing mandatory URL parameter"}, REQUEST_ERROR),
+ (404, {"message": "Not found"}, REQUEST_ERROR),
+ ],
+)
+def test_errors_stop_sync_and_explain_validation_failure(status: int, body: object, message: str) -> None:
+ with patch.object(Session, "send", return_value=response(body, status)) as send:
+ with pytest.raises(ValueError, match=message):
+ list(cast(Iterable[Any], semrush_source("fake-api-key", "123", "site_audit", 1, "job").items()))
+ assert send.call_count == 1
+ assert validate_credentials("fake-api-key", "123", 1) == (False, message)
+ assert send.call_count == 2
+ assert message in SemrushSource().get_non_retryable_errors()
+
+
+ "status,body", [(429, {}), (500, {}), (503, {}), (200, {"code": 511, "message": "Unknown error"})]
+)
+def test_transient_errors_retry(status: int, body: object) -> None:
+ failed = response(body, status)
+ failed.headers["Retry-After"] = "0"
+ with (
+ patch.object(Session, "send", side_effect=[failed, response({"id": 123})]) as send,
+ patch("tenacity.nap.time.sleep"),
+ ):
+ assert validate_credentials("fake-api-key", "123", 1) == (True, None)
+ assert send.call_count == 2
+
+
+def test_retry_limit_bounds_paid_requests() -> None:
+ with patch.object(Session, "send", return_value=response({}, 503)) as send, patch("tenacity.nap.time.sleep"):
+ with pytest.raises(RESTClientRetryableError):
+ validate_credentials("fake-api-key", "123", 1)
+ assert send.call_count == 3
+
+
[email protected]("project_id", ["", "../456", "123?key=other", "https://example.com", "123", "123/456"])
+def test_invalid_project_id_never_makes_a_request(project_id: str) -> None:
+ with patch.object(Session, "send") as send:
+ assert validate_credentials("fake-api-key", project_id, 1) == (False, PROJECT_ID_ERROR)
+ with pytest.raises(ValueError, match=PROJECT_ID_ERROR):
+ semrush_source("fake-api-key", project_id, "site_audit", 1, "job")
+ send.assert_not_called()
+
+
+def test_unknown_table_never_makes_a_request() -> None:
+ with patch.object(Session, "send") as send:
+ with pytest.raises(UnknownResourceError):
+ semrush_source("fake-api-key", "123", "unknown", 1, "job")
+ send.assert_not_called()
+
+
+ "endpoint,body,message",
+ [
+ ("site_audit_snapshots", {"message": "Unexpected response"}, "Required data_selector"),
+ ("site_audit", {"code": 999, "message": "Unexpected error"}, "record without its ID"),
+ ("site_audit_snapshots", {"snapshots": [{"finish_date": 1700000000000}]}, "record without its ID"),
+ ],
+)
+def test_malformed_records_fail_instead_of_erasing_rows(endpoint: str, body: object, message: str) -> None:
+ with patch.object(Session, "send", return_value=response(body)):
+ with pytest.raises(ValueError, match=message):
+ list(cast(Iterable[Any], semrush_source("fake-api-key", "123", endpoint, 1, "job").items()))