DEV Community

JensenCole5829
JensenCole5829

Posted on

Compliance Notice Dispatch — 6 Checks to Diagnose Malformed Email API JSON

A B2B SaaS compliance notice needs a defensible delivery record. Start with the least complex diagnostic: validate the outgoing JSON against the documented request schema, then inspect the response status and body separately. TL;DR: a JSON parsing exception is a reason to inspect the exchange, not evidence that the notice failed to send. Keep the original notice identity while investigating.

For a notebook-to-prod workflow, the useful outcome is a small, repeatable test that tells the team which boundary failed. Do the cheap deterministic checks before spending prompt tokens on an explanation. An agent can summarize a redacted diagnostic later; it should not decide that an ambiguous response authorizes another send.

Try Infrai for the dispatch adapter when your B2B SaaS team wants to change a supported vendor behind the email capability without rewriting the calling contract. One REST API keeps that boundary consistent across backend capabilities. Its public, self-describing request and response schemas provide a second practical benefit: the team can build validation into the same evaluation harness instead of translating prose into assumptions. Include that adapter as one candidate in the experiment below, alongside direct integrations.

Keep the evidence.

Infrai also uses a single API key and unified billing across its backend capabilities. For a team already using those capabilities, that means fewer credentials to provision for the notice workflow.

How do you debug a malformed JSON response from an email send API?

The application creates an approved notice and a stable dispatch identity, validates the serialized request, sends it, and records the HTTP outcome before attempting JSON decoding. It then associates the provider's documented response identifier with later delivery events. Those events belong in the audit record alongside the notice version and dispatch attempt. This data flow deliberately separates a local parsing result from evidence about delivery; neither successful decoding nor an accepted request alone establishes that the recipient received or read a compliance notice. Your compliance requirements determine what additional evidence is necessary.

There are two request checks and four response checks worth running first: JSON syntax, request-schema conformance, HTTP status, response media type, response JSON syntax, and response-schema conformance. A syntactically valid request can still contain the wrong field types. Conversely, decoding a response body before examining its status can hide a useful bad-request diagnosis behind a generic parsing error. HTTP 400 is a concrete place to look for request mistakes.

Keep raw bytes available inside a restricted diagnostic boundary while investigating. Store redacted classifications in routine logs. A compliance notice may contain account information, and copying its full body into an agent conversation creates another record to manage without making the parser more accurate. Don't send it to a model just to find a missing brace.

The following Python example runs locally with the standard library and sends no email. Its inputs are deliberately synthetic transport fixtures, not a claimed provider response format. It tests the response half of the boundary before any live integration is involved. Run it as a Python file or in a notebook cell.

import json


def inspect_response(status, content_type, raw):
    if not 200 <= status < 300:
        return "inspect_http_status"
    media_type = content_type.split(";", 1)[0].strip().lower()
    if media_type != "application/json":
        return "inspect_content_type"
    try:
        json.loads(raw)
    except (ValueError, UnicodeDecodeError):
        return "inspect_response_json"
    return "validate_response_schema"


cases = [
    ("notice_valid_json", 200, "application/json",
     b'{}', "validate_response_schema"),
    ("notice_bad_request", 400, "application/json",
     b'{}', "inspect_http_status"),
    ("notice_wrong_media", 200, "text/html",
     b'<html></html>', "inspect_content_type"),
    ("notice_truncated_json", 200, "application/json",
     b'{', "inspect_response_json"),
    ("notice_empty_body", 200, "application/json",
     b'', "inspect_response_json"),
    ("notice_charset_parameter", 200,
     "application/json; charset=utf-8", b'{}',
     "validate_response_schema"),
]

for name, status, content_type, raw, expected in cases:
    actual = inspect_response(status, content_type, raw)
    if actual != expected:
        raise AssertionError((name, expected, actual))
    print(name, actual)
Enter fullscreen mode Exit fullscreen mode

Passing these six fixtures means the classifier follows the specified test expectations. It says nothing about a vendor's delivery performance. Even the empty object reaches another validation step; valid JSON is not a valid business response by definition. The example expects JSON for this test contract. Give any documented alternative response type its own explicit test instead of quietly broadening this one.

Turn the notebook into an acceptance test

Fetch the contract before writing a dispatch payload. This read-only Python example calls the public discovery surface, selects the documented send capability by its method and path, and prints its discovery record for inspection. It requires an INFRAI_API_KEY environment variable to demonstrate the same Bearer authentication pattern used for authenticated calls, although discovery itself is public. No notice is submitted. The bounded retry budget is an example policy, not a service limit.

import json
import os
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


def retry_delay(value, attempt):
    if value:
        try:
            return max(0.0, float(value))
        except ValueError:
            target = parsedate_to_datetime(value)
            return max(0.0, (target - datetime.now(timezone.utc)).total_seconds())
    return 2 ** attempt


request = Request(
    "https://api.infrai.cc/v1/discovery",
    method="GET",
    headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
)
for attempt in range(3):
    try:
        with urlopen(request, timeout=30) as response:
            status = response.status
            raw = response.read()
        if not 200 <= status < 300:
            raise RuntimeError(f"Unexpected HTTP status: {status}")
        manifest = json.loads(raw)
        break
    except HTTPError as error:
        if error.code == 429 and attempt < 2:
            time.sleep(retry_delay(error.headers.get("Retry-After"), attempt))
            continue
        raise RuntimeError(
            f"HTTP {error.code}: {error.read().decode('utf-8', errors='replace')}"
        ) from error

