Skip to main content

Build a Consent-First beehiiv Signup Payload in Python

Updated 6 min readMarkdown

Try this before connecting a newsletter form to an API: paste the string "false" into a Python truthiness check. It returns true. Now imagine that check is the only thing between an unchecked box and a subscription request.

Newsletter integrations have another consequential choice: whether an ordinary signup request can reactivate somebody who already unsubscribed. That decision should be visible in code review.

Affiliate disclosure: This tutorial contains a beehiiv affiliate link. I may earn a commission from an eligible purchase. AI was used for research, writing, and code. The example is an offline demonstration with fictional data, not a live integration.

We will build an offline request object that requires confirmation and never requests automatic reactivation. You can inspect its output and run its tests without enrolling a subscriber.

Make the subscription decisions explicit

beehiiv documents a create subscription endpoint. Two options deserve particular care: reactivate_existing and double_opt_override. The API allows control over reactivation and confirmation; our application should choose deliberately.

For this example, the form offers one clearly named newsletter. A new signup must explicitly request that newsletter. The payload requires confirmation, declines reactivation, and does not request a welcome message. That last choice only controls this request field; it is not a guarantee that other configured automations or publication emails remain silent.

An existing unsubscribed reader needs a separate, deliberate resubscription workflow. This small builder cannot establish that a browser visitor owns the address, so it never requests reactivation.

Accept a source key rather than arbitrary campaign data

The API accepts acquisition fields such as utm_source, utm_medium, and utm_campaign. Letting a client submit any values makes reporting easy to manipulate, even accidentally.

Here, the application accepts a source key that maps to a server-owned campaign. The key remains a claim about where the request came from. A production endpoint should derive or validate it using its own route and session context; a dictionary alone does not prove provenance.

Keep the same discipline for consent. This local Python expression illustrates the trap:

bool("false")  # True because the string is nonempty

Strictly accepting the boolean True avoids that type-confusion bug. It does not prove consent: a malicious client can submit True too. The service still needs a clear form promise, abuse protection, and a retained record of when and to what the person opted in.

Build a request you can inspect

Save this as signup_payload.py. It uses only the Python standard library. The fictional source labels are application choices, not beehiiv defaults.

import json
import re

# Server-owned attribution: never accept arbitrary campaign values from clients.
SOURCES = {
    "guide": ("website", "organic", "owner_guide"),
    "event": ("workshop", "offline", "newsletter_signup"),
}


def build_payload(email, *, consent, source):
    if consent is not True:
        raise ValueError("affirmative newsletter opt-in is required")
    if not isinstance(email, str):
        raise ValueError("email must be text")
    email = email.strip()
    # A deliberately limited ASCII demo, not a complete email parser.
    if not email.isascii() or not re.fullmatch(r"[^\s@]+@[^\s@]+\.[^\s@]+", email):
        raise ValueError("unsupported address format")
    local, domain = email.split("@")
    if not isinstance(source, str) or source not in SOURCES:
        raise ValueError("unrecognized signup source")
    utm_source, utm_medium, utm_campaign = SOURCES[source]
    return {
        "email": local + "@" + domain.lower(),
        "reactivate_existing": False,
        "send_welcome_email": False,
        "double_opt_override": "on",
        "utm_source": utm_source,
        "utm_medium": utm_medium,
        "utm_campaign": utm_campaign,
    }


if __name__ == "__main__":
    payload = build_payload(
        "Reader@EXAMPLE.COM", consent=True, source="guide"
    )
    print(json.dumps(payload, indent=2, sort_keys=True))

Run python3 signup_payload.py. The output includes Reader@example.com, double_opt_override set to on, and both boolean options set to false.

The domain is lowercased while the local part is preserved. That choice follows the distinction discussed in RFC 5321. The regular expression accepts a limited ASCII subset. It can reject legitimate addresses and does not prove that a domain or mailbox exists. Use a suitable maintained parser when the application needs broader syntax support.

Run the local checks

Save the example as signup_payload.py. The following standard-library tests check confirmation, reactivation, address normalization, strict consent types, and the closed set of source keys.

import unittest
from signup_payload import build_payload


class SignupPayloadTests(unittest.TestCase):
    def test_safe_defaults(self):
        payload = build_payload("Reader@EXAMPLE.COM", consent=True, source="guide")
        self.assertEqual(payload["email"], "Reader@example.com")
        self.assertEqual(payload["double_opt_override"], "on")
        self.assertFalse(payload["reactivate_existing"])
        self.assertFalse(payload["send_welcome_email"])
        self.assertEqual(payload["utm_campaign"], "owner_guide")

    def test_non_boolean_consent(self):
        for value in ("false", "true", 1, None, False):
            with self.subTest(value=value), self.assertRaises(ValueError):
                build_payload("reader@example.com", consent=value, source="guide")

    def test_unrecognized_source(self):
        with self.assertRaises(ValueError):
            build_payload("reader@example.com", consent=True, source="arbitrary")


if __name__ == "__main__":
    unittest.main()

Save the tests as test_signup_payload.py and run python3 -m unittest -v in the same directory.

The case involving numeric 1 matters because Python considers it equal to True in an equality comparison. The builder uses identity to require the boolean itself. Test "true" and None too; their meanings should never depend on a language's truthiness rules.

Another test checks the entire key set. An unrelated feature should not quietly add a premium tier, an automation, or another list to this newsletter signup request.

Add HTTP after the local contract is clear

Keep credentials on the server and scope access to the intended publication. Do not expose a bearer token in browser code. Validate the request before calling the API and avoid recording raw addresses or tokens in routine logs.

If a request times out after beehiiv accepted it, its outcome is uncertain. Do not assume the remote action failed or promise that a blind retry is harmless. Design reconciliation against the documented API behavior, particularly before allowing welcome emails or automation enrollment.

Inspect the returned subscription state rather than equating HTTP success with a confirmed reader. beehiiv's double opt-in guide explains the confirmation step. Reconcile existing subscriptions and returned warnings without returning private subscriber details to an anonymous caller.

The acceptable use policy requires affirmative consent and restricts re-adding unsubscribed people. A valid address and a successful API response are insufficient evidence of that consent.

Know what the passing tests establish

The local tests exercise payload construction. They do not test authentication, account eligibility, rate limits, confirmation delivery, webhook behavior, or your publication's welcome settings. Those require separate integration tests with controlled addresses and an authorized account.

The code review question is now concrete: can any ordinary signup path request reactivation or skip confirmation? In this builder, both choices are explicit. Keep them explicit when you add authentication, persistence, and HTTP; a refactor should not quietly change the relationship the reader is joining.

3 views

About the author

  • I’m Pratham Malhotra, founder of SaaSFolio (saasfolio.tech), where I track SaaS pricing and deals. Here I publish hands-on guides to SaaS analytics, developer tools and web hosting, with runnable code, real costs and honest trade-offs. Some posts contain affiliate links, and I always disclose them.

No comments yet. Be the first to comment.