Sub topic 11
Connecting Workflows to CMS, Email, and Analytics Tools
This chapter assumes you have read the earlier chapters on structured output and chaining steps. You should be comfortable with a workflow that takes named inputs, runs steps, and returns validated JSON. Here you connect that workflow to the systems where marketing work lives: a content management system (CMS), an email platform, and an analytics tool.
Why integration is a separate concern
A workflow that ends with text in a chat window still needs a person to copy it somewhere. Integration removes that copy step. It also adds risk, because a bad output can now publish, send, or overwrite something.
The safest design keeps the model away from the tools. The model produces a validated draft. Ordinary code then decides what to do with that draft. This split has three benefits:
- The model never holds credentials, so a bad prompt cannot leak them.
- The tool call is plain code that you can test without calling a model.
- You can swap the model, or the tool, without rewriting the other half.
Three directions of data flow
Integrations move data in one of three ways. Naming the direction first makes the design choices clearer.
| Direction | Example | Main risk |
|---|---|---|
| Read into the workflow | Pull last week's campaign metrics from analytics | Stale or partial data produces a wrong summary |
| Write out of the workflow | Create a draft blog post in the CMS | A bad draft is published or overwrites live content |
| Both | Read subscriber segments, write a segmented send | Personal data enters the prompt |
Reads are low risk for the outside system but high risk for output quality. If the model summarizes numbers it was never given, it will invent them. Writes are the opposite. The content may be fine, but the action may be hard to undo.
Choose the integration method
Most marketing tools offer at least one of these ways in.
- Native API. The tool exposes an HTTP interface with documented endpoints. This is the most flexible and the one this chapter uses.
- Automation platform. A no-code service connects a trigger (a new row, a form submission) to an action. It is quick to set up but harder to version and test.
- File exchange. The workflow writes a CSV or Markdown file to a shared folder, and the tool imports it. It is crude but needs no credentials and is easy to audit.
Choose by asking what happens when something goes wrong. If you can tolerate a manual retry, file exchange is enough. If you need a record of every call, use the API and log each request.
Build an adapter layer
An adapter is a small function that turns your validated output into the format one tool expects. Keep one adapter per tool. The workflow never knows the tool's field names.
The example below maps the validated email draft from the structured-output chapter to a request for a hypothetical email platform. It creates a draft, not a send.
import json
import os
import urllib.request
API_BASE = "https://api.example-email.test/v1"
def to_email_payload(draft, list_id):
return {
"list_id": list_id,
"subject": draft["subject"],
"preview_text": draft["preview_text"],
"html_body": draft["body"],
"status": "draft", # never "scheduled" or "sent" from this adapter
}
def create_email_draft(draft, list_id):
payload = to_email_payload(draft, list_id)
request = urllib.request.Request(
f"{API_BASE}/campaigns",
data=json.dumps(payload).encode("utf-8"),
headers={
"Authorization": f"Bearer {os.environ['EMAIL_API_KEY']}",
"Content-Type": "application/json",
},
method="POST",
)
with urllib.request.urlopen(request, timeout=15) as response:
return json.load(response)Three details matter here:
- The status is hard-coded to
draft. The workflow cannot send, even if a prompt or a bug tries to. - The API key comes from an environment variable, not from the code or the prompt.
- The request has a timeout, so a slow service does not hang the whole run.
Because to_email_payload is a pure function, you can test it with a fixed draft and no network access.
Connect to a CMS
A CMS integration usually creates or updates a post. Two rules prevent most accidents.
First, write drafts only. Most CMS APIs accept a status field. Create content as draft or pending review and let a human publish it.
Second, make writes idempotent. An idempotent write gives the same result if you run it twice. Without it, a retry after a network error creates a duplicate post. The usual fix is to give each piece of content a stable key, such as a slug or an external ID, and look it up before creating.
import json
import os
import urllib.parse
import urllib.request
CMS_BASE = "https://cms.example.test/api"
def _call(method, path, body=None):
data = json.dumps(body).encode("utf-8") if body is not None else None
request = urllib.request.Request(
CMS_BASE + path,
data=data,
headers={
"Authorization": f"Bearer {os.environ['CMS_API_KEY']}",
"Content-Type": "application/json",
},
method=method,
)
with urllib.request.urlopen(request, timeout=15) as response:
return json.load(response)
def upsert_draft_post(slug, title, body_markdown):
query = urllib.parse.urlencode({"slug": slug})
existing = _call("GET", f"/posts?{query}")
payload = {
"slug": slug,
"title": title,
"body": body_markdown,
"status": "draft",
}
if existing.get("items"):
post_id = existing["items"][0]["id"]
return _call("PUT", f"/posts/{post_id}", payload)
return _call("POST", "/posts", payload)Running upsert_draft_post twice with the same slug updates one draft instead of creating two. If a draft was already published, check the existing status before the PUT. Otherwise a rerun could overwrite live copy with a new draft.
Read from analytics
Analytics is where the workflow gets its facts. The goal is to give the model verified numbers and ask it only to describe them.
- Fetch the metrics with code, not with the model.
- Validate them: check that required fields exist, that the date range matches the request, and that values are plausible.
- Compute any derived numbers in code, such as week-over-week change.
- Pass the final numbers into the prompt and instruct the model to use only those figures.
def summarize_inputs(metrics):
required = ["period", "sessions", "prev_sessions", "signups"]
missing = [key for key in required if key not in metrics]
if missing:
raise ValueError(f"Analytics response is missing: {missing}")
if metrics["prev_sessions"] <= 0:
raise ValueError("Previous period has no sessions; cannot compute change")
change = (metrics["sessions"] - metrics["prev_sessions"]) / metrics["prev_sessions"]
return {
"period": metrics["period"],
"sessions": metrics["sessions"],
"signups": metrics["signups"],
"sessions_change_pct": round(change * 100, 1),
}
print(summarize_inputs(
{"period": "2026-W47", "sessions": 5400, "prev_sessions": 4800, "signups": 212}
))This prints a dictionary with sessions_change_pct of 12.5. The prompt template then says "Use only the figures below. If a figure is not provided, say it is unavailable."
Handle failures
External calls fail in ordinary ways. Plan for each one before the first scheduled run.
| Failure | Typical sign | Response |
|---|---|---|
| Expired or wrong credentials | HTTP 401 or 403 | Stop and alert a person. Do not retry. |
| Rate limit | HTTP 429, often with a `Retry-After` header | Wait, then retry a limited number of times. |
| Temporary server error | HTTP 500 to 503, or a timeout | Retry with increasing delays. |
| Invalid payload | HTTP 400 or 422 | Do not retry. Log the payload and the error message. |
| Partial success | One of several writes fails | Record which writes succeeded so a rerun skips them. |
Retries are only safe for idempotent calls. Retrying a "create draft" call without a stable key is how duplicate emails and posts appear. For the same reason, never retry a send automatically.
Write one log line per external call with the workflow name and version, the target tool, the status code, and the ID of the item created. When something goes wrong a month later, this record is how you reconstruct what happened.
Keep the human gate before writes
Integration does not remove the review checkpoints from earlier chapters. It moves them. The right gate sits between validation and the adapter, and again between the draft and the final publish or send.
- Writing a draft to the CMS or email tool is reversible, so it can often run without approval.
- Publishing, scheduling, or sending is not reversible. Require a person to do it in the tool itself, or to approve it explicitly.
- Anything that touches a list of real people, such as a send or a segment change, gets the strictest review.
A good rule is that the workflow's credentials should not have permission to publish or send at all. Create an API key with the narrowest scope the tool allows, such as "create drafts". Then a mistake in your code cannot cause an irreversible action, because the tool refuses it.
Privacy when data flows both ways
Reading subscriber or customer data into a prompt sends that data to the model provider. Follow the rules from the governance chapter:
- Send aggregates, such as counts and percentages, instead of individual records, wherever the task allows.
- Remove names, email addresses, and other identifiers before building a prompt.
- Keep personalization out of the model. Use placeholders such as
{first_name}in the draft and let the email platform fill them at send time.
The last point also helps with testing. A template with placeholders can be reviewed once and reused for every recipient.
Test integrations without touching production
Use these practices to test safely.
- Use a sandbox or staging account if the tool offers one.
- Make the base URL a setting, so tests can point at a local fake server.
- Test adapters with fixed inputs and compare the payload they build to an expected one.
- Run the whole workflow once with real tools but a test list containing only your own address.
Common mistakes
- Letting the model call tools directly, so a bad output becomes a bad action.
- Using an API key with publish or send rights for a drafting workflow.
- Retrying a create call that has no stable key, which makes duplicates.
- Trusting analytics numbers the model computed itself.
- Running a report before the data is final.
- Putting subscriber identifiers into prompts when aggregates would do.
Exercise
Your weekly newsletter workflow creates a draft in the email platform. A network timeout occurs after the platform created the draft but before your code received the response, and your code retries. Name the problem this can cause and two changes that prevent it.
Show answer
The retry can create a second, duplicate draft, because the first request actually succeeded. Prevent it by (1) giving each newsletter a stable key, such as an external ID or slug including the issue date, and looking it up before creating, so the call is idempotent, and (2) using an API key limited to creating drafts, so a duplicate can never be sent. Logging the created item's ID also lets a rerun detect that the draft exists.
Exercise
A weekly report workflow asks the model to read raw analytics rows and calculate the percentage change in sessions. Describe a better design in two or three sentences.
Show answer
Fetch the metrics with code, validate required fields and the date range, and compute the percentage change in code. Pass only the final numbers to the prompt and tell the model to use only those figures and to say a figure is unavailable if it is missing. The model then writes the description, and it cannot invent or miscalculate the numbers.