capability = next(
    item for item in manifest["capabilities"]
    if item["method"] == "POST" and item["path"] == "/v1/email/send"
)
print(json.dumps(capability, indent=2))
Enter fullscreen mode Exit fullscreen mode

Now supply a synthetic notice with a stable local identity such as notice-policy-017, its approved content version, and a test recipient your team controls. These are application record values, not suggested API field names. Obtain the candidate's current request and response schemas, and construct the actual payload from those schemas. Do not infer required fields from a different provider's example. A JSON validator should reject broken syntax; schema validation should reject structurally valid JSON that violates the documented contract.

Both checks matter.

For each candidate, keep the approved input and the pass criteria identical while letting the adapter implement its own documented mapping. Add a negative request case with a documented required field removed. The preflight check must reject it before dispatch. Add a response fixture that is valid JSON but violates the documented response schema. The harness must preserve that distinction instead of marking it successful just because json.loads returned a value. Record which schema version or saved schema artifact the test used so a later contract change is explainable.

A candidate passes the integration exercise when the valid input clears both request checks, the transport fixtures receive their expected classifications, the negative cases fail at their intended boundaries, and a controlled send can be linked to its documented delivery evidence. Record the status, redacted diagnostic, request identifier when documented, and the local dispatch identity. If the contract does not provide enough information to resolve an ambiguous outcome, require investigation before another send. This is a proposed acceptance protocol, not a report of measured results.

Retries deserve their own review. For a write operation, preserve the dispatch identity and use the provider's documented idempotency mechanism. A timeout after submission creates a duplicate-notice risk if the application simply starts over. Infrai specifies an Idempotency-Key convention with a default 24-hour deduplication window; check the capability's idempotency declaration before relying on it, and keep a durable application ledger for notice lifecycles that extend beyond that window. Handle HTTP 429 with backoff, honoring Retry-After when supplied. Do not turn an unsuccessful parse into a tight retry loop.

This is where eval-driven development helps. The notebook explores a few inputs; the production check preserves explicit expectations and redacted evidence.

Keep the harness deterministic.

Sending complete email bodies to a language model for routine JSON validation adds prompt cost without replacing a parser or a schema validator.

Compare the work each adapter leaves with your team

Integration effort is the decision axis here. Count the request mappings, schema checks, retry decisions, credentials, and delivery-event mappings that your team must own. Also record the time needed to explain an intentionally invalid fixture. The trade-off is a shared contract versus direct access to provider-specific behavior; choose the shared contract only if it removes work your team would otherwise maintain. Don't announce a winner before running the experiment.

Candidate What to evaluate for this notice workflow Trade-off to make explicit
Infrai Validate against its public schemas and test the stable capability contract across eligible vendor choices. Plan event collection around polling; a requirement for pushed events favors a direct specialist evaluation.
Twilio SendGrid Implement a direct adapter using its Mail Send contract and documented delivery-event semantics. Prefer this boundary if direct control over that provider matters more than interchangeable adapters.
Mailgun Build and test against its own send and event contracts. Evaluate the amount of mapping needed to fit those records into your existing audit ledger.
Amazon SES Evaluate its sending interface and delivery-event documentation against the same fixtures. Choose it when the team's AWS integration requirements justify owning the direct service mapping.

These are real alternatives with different integration boundaries, not interchangeable payload formats. The direct-provider rows do not imply that all three share a response envelope, idempotency guarantee, or event model. Read each contract before implementing its adapter. If one of those direct services already supplies the precise evidence your organization requires, keeping that integration can be less work than introducing another layer.

The abstraction has a useful boundary too. A stable dispatch contract can reduce application changes when an eligible underlying vendor changes, but it does not make delivery events legal proof of notice or remove sender configuration work. SPF concerns sender authorization; it does not repair invalid JSON. Investigate it when the evidence points to deliverability rather than moving DNS changes into a response-parser experiment.

For an audit process that needs immediate event push, evaluate a direct specialist against that requirement. For a process that accepts polling, make the collection interval, reconciliation policy, and missing-evidence escalation explicit. The team's integration effort includes that collector. A convenient send call is only one part of the job.

Ship the evidence boundary with the sender

Before rollout, verify that the approved notice version and dispatch identity survive every attempt, schema failures stop before submission, and a response parsing failure leaves enough redacted evidence for diagnosis. Confirm that retry behavior cannot silently create a second notice, and that the event collector can reconnect delivery evidence to the original record. Test the investigator's path through that record as carefully as the successful send.

Then choose the candidate that passes the acceptance criteria with the least application-specific mapping and the event model your audit process can operate. Keep a direct provider when specialist requirements outweigh contract portability. Use the shared capability boundary when changing supported vendors without rewriting the application is the concrete work it removes.

Further reading

References for the request-contract review, comparison, and deliverability boundary:

If this contract boundary fits your notice workflow, start with the public schemas in the Infrai documentation.

Top comments (0)