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 Buttondown source (#77084)

Tom Owers87ff11d81f43
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 1b5605953c60..289a0e7b33c6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -123,6 +123,7 @@ the row lists both.
| buildbetter | HTTP | requests | ✅ |
| buildkite | HTTP | requests | ✅ |
| bunny | HTTP | requests | ✅ |
+| buttondown | HTTP | requests + `rest_source.RESTClient` | ✅ |
| buzzsprout | HTTP | requests | ✅ |
| cal_com | HTTP | requests | ✅ |
| calendly | HTTP | requests | ✅ |
@@ -842,7 +843,6 @@ doesn't conflict with concurrent PRs.
- browse_ai
- buffer
- buildium
-- buttondown
- buy_me_a_coffee
- cal_com
- calendarific
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/buttondown.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/buttondown.py
new file mode 100644
index 000000000000..ed8ea842dd07
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/buttondown.py
@@ -0,0 +1,162 @@
+import dataclasses
+from datetime import date, datetime, timedelta
+from typing import Any, Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.buttondown.settings import BUTTONDOWN_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponsePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+
+BUTTONDOWN_BASE_URL = "https://api.buttondown.com/v1"
+# Buttondown's API is date-versioned. Unpinned requests get whatever version is newest, so send the
+# version this code was written against on every request.
+BUTTONDOWN_API_VERSION = "2026-04-01"
+
+
+class ButtondownResumeConfig:
+ # Absolute URL of the next unfetched page. Buttondown paginates DRF-style: each page body carries
+ # a fully-formed `next` link (or null on the last page).
+ next_url: str
+
+
+def _headers(api_version: str) -> dict[str, str]:
+ # Auth rides the framework's api_key auth so its value is redacted from logs and samples; only
+ # the non-secret version/accept headers are set here.
+ return {"X-API-Version": api_version, "Accept": "application/json"}
+
+
+def _to_start_date(value: Any) -> Optional[str]:
+ """Format an incremental watermark as the `YYYY-MM-DD` Buttondown's date filters expect.
+
+ The filters take a date, not a timestamp, and the docs word some of them as "after the given
+ date" without saying whether that bound is inclusive. Stepping back a day makes the request
+ overlap instead of risking a same-day gap; the extra rows merge away on primary key.
+ """
+ if value is None:
+ return None
+
+ if isinstance(value, datetime):
+ day = value.date()
+ elif isinstance(value, date):
+ day = value
+ else:
+ try:
+ day = datetime.fromisoformat(str(value).replace("Z", "+00:00")).date()
+ except ValueError:
+ # An unparseable watermark drops the filter, which costs a full scan but never skips rows.
+ return None
+
+ return (day - timedelta(days=1)).isoformat()
+
+
+def buttondown_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[ButtondownResumeConfig],
+ api_version: str = BUTTONDOWN_API_VERSION,
+ db_incremental_field_last_value: Optional[Any] = None,
+ should_use_incremental_field: bool = False,
+) -> SourceResponse:
+ config = BUTTONDOWN_ENDPOINTS[endpoint]
+
+ params: dict[str, Any] = {}
+ if config.ordering is not None:
+ params["ordering"] = config.ordering
+ if should_use_incremental_field and config.incremental_start_param is not None:
+ params[config.incremental_start_param] = {
+ "type": "incremental",
+ "cursor_path": "creation_date",
+ "initial_value": None,
+ "convert": _to_start_date,
+ }
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": BUTTONDOWN_BASE_URL,
+ "headers": _headers(api_version),
+ "auth": {
+ "type": "api_key",
+ "name": "Authorization",
+ # Buttondown requires the literal "Token " prefix, not "Bearer ".
+ "api_key": f"Token {api_key}",
+ "location": "header",
+ },
+ "paginator": JSONResponsePaginator(next_url_path="next"),
+ # Pagination follows absolute `next` links straight out of the response body, so pin
+ # them to the API host: a spoofed link would otherwise replay the API key elsewhere.
+ "allowed_hosts": [],
+ },
+ "resource_defaults": {},
+ "resources": [
+ {
+ "name": endpoint,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}
+ if should_use_incremental_field
+ else "replace",
+ "table_format": "delta",
+ "endpoint": {
+ "path": config.path,
+ "params": params,
+ "data_selector": "results",
+ # A 200 without `results` means the envelope changed — fail loud rather than
+ # silently syncing 0 rows.
+ "data_selector_required": True,
+ },
+ }
+ ],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None:
+ initial_paginator_state = {"next_url": resume.next_url}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Saved after a page is yielded, so a crash re-yields the last page (merge dedupes) instead
+ # of skipping it. No state means no next page.
+ if state and state.get("next_url"):
+ resumable_source_manager.save_state(ButtondownResumeConfig(next_url=str(state["next_url"])))
+
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value if should_use_incremental_field else None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=config.primary_keys,
+ sort_mode=config.sort_mode,
+ 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,
+ column_hints=resource.column_hints,
+ )
+
+
+def validate_credentials(api_key: str, api_version: str = BUTTONDOWN_API_VERSION) -> tuple[bool, int | None]:
+ # /accounts/me is the cheapest authenticated endpoint: it returns the account the key belongs to
+ # and 401s on a bad key, without paging any newsletter data.
+ return validate_via_probe(
+ lambda: make_tracked_session(redact_values=(api_key,)),
+ f"{BUTTONDOWN_BASE_URL}/accounts/me",
+ headers={"Authorization": f"Token {api_key}", **_headers(api_version)},
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/canonical_descriptions.py
new file mode 100644
index 000000000000..fe09c1e79d38
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/canonical_descriptions.py
@@ -0,0 +1,216 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions taken from the Buttondown API reference (version 2026-04-01):
+# https://docs.buttondown.com/api-introduction
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "automations": {
+ "description": "An automation: a trigger, optional filters, and the actions Buttondown runs when a subscriber matches.",
+ "docs_url": "https://docs.buttondown.com/api-automations-list",
+ "columns": {
+ "actions": "The actions to perform when the trigger fires.",
+ "creation_date": "The date and time at which the object was first created.",
+ "filters": "Conditions that must be met for the automation to run.",
+ "id": "A unique TypeID associated with the object.",
+ "metadata": "Additional metadata for the automation.",
+ "name": "The name of the automation.",
+ "should_evaluate_filter_after_delay": "If true, filters are re-evaluated after the delay has passed.",
+ "status": "Whether the automation is enabled or disabled.",
+ "trigger": "The event that causes this automation to run.",
+ },
+ },
+ "comments": {
+ "description": "A comment left on an email, by a subscriber or by the newsletter author.",
+ "docs_url": "https://docs.buttondown.com/api-comments-list",
+ "columns": {
+ "creation_date": "The date and time at which the object was first created.",
+ "email_id": "The ID of the email this comment is attached to.",
+ "id": "A unique TypeID associated with the object.",
+ "parent_id": "The ID of the parent comment, if this comment is a reply to another comment.",
+ "status": "The moderation status of the comment (e.g. `active`, `spammy`).",
+ "subscriber_id": "The ID of the subscriber who posted the comment, or null if posted by the newsletter author.",
+ "text": "The text content of the comment.",
+ },
+ },
+ "emails": {
+ "description": "An email in the newsletter, covering drafts, scheduled sends, and sent issues, with its body and aggregate analytics.",
+ "docs_url": "https://docs.buttondown.com/api-emails-list",
+ "columns": {
+ "absolute_url": "The canonical web URL of the email on the newsletter's archive.",
+ "analytics": "Aggregate analytics for the email. Null until the email has been sent.",
+ "archival_mode": "Controls who can view this email in the archive.",
+ "attachments": "A list of attachment IDs present on the email. (See Attachments for more information.)",
+ "body": "The body of the email, in either HTML or markdown format. Buttondown attempts to intelligently detect the format of the body automatically, but you can also specify the format explicitly by prepending the text with the `buttondown-editor-mode` comment: `<!-- buttondown-editor-mode: fancy -->` or `<!-- buttondown-editor-mode: plaintext -->`.",
+ "callouts": "A list of callouts that apply to this email, surfaced in the UI alongside analytics to flag context the reader should know about (e.g., first send on a custom sending domain).",
+ "canonical_url": "The URL of the original source of the content.",
+ "commenting_mode": "Controls whether subscribers can comment on this email.",
+ "creation_date": "The date and time at which the object was first created.",
+ "description": "A human-readable description of the email, used for archives and SEO.",
+ "email_type": "The type of email. Defaults to `PUBLIC`.",
+ "featured": "Designated whether or not this email should be highlighted within the archives.",
+ "filters": "Tag-based filter rules determining which subscribers receive this email.",
+ "id": "A unique TypeID associated with the object.",
+ "image": "A primary image URL used when previewing the email on the web or in other contexts.",
+ "metadata": "A structured key-value blob that you can use to store arbitrary data on the object.",
+ "modification_date": "The date and time at which the object was last modified.",
+ "publish_date": "The date and time at which the email should be published in the future (for scheduled emails), or the date and time at which the email was published (for sent emails).",
+ "related_email_ids": "A list of email IDs that are related to this email. Related emails are shown at the bottom of the email and archive pages.",
+ "secondary_id": "An informal 'number' for the email, used in some templates ('This was issue #123').",
+ "should_trigger_pay_per_email_billing": "Whether this email should trigger pay-per-email billing for paid subscribers.",
+ "slug": "A short, human-readable identifier for the email, used in the archive URL.",
+ "source": "The source of the email.",
+ "status": "The current status of the email.",
+ "subject": "The subject line for the email.",
+ "suppression_reason": "If the email has been suppressed from sending, the reason why.",
+ "template": "If present, this template overrides your newsletter's default email template.",
+ },
+ },
+ "events": {
+ "description": "A per-subscriber email engagement event, such as a delivery, open, click, bounce, or unsubscribe.",
+ "docs_url": "https://docs.buttondown.com/api-emails-events",
+ "columns": {
+ "automation_id": "The ID of the automation that sent the email, if any.",
+ "creation_date": "The date and time at which the object was first created.",
+ "email_id": "The ID of the email the event is attributed to, if any.",
+ "event_type": "The type of event (e.g. `delivered`, `opened`, `clicked`, `unsubscribed`).",
+ "id": "A unique TypeID associated with the object.",
+ "metadata": "Event-type-specific metadata (e.g. clicked URL, bounce reason).",
+ "subscriber_id": "The ID of the subscriber the event is attributed to, if any.",
+ },
+ },
+ "forms": {
+ "description": "A registration form subscribers can sign up through, with its signup and page view counts.",
+ "docs_url": "https://docs.buttondown.com/api-introduction",
+ "columns": {
+ "admin": "If true, the form acts as an admin-only signup form: it skips confirmation and can accept additional subscriber fields.",
+ "body": "Markdown body rendered above the subscribe fields on the hosted form page.",
+ "confirmed_subscriber_count": "The number of confirmed subscribers who signed up through this form.",
+ "creation_date": "The date and time at which the object was first created.",
+ "css": "Custom CSS applied to the hosted form page.",
+ "id": "A unique TypeID associated with the object.",
+ "page_view_count": "The number of page views for this form.",
+ "slug": "A URL-safe identifier used in the form's hosted URL (e.g. `/forms/{slug}`).",
+ "status": "The status of the form. Only `active` forms accept submissions.",
+ "subscriber_count": "The number of subscribers who signed up through this form.",
+ "success_body": "Markdown shown to the subscriber after a successful submission.",
+ "surveys": "IDs of surveys to attach to this form. Responses are associated with the submitting subscriber.",
+ "title": "The human-readable title of the form, shown in the UI and on the hosted form page.",
+ },
+ },
+ "prices": {
+ "description": "A price for a paid subscription to the newsletter, backed by a Stripe product.",
+ "docs_url": "https://docs.buttondown.com/api-prices-list",
+ "columns": {
+ "amount": "The price amount in the smallest currency unit (e.g. cents).",
+ "cadence": "The billing cadence for this price.",
+ "currency": "The three-letter ISO currency code (e.g. 'usd').",
+ "description": "An optional human-readable description of the price.",
+ "id": "The unique identifier of the price.",
+ "maximum_amount": "The maximum amount for pay-what-you-want prices.",
+ "minimum_amount": "The minimum amount for pay-what-you-want prices.",
+ "product_id": "The ID of the Stripe product this price belongs to.",
+ "style": "The pricing style: 'fixed', 'pay-what-you-want', or 'usage-based'.",
+ "suggested_amount": "The suggested amount for pay-what-you-want prices.",
+ },
+ },
+ "subscribers": {
+ "description": "A subscriber to the newsletter, with lifecycle state, signup attribution, and cached engagement counts.",
+ "docs_url": "https://docs.buttondown.com/api-subscribers-list",
+ "columns": {
+ "avatar_url": "URL of the subscriber's avatar image (e.g. a Gravatar URL), if available.",
+ "bounce_date": "The date of the subscriber's most recent bounce event. May be set even if the subscriber has not yet been marked as undeliverable.",
+ "bounce_reason": "The reason of the subscriber's most recent bounce event. May be set even if the subscriber has not yet been marked as undeliverable.",
+ "churn_date": "When the subscriber cancelled their paid subscription, if applicable.",
+ "click_rate": "The subscriber's click rate, computed from engagement counts.",
+ "clicked_count": "The subscriber's clicked count.",
+ "commenting_disabled": "Whether this subscriber is prevented from commenting.",
+ "country": "The ISO 3166-1 alpha-2 country code inferred from the subscriber's IP address at signup, if available.",
+ "creation_date": "The date and time at which the object was first created.",
+ "delivered_count": "The number of distinct emails (broadcasts and automation sends) delivered to this subscriber.",
+ "email_address": "The email address of the subscriber.",
+ "email_transitions": "The history of email address changes for this subscriber.",
+ "firewall_reasons": "Information collected by Buttondown's firewall about this subscriber.",
+ "form_id": "The ID of the registration form the subscriber signed up through, if any.",
+ "gift_subscription_end_date": "When the subscriber's gift subscription expires, if applicable.",
+ "gift_subscription_message": "A custom message that was sent to the subscriber when the gift subscription was created.",
+ "id": "A unique TypeID associated with the object.",
+ "ip_address": "The IP address recorded when the subscriber signed up, if available.",
+ "last_click_date": "When the subscriber most recently clicked a link in an email.",
+ "last_open_date": "When the subscriber most recently opened an email.",
+ "metadata": "A structured key-value blob that you can use to store arbitrary data on the object.",
+ "notes": "Any notes you want to attach to the subscriber. These are not publicly visible.",
+ "open_count": "The subscriber's open count.",
+ "open_rate": "The subscriber's open rate, computed from engagement counts.",
+ "purchased_by": "The email address of the individual who purchased this subscription on behalf of the subscriber.",
+ "purchased_message": "A custom message that was sent to the subscriber when the subscription was purchased on behalf of the subscriber.",
+ "referral_code": "The subscriber's unique referral code, used to attribute referred signups.",
+ "referrer_url": "The URL the subscriber was referred from (e.g. where they submitted the subscription form).",
+ "risk_score": "The risk score of the subscriber. Positive numbers represent a higher risk; negative numbers represent a lower risk.",
+ "secondary_id": "A human-readable sequential identifier, unique within the newsletter.",
+ "source": "Where the subscriber signed up from (e.g. `api`, `import`, `form`).",
+ "stripe_coupon": "The Stripe coupon applied to the subscriber's paid subscription, if any.",
+ "stripe_customer_id": "The Stripe customer ID associated with the subscriber, if any.",
+ "subscriber_import_id": "The ID of the subscriber import that created this subscriber, if any.",
+ "tags": "A list of tag names applied to the subscriber. Tags that don't already exist will be created, which requires a plan that includes tags (Basic or higher).",
+ "transitions": "The history of subscriber type transitions (for example regular to premium).",
+ "type": "The subscriber's lifecycle state: one of `blocked`, `churned`, `churning`, `complained`, `gifted`, `past_due`, `paused`, `premium`, `regular`, `removed`, `trialed`, `unactivated`, `undeliverable`, `unpaid`, `unsubscribed`, `upcoming`.",
+ "undeliverability_date": "When the subscriber was marked as undeliverable, if applicable.",
+ "undeliverability_reason": "The reason the subscriber is undeliverable. (Only populated for undeliverable subscribers.)",
+ "unsubscription_date": "When the subscriber unsubscribed, if applicable.",
+ "unsubscription_reason": "Free-text reason the subscriber unsubscribed, if provided.",
+ "upgrade_date": "When the subscriber upgraded to a paid subscription, if applicable.",
+ "utm_campaign": "The UTM campaign the subscriber was attributed to at signup.",
+ "utm_medium": "The UTM medium the subscriber was attributed to at signup.",
+ "utm_source": "The UTM source the subscriber was attributed to at signup.",
+ },
+ },
+ "survey_responses": {
+ "description": "A single subscriber response to a survey.",
+ "docs_url": "https://docs.buttondown.com/api-survey-responses",
+ "columns": {
+ "answer": "The answer given to the survey.",
+ "automation_id": "The ID of the automation where this response was submitted, if any.",
+ "creation_date": "The date and time at which the object was first created.",
+ "email_id": "The ID of the email where this response was submitted, if any.",
+ "id": "A unique TypeID associated with the object.",
+ "source": "For responses not tied to an email or automation, the origin the survey was answered from.",
+ "subscriber_id": "The ID of the subscriber who submitted this response.",
+ "survey_id": "The ID of the survey this response was submitted to.",
+ "text": "Optional text included by the subscriber with the response. Subscribers are only prompted to supply a text response if the `is_freeform_response_enabled` field is set to `true` on the survey.",
+ },
+ },
+ "surveys": {
+ "description": "A survey subscribers can answer from an email, an automation, or a registration form.",
+ "docs_url": "https://docs.buttondown.com/api-surveys-list",
+ "columns": {
+ "answers": "The list of pre-defined answer choices. Order is preserved unless `randomize_answers` is true.",
+ "creation_date": "The date and time at which the object was first created.",
+ "id": "A unique TypeID associated with the object.",
+ "identifier": "A newsletter-scoped slug used to reference this survey when embedding it in emails.",
+ "input_type": "The UI control used to collect responses (e.g. `radio`, `checkbox`).",
+ "is_freeform_response_enabled": "If true, subscribers can provide a freeform text response in addition to (or instead of) picking from `answers`.",
+ "notes": "Internal notes about the survey. Not shown to subscribers.",
+ "question": "The survey question shown to subscribers.",
+ "randomize_answers": "If true, the order of `answers` is shuffled each time the survey is rendered.",
+ "response_cadence": "How often a given subscriber can respond, e.g. `once` (single response per subscriber) or `unlimited`.",
+ "response_count": "The total number of responses this survey has received.",
+ "status": "The lifecycle status of the survey (e.g. `active`, `archived`).",
+ },
+ },
+ "tags": {
+ "description": "A tag that can be applied to subscribers for segmentation.",
+ "docs_url": "https://docs.buttondown.com/api-tags-list",
+ "columns": {
+ "color": "The hex color code associated with the tag.",
+ "creation_date": "The date and time at which the object was first created.",
+ "description": "An internal description of the tag, only visible to the newsletter author.",
+ "id": "A unique TypeID associated with the object.",
+ "name": "The name of the tag.",
+ "public_description": "A public-facing description of the tag, visible to subscribers in the subscriber portal.",
+ "secondary_id": "The secondary ID of the tag, used as a human-readable numeric identifier.",
+ "subscriber_editable": "If true, subscribers can add or remove this tag from their own profile via the subscriber portal.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/settings.py
new file mode 100644
index 000000000000..c73f904a3ea9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/settings.py
@@ -0,0 +1,69 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class ButtondownEndpointConfig:
+ name: str
+ path: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Server-side "created on/after" filter, when the endpoint has one. Only endpoints that expose
+ # it advertise incremental sync; the rest are full refresh.
+ incremental_start_param: str | None = None
+ # Value passed as `?ordering=`. Only set where the API documents `creation_date` as an accepted
+ # ordering value, so pagination walks a stable, monotonic column.
+ ordering: str | None = None
+ # Only consulted on incremental syncs: "asc" lets the pipeline checkpoint the watermark after
+ # every batch, so it is safe only where the request forces ascending order. Endpoints whose
+ # order we cannot force stay "desc", which defers the commit to the end of a successful job.
+ sort_mode: SortMode = "desc"
+ partition_key: str | None = "creation_date"
+
+
+BUTTONDOWN_ENDPOINTS: dict[str, ButtondownEndpointConfig] = {
+ "automations": ButtondownEndpointConfig(name="automations", path="/automations", sort_mode="asc"),
+ "comments": ButtondownEndpointConfig(name="comments", path="/comments", ordering="creation_date", sort_mode="asc"),
+ "emails": ButtondownEndpointConfig(
+ name="emails",
+ path="/emails",
+ incremental_start_param="creation_date__start",
+ ordering="creation_date",
+ sort_mode="asc",
+ ),
+ "events": ButtondownEndpointConfig(name="events", path="/events", ordering="creation_date", sort_mode="asc"),
+ "forms": ButtondownEndpointConfig(name="forms", path="/forms", ordering="creation_date", sort_mode="asc"),
+ "prices": ButtondownEndpointConfig(name="prices", path="/prices", sort_mode="asc", partition_key=None),
+ # `ordering` is documented on /subscribers but its accepted values are not enumerated, and an
+ # unrecognized value falls back to the default `-creation_date` rather than erroring. Rather
+ # than risk declaring an ascending sort the API silently ignores, take the documented default
+ # (newest first) and keep the watermark on the end-of-job commit path.
+ "subscribers": ButtondownEndpointConfig(
+ name="subscribers", path="/subscribers", incremental_start_param="date__start"
+ ),
+ # /survey_responses has no `ordering` param at all, so row order is undocumented.
+ "survey_responses": ButtondownEndpointConfig(
+ name="survey_responses", path="/survey_responses", incremental_start_param="creation_date__start"
+ ),
+ "surveys": ButtondownEndpointConfig(name="surveys", path="/surveys", ordering="creation_date", sort_mode="asc"),
+ "tags": ButtondownEndpointConfig(name="tags", path="/tags", sort_mode="asc"),
+}
+
+ENDPOINTS = tuple(BUTTONDOWN_ENDPOINTS.keys())
+
+# Only endpoints with a real server-side "created on/after" filter. Everything else stays full
+# refresh: /events and /comments carry a `creation_date` but expose no date filter, so an
+# "incremental" sync there would still page through the entire history on every run.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: [
+ {
+ "label": "creation_date",
+ "type": IncrementalFieldType.DateTime,
+ "field": "creation_date",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ]
+ for name, config in BUTTONDOWN_ENDPOINTS.items()
+ if config.incremental_start_param is not None
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/source.py
index d50f109e4053..19c4ca4d4b4e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/source.py
@@ -1,13 +1,35 @@
-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.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.buttondown.buttondown import (
+ BUTTONDOWN_BASE_URL,
+ ButtondownResumeConfig,
+ buttondown_source,
+ validate_credentials as validate_buttondown_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.buttondown.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ 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.buttondown import (
ButtondownSourceConfig,
)
@@ -15,7 +37,12 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ButtondownSource(SimpleSource[ButtondownSourceConfig]):
+class ButtondownSource(ResumableSource[ButtondownSourceConfig, ButtondownResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ supported_versions = ("2026-04-01",)
+ default_version = "2026-04-01"
+ api_docs_url = "https://docs.buttondown.com/api-changelog"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BUTTONDOWN
@@ -26,7 +53,87 @@ class ButtondownSource(SimpleSource[ButtondownSourceConfig]):
name=SchemaExternalDataSourceType.BUTTONDOWN,
category=DataWarehouseSourceCategory.MARKETING___EMAIL,
label="Buttondown",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Buttondown API key to sync your newsletter data into the PostHog data warehouse.
+
+You can find your API key on the [API page](https://buttondown.com/requests) in your Buttondown settings.
+""",
iconPath="/static/services/buttondown.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/buttondown",
+ keywords=["newsletter", "email marketing", "subscribers"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.buttondown.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ f"401 Client Error: Unauthorized for url: {BUTTONDOWN_BASE_URL}": "Your Buttondown API key is invalid or has been revoked. Create a new key on the API page in your Buttondown settings, then reconnect.",
+ f"403 Client Error: Forbidden for url: {BUTTONDOWN_BASE_URL}": "Your Buttondown API key cannot read this data. Check the key on the API page in your Buttondown settings, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: ButtondownSourceConfig,
+ 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, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: ButtondownSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ is_valid, status_code = validate_buttondown_credentials(config.api_key, self.resolve_api_version(api_version))
+ if is_valid:
+ return True, None
+
+ # A 403 means the key is real but the account cannot read this endpoint, so it must not block
+ # source creation; only re-raise it when validating one specific table.
+ if status_code == 403 and schema_name is None:
+ return True, None
+
+ return False, "Invalid Buttondown API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ButtondownResumeConfig]:
+ return ResumableSourceManager[ButtondownResumeConfig](inputs, ButtondownResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ButtondownSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ButtondownResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return buttondown_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ api_version=self.resolve_api_version(inputs.api_version),
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,
+ should_use_incremental_field=inputs.should_use_incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/tests/test_buttondown.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/tests/test_buttondown.py
new file mode 100644
index 000000000000..f34147879611
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/tests/test_buttondown.py
@@ -0,0 +1,262 @@
+import json
+from datetime import date, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from requests import PreparedRequest, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.buttondown.buttondown import (
+ BUTTONDOWN_API_VERSION,
+ BUTTONDOWN_BASE_URL,
+ ButtondownResumeConfig,
+ _to_start_date,
+ buttondown_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.buttondown.settings import BUTTONDOWN_ENDPOINTS
+
+# RESTClient builds its session via make_tracked_session in the rest_client module.
+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+BUTTONDOWN_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.buttondown.buttondown.make_tracked_session"
+)
+
+
+def _response(results: list[dict[str, Any]] | None, next_url: str | None = None, *, drop_results: bool = False):
+ body: dict[str, Any] = {"count": 1, "next": next_url, "previous": None}
+ if not drop_results:
+ body["results"] = results or []
+ response = Response()
+ response.status_code = 200
+ response._content = json.dumps(body).encode()
+ return response
+
+
+def _make_manager(resume_state: ButtondownResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+class _Wired:
+ def __init__(self) -> None:
+ self.params: list[dict[str, Any]] = []
+ self.urls: list[str] = []
+ self.auths: list[Any] = []
+
+
+def _wire(session: mock.MagicMock, responses: list[Response]) -> _Wired:
+ # `request.params`/`request.url` are mutated in place across pages, so snapshot them when each
+ # request is prepared rather than reading the final state after the run.
+ session.headers = {}
+ wired = _Wired()
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ wired.params.append(dict(request.params or {}))
+ wired.urls.append(request.url)
+ wired.auths.append(request.auth)
+ return mock.MagicMock(url=request.url)
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return wired
+
+
+def _rows(source_response) -> list[dict[str, Any]]:
+ return [row for page in source_response.items() for row in page]
+
+
+def _run(endpoint: str, responses: list[Response], manager: mock.MagicMock | None = None, **kwargs):
+ with mock.patch(CLIENT_SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ wired = _wire(session, responses)
+ response = buttondown_source(
+ "bd-key",
+ endpoint,
+ team_id=1,
+ job_id="job",
+ resumable_source_manager=manager or _make_manager(),
+ **kwargs,
+ )
+ rows = _rows(response)
+ return rows, wired, response, session
+
+
+class TestButtondownTransport:
+ def test_follows_next_link_until_null(self) -> None:
+ page_two = f"{BUTTONDOWN_BASE_URL}/subscribers?page=2"
+ rows, wired, _, _ = _run(
+ "subscribers",
+ [_response([{"id": "a"}], next_url=page_two), _response([{"id": "b"}], next_url=None)],
+ )
+
+ assert [row["id"] for row in rows] == ["a", "b"]
+ assert wired.urls[1] == page_two
+ # The next link is self-contained; re-sending the original params would duplicate them.
+ assert wired.params[1] == {}
+
+ def test_checkpoints_only_while_a_next_page_remains(self) -> None:
+ page_two = f"{BUTTONDOWN_BASE_URL}/subscribers?page=2"
+ manager = _make_manager()
+ _run(
+ "subscribers",
+ [_response([{"id": "a"}], next_url=page_two), _response([{"id": "b"}], next_url=None)],
+ manager,
+ )
+
+ manager.save_state.assert_called_once_with(ButtondownResumeConfig(next_url=page_two))
+
+ def test_resumes_from_saved_next_url(self) -> None:
+ saved = f"{BUTTONDOWN_BASE_URL}/subscribers?page=7"
+ rows, wired, _, session = _run(
+ "subscribers",
+ [_response([{"id": "z"}], next_url=None)],
+ _make_manager(ButtondownResumeConfig(next_url=saved)),
+ )
+
+ assert wired.urls[0] == saved
+ assert session.send.call_count == 1
+ assert [row["id"] for row in rows] == ["z"]
+
+ def test_sends_token_prefixed_key_and_version_header(self) -> None:
+ _, wired, _, session = _run("subscribers", [_response([{"id": "a"}])])
+
+ prepared = PreparedRequest()
+ prepared.prepare(method="GET", url=f"{BUTTONDOWN_BASE_URL}/subscribers")
+ wired.auths[0](prepared)
+ # Buttondown rejects a "Bearer " prefix, so this is the difference between syncing and 401ing.
+ assert prepared.headers["Authorization"] == "Token bd-key"
+ assert session.headers.get("X-API-Version") == BUTTONDOWN_API_VERSION
+
+ def test_api_version_header_is_overridable(self) -> None:
+ _, _, _, session = _run("subscribers", [_response([{"id": "a"}])], api_version="2025-01-02")
+
+ assert session.headers.get("X-API-Version") == "2025-01-02"
+
+ @pytest.mark.parametrize(
+ "endpoint,expected_param",
+ [
+ ("subscribers", "date__start"),
+ ("emails", "creation_date__start"),
+ ("survey_responses", "creation_date__start"),
+ ],
+ )
+ def test_incremental_sync_sends_the_server_side_date_filter(self, endpoint: str, expected_param: str) -> None:
+ _, wired, _, _ = _run(
+ endpoint,
+ [_response([{"id": "a"}])],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 15, 30),
+ )
+
+ # One day back from the watermark: the docs don't say whether the bound is inclusive, and
+ # overlapping rows merge away while a missed day would be silent data loss.
+ assert wired.params[0][expected_param] == "2026-03-03"
+
+ @pytest.mark.parametrize("endpoint", ["subscribers", "emails", "survey_responses"])
+ def test_full_refresh_sends_no_date_filter(self, endpoint: str) -> None:
+ _, wired, _, _ = _run(
+ endpoint,
+ [_response([{"id": "a"}])],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime(2026, 3, 4),
+ )
+
+ assert not [key for key in wired.params[0] if key.endswith("__start")]
+
+ @pytest.mark.parametrize("endpoint", ["subscribers", "emails", "survey_responses"])
+ @pytest.mark.parametrize("watermark", [None, "not-a-date"], ids=["missing", "unparseable"])
+ def test_incremental_without_a_usable_watermark_sends_no_date_filter(self, endpoint: str, watermark: Any) -> None:
+ # The first incremental run has no stored cursor, and a bad cursor converts to None. Either
+ # way the filter must be dropped so the request backfills instead of asking for `__start=None`.
+ _, wired, _, _ = _run(
+ endpoint,
+ [_response([{"id": "a"}])],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ )
+
+ assert not [key for key in wired.params[0] if key.endswith("__start")]
+
+ @pytest.mark.parametrize("endpoint", sorted(BUTTONDOWN_ENDPOINTS))
+ def test_ordering_param_matches_the_endpoint_config(self, endpoint: str) -> None:
+ config = BUTTONDOWN_ENDPOINTS[endpoint]
+ _, wired, _, _ = _run(endpoint, [_response([{"id": "a"}])])
+
+ assert wired.params[0].get("ordering") == config.ordering
+
+ @pytest.mark.parametrize(
+ "endpoint",
+ sorted(name for name, config in BUTTONDOWN_ENDPOINTS.items() if config.incremental_start_param),
+ )
+ def test_ascending_sort_mode_is_backed_by_an_explicit_ordering(self, endpoint: str) -> None:
+ config = BUTTONDOWN_ENDPOINTS[endpoint]
+
+ # An "asc" watermark is checkpointed after every batch, so it is only safe when the request
+ # forces ascending order. Anything else must stay on the end-of-job commit path.
+ assert config.sort_mode == "desc" or config.ordering == "creation_date"
+
+ @pytest.mark.parametrize("endpoint", sorted(BUTTONDOWN_ENDPOINTS))
+ def test_source_response_shape_per_endpoint(self, endpoint: str) -> None:
+ config = BUTTONDOWN_ENDPOINTS[endpoint]
+ _, _, response, _ = _run(endpoint, [_response([{"id": "a"}])])
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == config.sort_mode
+ assert response.partition_keys == ([config.partition_key] if config.partition_key else None)
+
+ def test_missing_results_key_fails_loudly(self) -> None:
+ with pytest.raises(ValueError, match="matched nothing"):
+ _run("subscribers", [_response(None, drop_results=True)])
+
+ def test_empty_results_page_is_not_an_error(self) -> None:
+ rows, _, _, _ = _run("subscribers", [_response([])])
+
+ assert rows == []
+
+
+class TestToStartDate:
+ @pytest.mark.parametrize(
+ "value,expected",
+ [
+ (datetime(2026, 3, 4, 15, 30), "2026-03-03"),
+ (date(2026, 3, 4), "2026-03-03"),
+ ("2026-03-04T15:30:00Z", "2026-03-03"),
+ ("2026-03-04", "2026-03-03"),
+ ("2026-03-01", "2026-02-28"),
+ (None, None),
+ ("not-a-date", None),
+ ],
+ )
+ def test_formats_watermarks_as_dates(self, value: Any, expected: str | None) -> None:
+ assert _to_start_date(value) == expected
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code,expected",
+ [(200, (True, 200)), (401, (False, 401)), (403, (False, 403)), (500, (False, 500))],
+ )
+ def test_maps_probe_status_to_result(self, status_code: int, expected: tuple[bool, int]) -> None:
+ with mock.patch(BUTTONDOWN_SESSION_PATCH) as mock_session:
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)
+ assert validate_credentials("bd-key") == expected
+
+ def test_transport_failure_is_not_validated(self) -> None:
+ with mock.patch(BUTTONDOWN_SESSION_PATCH) as mock_session:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("bd-key") == (False, None)
+
+ def test_probe_sends_token_prefixed_key(self) -> None:
+ with mock.patch(BUTTONDOWN_SESSION_PATCH) as mock_session:
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
+ validate_credentials("bd-key")
+
+ url = mock_session.return_value.get.call_args.args[0]
+ headers = mock_session.return_value.get.call_args.kwargs["headers"]
+ assert url == f"{BUTTONDOWN_BASE_URL}/accounts/me"
+ assert headers["Authorization"] == "Token bd-key"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/tests/test_buttondown_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/tests/test_buttondown_source.py
new file mode 100644
index 000000000000..29ebef03b5de
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buttondown/tests/test_buttondown_source.py
@@ -0,0 +1,173 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.buttondown.buttondown import (
+ ButtondownResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.buttondown.settings import (
+ BUTTONDOWN_ENDPOINTS,
+ ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.buttondown.source import ButtondownSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.buttondown import (
+ ButtondownSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+VALIDATE_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.buttondown.source.validate_buttondown_credentials"
+)
+SOURCE_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.buttondown.source.buttondown_source"
+
+
+class TestButtondownSource:
+ def setup_method(self) -> None:
+ self.source = ButtondownSource()
+ self.team_id = 123
+ self.config = ButtondownSourceConfig(api_key="bd-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.BUTTONDOWN
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Buttondown"
+ assert config.label == "Buttondown"
+ assert config.category == DataWarehouseSourceCategory.MARKETING___EMAIL
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/buttondown.png"
+
+ field_names = [field.name for field in config.fields if isinstance(field, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_field_is_a_required_secret(self) -> None:
+ config = self.source.get_source_config
+ api_key_field = next(
+ field for field in config.fields if isinstance(field, SourceFieldInputConfig) and field.name == "api_key"
+ )
+
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+ assert api_key_field.required is True
+
+ def test_get_schemas_lists_every_endpoint(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ def test_only_endpoints_with_a_server_side_date_filter_advertise_incremental(self) -> None:
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ # Advertising incremental on an endpoint with no server-side filter would page the entire
+ # history on every run while claiming to be cheap.
+ for name, endpoint in BUTTONDOWN_ENDPOINTS.items():
+ expected = endpoint.incremental_start_param is not None
+ assert schemas[name].supports_incremental is expected
+ assert bool(schemas[name].incremental_fields) is expected
+
+ def test_incremental_fields_track_creation_date(self) -> None:
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ for name, endpoint in BUTTONDOWN_ENDPOINTS.items():
+ if endpoint.incremental_start_param is None:
+ continue
+ assert [field["field"] for field in schemas[name].incremental_fields] == ["creation_date"]
+
+ @pytest.mark.parametrize("names,expected", [(["emails"], ["emails"]), (["nope"], [])])
+ def test_get_schemas_filters_by_name(self, names: list[str], expected: list[str]) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=names)
+ assert [schema.name for schema in schemas] == expected
+
+ @pytest.mark.parametrize(
+ "probe_result,schema_name,expected",
+ [
+ ((True, 200), None, (True, None)),
+ ((False, 401), None, (False, "Invalid Buttondown API key")),
+ # A 403 means a real key that can't read one endpoint, so it must not block setup.
+ ((False, 403), None, (True, None)),
+ ((False, 403), "emails", (False, "Invalid Buttondown API key")),
+ ((False, None), None, (False, "Invalid Buttondown API key")),
+ ],
+ )
+ def test_validate_credentials(
+ self, probe_result: tuple[bool, int | None], schema_name: str | None, expected: tuple[bool, str | None]
+ ) -> None:
+ with mock.patch(VALIDATE_PATCH, return_value=probe_result) as mock_validate:
+ assert self.source.validate_credentials(self.config, self.team_id, schema_name) == expected
+
+ mock_validate.assert_called_once_with("bd-key", "2026-04-01")
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.buttondown.com/v1/subscribers?page=2",
+ "403 Client Error: Forbidden for url: https://api.buttondown.com/v1/emails",
+ ],
+ )
+ def test_auth_failures_are_non_retryable(self, observed_error: str) -> None:
+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.buttondown.com/v1/subscribers",
+ ],
+ )
+ def test_unrelated_failures_stay_retryable(self, observed_error: str) -> None:
+ assert not any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is ButtondownResumeConfig
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "emails"
+ inputs.team_id = 7
+ inputs.job_id = "job"
+ inputs.api_version = None
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-03-04T00:00:00Z"
+ manager = mock.MagicMock()
+
+ with mock.patch(SOURCE_PATCH) as mock_source:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "bd-key"
+ assert kwargs["endpoint"] == "emails"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-03-04T00:00:00Z"
+ # An unpinned source must still send the version this code was written against.
+ assert kwargs["api_version"] == "2026-04-01"
+
+ def test_source_for_pipeline_honors_a_pinned_api_version(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "emails"
+ inputs.api_version = "2025-01-02"
+
+ with mock.patch(SOURCE_PATCH) as mock_source:
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["api_version"] == "2025-01-02"
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+
+ assert set(descriptions.keys()) == set(ENDPOINTS)
+ for name, endpoint in BUTTONDOWN_ENDPOINTS.items():
+ for primary_key in endpoint.primary_keys:
+ assert primary_key in descriptions[name]["columns"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/buttondown.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/buttondown.py
index bc531a2a8cb1..f0556e6f441c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/buttondown.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/buttondown.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class ButtondownSourceConfig(config.Config):
- pass
+ api_key: str