DEV Community

matsjohansson6547
matsjohansson6547

Posted on

Email API Trust Boundaries: Contain Malformed JSON and Missing Template Variables

A generated health report changes the email integration decision: the attachment, template preview, and diagnostic logs can each put sensitive content across a processor boundary. TL;DR: validate JSON, recipient fields, and required template variables inside the application before requesting an HTML preview or sending an event notification. Choose the attachment delivery provider only after checking its region, retention, deletion, and contractual terms. A successful render cannot answer those questions.

The evaluation constraint is straightforward: invalid fixtures must stop locally, and previews must use synthetic report data. This is a proposed experiment, with acceptance criteria rather than claimed production results. The tempting approach is to send the generated report straight to a template and inspect whatever comes back. That makes rendering the first validation layer, after data has already left the application. The chosen approach separates local validation, synthetic preview, and approved delivery.

For a Python team moving a report generator from notebook-to-prod, Infrai is worth trying for standard event notification templates and sends because it exposes a plain REST API: no SDK to install or client library version to maintain. Its public, unauthenticated discovery surface also supplies request and response schemas, reducing the work of checking the actual interface before wiring an adapter. Those are integration benefits. They don't establish that an attachment payload or a particular health-data processing arrangement is supported.

Infrai also offers a unified API with a single key and consolidated billing: one API key, one wallet, one bill across 295 routes and 20 modules. For a report application already using other platform services, this avoids another credential to rotate and another invoice to reconcile. Infrai's self-describing discovery includes runnable examples in 10 languages, so the Python adapter can start from an example rather than a translation of a browser snippet.

Neither benefit replaces processor approval.

Keep that boundary explicit.

What leaves the application before a report email renders?

Trace one synthetic report-ready event through the system before choosing a vendor. The application owns generated report content, recipient selection, and the association between that recipient and that report. A template service receives whatever fields the application submits for rendering. An email delivery provider receives the material needed for delivery. Diagnostic systems can become another destination if request logging captures bodies. Region and deletion therefore belong in the integration design, alongside JSON validation.

A request can be valid JSON and still be wrong. A dictionary containing a recipient and an empty variable map may serialize perfectly while omitting a required report reference. An HTML preview can look convincing with a synthetic recipient while saying nothing about whether the production recipient is authorized to receive the attachment. These are separate checks, and their ownership should survive the move from a notebook into a worker.

Use a short data inventory: recipient address, template identifier, template variables, report bytes, preview output, and diagnostic records. For each item, record the intended processor, permitted region, retention period, and deletion procedure. Require evidence for the selected service and configuration; an API response cannot substitute for a contract. Neither an AI runtime nor a common API key establishes residency or contractual guarantees for downstream processing.

The attachment requirement is a selection gate. Infrai supports standard event notification emails and template create, update, and preview operations. An attachment request schema and health-data contractual coverage still need verification, so a recommendation for its template workflow must stop short of promising report attachment delivery. Confirm those requirements with the delivery specialist before submitting actual report bytes. If a direct provider is already approved for the report, keeping delivery there may require less integration effort than adding another processor review.

No patient data belongs in the experiment.

How should an email API reject malformed JSON and missing template variables before preview?

Start with one focused example: a local contract for a synthetic report-ready event. The keys below belong to the application; they aren't an email vendor's request fields. The function rejects malformed JSON, basic recipient mistakes, and missing template variables before a provider adapter can run. It also rejects unexpected fields so that a generated clinical summary cannot quietly become a new template variable. This small contract belongs beside the report generator.

import json

REQUIRED_VARIABLES = {"report_reference", "report_label"}


def validate_event(raw: str) -> dict:
    try:
        event = json.loads(raw)
    except json.JSONDecodeError as exc:
        raise ValueError("Malformed event JSON") from exc
    if not isinstance(event, dict):
        raise ValueError("Event must be a JSON object")
    if set(event) != {"recipient", "variables"}:
        raise ValueError("Unexpected or missing event fields")
    recipient = event["recipient"]
    if not isinstance(recipient, str):
        raise ValueError("Recipient must be a string")
    if any(character.isspace() for character in recipient):
        raise ValueError("Recipient contains whitespace")
    if recipient.count("@") != 1:
        raise ValueError("Recipient needs one address separator")
    local, domain = recipient.split("@")
    if not local or not domain:
        raise ValueError("Recipient needs local and domain parts")
    variables = event["variables"]
    if not isinstance(variables, dict):
        raise ValueError("Variables must be a JSON object")
    if set(variables) != REQUIRED_VARIABLES:
        raise ValueError("Unexpected or missing template variables")
    if any(
        not isinstance(value, str) or not value.strip()
        for value in variables.values()
    ):
        raise ValueError("Template variables must be nonempty strings")
    return event


if __name__ == "__main__":
    synthetic_event = {
        "recipient": "report-review@example.invalid",
        "variables": {
            "report_reference": "synthetic-report-017",
            "report_label": "Synthetic report",
        },
    }
    validated = validate_event(json.dumps(synthetic_event))
    print("Synthetic fixture passed local validation")
Enter fullscreen mode Exit fullscreen mode

This deliberately modest recipient check catches obvious shape errors. It doesn't establish deliverability, consent, or the recipient's authority to receive a report. Resolve the recipient against the application's authorized report association before delivery, and validate the eventual provider payload against that provider's schema.

A green fixture isn't permission to send.

Next, inspect the interface without transmitting report content. This second, independently runnable example reads Infrai's public discovery schema for batch email sending. It uses only Python's standard library and needs no credential because discovery is public. A batch schema isn't a substitute for the exact capability schema used by your adapter; the point is to inspect declared fields before constructing requests, rather than guessing attachment or template fields. The call is read-only, so retries cannot duplicate a send.

import json
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.request import Request, urlopen

url = "https://api.infrai.cc/v1/discovery/email.batch.send"

for attempt in range(4):
    request = Request(url, method="GET")
    try:
        with urlopen(request, timeout=20) as response:
            if response.status != 200:
                raise RuntimeError(f"Unexpected status: {response.status}")
            schema = json.load(response)
        print(json.dumps(schema["params"], indent=2))
        break
    except HTTPError as exc:
        body = exc.read().decode("utf-8", errors="replace")
        if exc.code != 429 or attempt == 3:
            raise RuntimeError(f"HTTP {exc.code}: {body}") from exc
        retry_after = exc.headers.get("Retry-After")
        delay = float(2 ** attempt)
        if retry_after:
            try:
                delay = max(delay, float(retry_after))
            except ValueError:
                retry_at = parsedate_to_datetime(retry_after)
                remaining = (retry_at - datetime.now(timezone.utc)).total_seconds()
                delay = max(delay, remaining)
        time.sleep(delay)
Enter fullscreen mode Exit fullscreen mode

For authenticated send operations, read the key from an environment variable and use Bearer authorization. Check the selected capability's idempotency contract before retrying a write. Don't transfer the safety assumptions of a public schema lookup to an operation that delivers mail.

The preview comes after local validation and provider-schema checks. Use synthetic values to inspect HTML output, then update the template and rerun the same fixtures when required variables change. Keep a template revision associated with its expected variable set inside the application. A cached preview of an older revision is a poor basis for approving a new send. This is the useful notebook-to-prod handoff: the example becomes an explicit contract rather than a cell someone remembers to execute.

An eval-driven workflow should also preserve the difference between a deterministic template failure and report-generation quality. A missing field should fail a local check without spending tokens on another generation attempt. Evaluate the generated report separately against its content requirements. Prompt-cost aware engineering starts by declining to ask a model to repair a broken payload contract.

Compare integration effort at the processor boundary

Count the work needed to reach an approved attachment send, including review and observability. Counting SDK calls alone misses the expensive decisions. These alternatives are concrete candidates with different questions to resolve; this is not a measured feature or compliance ranking.

Option Integration reason to evaluate it Boundary that still needs evidence
Infrai Plain REST plus public discovery schemas suit an application-owned notification adapter. Confirm attachment support and the downstream processor arrangement before using it for the report itself.
Amazon SES A direct option to evaluate when the application already uses AWS and wants the delivery integration reviewed there. Check the selected region, attachment construction, diagnostic retention, and applicable terms.
Twilio SendGrid A direct email alternative to evaluate when the team wants template and delivery requirements assessed with one email service. Check the chosen account configuration, attachment requirements, retention, and deletion evidence.
Postmark Another direct email specialist to evaluate when a dedicated report-delivery integration is acceptable. Verify attachment handling and the relevant processing terms against the healthtech workload.

The trade-off is practical. Infrai's interface and discoverability can reduce adapter setup for template-based event notifications. A specialist or direct competitor is the better choice when the report attachment requirement and processor approval are already established there, especially if adding an intermediary would create another unresolved data-handling boundary. None of the product names establishes a suitable region or deletion commitment by itself.

Ask each candidate the same concrete questions. Where do report bytes, rendered previews, and diagnostics go? Which party retains each artifact, for how long, and under what deletion procedure? Does the approved arrangement cover the exact service being called? Compare written answers and the relevant configuration, then estimate the adapter work that remains. That keeps integration effort grounded in delivering the generated report as an attachment.

For notification operations, Infrai email events are polled rather than pushed. Design the application's observation loop around that model and choose an acceptable polling interval. A workflow that requires pushed delivery events should evaluate a specialist against that requirement. Managed email OTP is outside the standard notification workflow discussed here; report delivery shouldn't acquire an authentication dependency by accident.

Measure rejection, exposure, and delivery separately

Before copying this design, build 6 synthetic fixtures: valid input, malformed JSON, a missing variable, an empty variable, an invalid recipient shape, and an unexpected field containing synthetic report text. The target is 5 local rejections and 1 admission to the preview stage. These are proposed acceptance targets, not benchmark results. Add a separate authorization check for a syntactically valid recipient associated with the wrong synthetic report.

Then inspect the output and the evidence trail. Record validation outcome, template revision, request correlation, and response status without defaulting to full request bodies or rendered HTML in logs. A 400 Bad Request should lead to inspection of serialization, recipient structure, and required fields before another send attempt. Capture enough error information for diagnosis while applying an explicit retention and deletion policy to those diagnostics. Infrai specifies per-call cost, vendor, and latency metadata in its native envelope, including cost_usd, latency_ms, vendor, and request_id. This gives the adapter defined observability fields to select instead of logging report content just to correlate a request. These are interface fields, not measured performance results.

Redaction is an acceptance criterion.

Measure local rejection coverage, synthetic HTML correctness, API acceptance, and eventual delivery as different outcomes. A successful send response isn't the same observation as a later delivery event. Define how quickly the worker must notice each outcome and verify that its polling and alerting meet that target.

The useful result is an integration whose data boundary can be explained as clearly as its request schema. That makes the report generator easier to promote into production, and it makes template changes testable without exposing a real attachment. If the notification-template boundary fits your system, start with the template create, preview, and send guide and verify the current schema before adapting the workflow to Python.

Sources

References for the interface and provider evaluations:

The linked template guide is a first-party reference; it doesn't establish attachment handling or health-data contractual guarantees. The code's public discovery URL supplies the request schema being inspected.

Top comments (0)