Building an AI Agent That Writes to Notion: Schema Design & API Logic
A code-first guide to Notion writeback for AI agents. You design a schema the agent can fill (status, topics, source, confidence), get structured output from a model with Pydantic, turn it into Notion blocks within the API's size limits, handle rate limits, and move pages through a status queue.

This guide is for developers whose AI agent produces good output that then sits in a terminal until someone copies it. You will design a Notion database the agent can write to, get structured output from a model, and save it as a Notion page with Python. The page lands with a status, topics, a source link and a confidence score, ready for you to review.
Key takeaways
- Design the database first. Each property you add (status, topics, confidence) is a field the agent must fill and you can filter on.
- Ask the model for structured output that matches the schema, and limit choice fields to a fixed list, so the agent can't invent new tags.
- Respect Notion's limits: 2,000 characters per text item, 100 blocks per request, and a
Retry-Afterwait when you are rate limited.
Why agents need a place to write
A chat window is a poor place for agent output. You can't filter it, sort it or hand it to someone for review. A database can do all three, and many teams already plan their work in Notion.
Agent writeback is the step where an agent saves its result into a system of record, such as a Notion database, as structured fields plus content, instead of returning text to a chat.
With writeback, the database becomes a queue. You add a row with status Inbox, the agent picks it up and writes a draft, and the row moves to Draft Ready for a human to check.
Part 1: Design the schema
Create a database in Notion (table view works) with these properties. The example is a content and research agent, but the pattern fits any domain.
| Property | Type | What the agent writes | Why it helps |
|---|---|---|---|
| Name | Title | A headline for the result | Scannable list and board views |
| Status | Select | Inbox, Processing, Draft Ready or Published |
Turns the database into a queue and a board |
| Topic | Multi-select | Tags from a fixed list | Filtering, and no tag sprawl |
| URL | URL | The source the agent used | You can check the claim in one click |
| Confidence Score | Number | 0 to 1, the agent's own rating | Sort the weakest drafts to the top for review |
Notion's page property values reference says that writing a select option name that doesn't exist adds it to the schema, if your connection can write to the data source. That is why the code below limits topics to a fixed list. Option names also can't contain commas.
Treat the confidence score as a hint
A model rating its own work is not a measurement. Use the score to order your review queue, not to skip review.
Part 2: Connect and find your IDs
- Create an internal connection in Notion's developer portal and copy its API token. Store it in an environment variable named
NOTION_TOKEN, never in the code. - Open the database, click •••, choose Add connections and pick your connection. Notion's authorization guide says requests for pages you haven't shared return an error. This is the step people miss most often.
- Copy the data source ID. Since API version
2025-09-03, a database can hold several data sources, and new pages name a data source as their parent. You can copy the ID in the database settings under Manage data sources, or read it from thedata_sourceslist returned byGET /v1/databases/{database_id}.
Save it as NOTION_DATA_SOURCE_ID.
Part 3: The writer module
The Notion API is verbose. Every database cell is a property object, and every paragraph is a block object. Create notion_writer.py, starting with one helper for all requests:
import os
import time
import requests
NOTION_VERSION = "2026-03-11"
MAX_TEXT = 2000 # characters per rich text item
MAX_BLOCKS = 100 # blocks per request
def notion_request(method, path, body=None):
headers = {
"Authorization": f"Bearer {os.environ['NOTION_TOKEN']}",
"Notion-Version": NOTION_VERSION,
"Content-Type": "application/json",
}
for attempt in range(4):
response = requests.request(
method, f"https://api.notion.com/v1/{path}", headers=headers, json=body, timeout=30
)
blocked = response.status_code == 429 and response.json().get("code") == "public_api_request_blocked"
if response.status_code not in (429, 529) or blocked or attempt == 3:
break # done, not retryable, or out of attempts: no pointless final sleep
time.sleep(int(response.headers.get("Retry-After", "1")))
response.raise_for_status()
return response.json()
Checked against requests@2.34.2, openai@3.41.0 and pydantic@2.14.1 (Python 3.13), 2026-10-29.
Notion's request limits page explains the retry rules this helper follows. Retry 429 and 529 responses after the number of seconds in Retry-After. Don't retry a 429 whose code is public_api_request_blocked, because that connection's access has been restricted. A fixed time.sleep(0.5) between calls only guesses at the limit. Retry-After tells you the exact wait.
2026-03-11 is the newest version on Notion's versioning page today. Pin it, and upgrade on purpose: that version renamed archived to in_trash, for example.
Create the page
Next, map one result onto the schema. The payload has two parts: properties for the database cells and children for the page body.
def append_blocks(page_id, blocks):
for start in range(0, len(blocks), MAX_BLOCKS):
notion_request("PATCH", f"blocks/{page_id}/children", {"children": blocks[start : start + MAX_BLOCKS]})
def create_notion_entry(title, content_blocks, topics, source_url, confidence):
payload = {
"parent": {"type": "data_source_id", "data_source_id": os.environ["NOTION_DATA_SOURCE_ID"]},
"properties": {
"Name": {"title": [{"text": {"content": title[:MAX_TEXT]}}]},
"Status": {"select": {"name": "Draft Ready"}},
"Topic": {"multi_select": [{"name": topic} for topic in topics]},
"URL": {"url": source_url},
"Confidence Score": {"number": confidence},
},
"children": content_blocks[:MAX_BLOCKS],
}
page = notion_request("POST", "pages", payload)
append_blocks(page["id"], content_blocks[MAX_BLOCKS:]) # the rest, 100 at a time
return page
The older version of this post had three bugs that this code fixes. It sent database_id as the parent, which fails once a database has more than one data source. It sent every block in one request, but Notion's create page reference caps children at 100 blocks. And it cut long paragraphs at 2,000 characters, dropping the rest.
The property names must match your columns exactly. If your Status column uses Notion's built-in status type, change "select" to "status".
Turn model text into blocks
You can't send a plain string as the page body. Each paragraph becomes a block, and Notion's request limits allow 2,000 characters per text item, so long paragraphs need splitting:
def rich_text(text):
return [{"type": "text", "text": {"content": text}}]
def text_to_blocks(text):
blocks = []
for part in text.split("\n\n"):
part = part.strip()
if not part:
continue
if part.startswith("## "):
heading = part[3:][:MAX_TEXT]
blocks.append({"object": "block", "type": "heading_2", "heading_2": {"rich_text": rich_text(heading)}})
continue
for start in range(0, len(part), MAX_TEXT):
chunk = part[start : start + MAX_TEXT]
blocks.append({"object": "block", "type": "paragraph", "paragraph": {"rich_text": rich_text(chunk)}})
return blocks
Split long text into more blocks, not shorter blocks:
# Don't: drops everything after character 2,000
{"content": paragraph[:2000]}
# Do: keeps every character, across as many blocks as needed
[paragraph[i : i + 2000] for i in range(0, len(paragraph), 2000)]
Or send Markdown
Notion's create page endpoint also takes a markdown string instead of children. Its markdown guide says the two can't be combined, and that bookmarks and embeds don't render from markdown. If your model already writes Markdown, this is the shortest path:
def create_from_markdown(title, markdown_body):
payload = {
"parent": {"type": "data_source_id", "data_source_id": os.environ["NOTION_DATA_SOURCE_ID"]},
"properties": {"Name": {"title": [{"text": {"content": title[:MAX_TEXT]}}]}},
"markdown": markdown_body,
}
return notion_request("POST", "pages", payload)
Here is how the three ways to write a page compare:
| Approach | What you send | Trade-off | Use it when |
|---|---|---|---|
children blocks with requests |
Block JSON you build | Most code, but full control and no SDK to track | You need specific block types or exact layout |
markdown with requests |
One Markdown string | Least code; some blocks (bookmarks, embeds) don't render | The model already writes Markdown |
notion-client SDK |
Python method calls | Less boilerplate; it is a community-maintained package, not Notion's own | Larger apps with many endpoints |
For a small agent, plain requests keeps the JSON visible, which makes the API's errors easier to match to your payload. That is a matter of taste, not a rule.
Part 4: Connect the model
The model should return data that already fits the schema. With OpenAI's structured outputs, a Pydantic model describes the shape, and Literal limits topics to your fixed list. Add this to notion_writer.py:
from typing import Literal
from openai import OpenAI
from pydantic import BaseModel, Field
Topic = Literal["Python", "SaaS", "Automation", "AI"]
class Insight(BaseModel):
title: str
body: str = Field(description="Plain text. Separate paragraphs with a blank line. Start a heading with '## '.")
topics: list[Topic]
confidence: float = Field(description="0 to 1: how well your sources support the body.")
def generate_insight(topic):
client = OpenAI() # reads OPENAI_API_KEY
response = client.responses.parse(
model=os.environ.get("AGENT_MODEL", "gpt-6-luna"),
input=[
{"role": "system", "content": "You are a research assistant. Write a short, factual briefing."},
{"role": "user", "content": topic},
],
text_format=Insight,
)
return response.output_parsed
responses.parse with text_format comes from OpenAI's structured outputs guide. The SDK builds the JSON schema from the class and returns an Insight object. On the date above, OpenAI's models page lists gpt-6-luna as its most efficient model. Check that page for current ids, and set AGENT_MODEL to switch. For more on schemas and retries, see structured JSON output from LLMs.
The client is created inside the function, because OpenAI() raises an error when no API key is set. That keeps the module importable in tests.
Finally, wire the steps together. This path creates a new row for each topic you pass in:
def agent_note(topic):
callout = {"rich_text": rich_text(f"Drafted by an AI agent for: {topic}"), "icon": {"emoji": "🤖"}}
return [{"object": "block", "type": "callout", "callout": callout}]
def run_agent_workflow(topic, source_url):
insight = generate_insight(topic)
blocks = agent_note(topic) + text_to_blocks(insight.body)
confidence = min(max(insight.confidence, 0.0), 1.0)
page = create_notion_entry(insight.title, blocks, insight.topics, source_url, confidence)
print(f"Created {page['url']}")
return page
if __name__ == "__main__":
run_agent_workflow("Notion schema design for AI agents", "https://developers.notion.com/reference/post-page")
The callout at the top marks the page as machine-written, so nobody mistakes a draft for reviewed work. The score is clamped to 0 to 1, because the schema can't force a float into a range.
Test it without keys
You can check the block logic and the payload shape with no API keys at all:
import notion_writer
long_text = "## Summary\n\n" + "x" * 4500
blocks = notion_writer.text_to_blocks(long_text)
assert [b["type"] for b in blocks] == ["heading_2", "paragraph", "paragraph", "paragraph"]
assert sum(len(b["paragraph"]["rich_text"][0]["text"]["content"]) for b in blocks[1:]) == 4500
sent = []
notion_writer.notion_request = lambda method, path, body=None: sent.append((method, path, body)) or {"id": "p1"}
notion_writer.os.environ["NOTION_DATA_SOURCE_ID"] = "ds1"
notion_writer.create_notion_entry("T", blocks * 30, ["AI"], "https://developers.notion.com", 0.5)
assert [(m, p) for m, p, _ in sent] == [("POST", "pages"), ("PATCH", "blocks/p1/children")]
print("writer works")
Save it as test_writer.py and run it. The 120 blocks go out as 100 on create and 20 in one append call.
Part 5: Close the loop with status
The Status field is what turns a database into a work queue. Instead of creating a new row, the agent can work on rows you add by hand: query the data source for Inbox rows, claim each one, and write the draft into that same row. Add these functions to notion_writer.py, above the if __name__ block:
def set_status(page_id, status):
notion_request("PATCH", f"pages/{page_id}", {"properties": {"Status": {"select": {"name": status}}}})
def next_inbox_items():
body = {"filter": {"property": "Status", "select": {"equals": "Inbox"}}, "page_size": 10}
return notion_request("POST", f"data_sources/{os.environ['NOTION_DATA_SOURCE_ID']}/query", body)["results"]
def process_inbox():
for row in next_inbox_items():
set_status(row["id"], "Processing") # claim the row before the slow model call
topic = "".join(part["plain_text"] for part in row["properties"]["Name"]["title"])
insight = generate_insight(topic)
append_blocks(row["id"], agent_note(topic) + text_to_blocks(insight.body))
notion_request("PATCH", f"pages/{row['id']}", {"properties": {
"Topic": {"multi_select": [{"name": name} for name in insight.topics]},
"Confidence Score": {"number": min(max(insight.confidence, 0.0), 1.0)},
"Status": {"select": {"name": "Draft Ready"}},
}})
To work the queue, call process_inbox() from the entry point instead of run_agent_workflow(...), or from a scheduled job. Each row moves to Processing before the model call and to Draft Ready only after its draft is written. If a run crashes, the row stays in Processing, so you can see what failed instead of having it picked up twice.
This is the same data source a Python daily brief can read each morning. If you prefer a visual builder, the n8n inbox triage tutorial creates Notion pages with n8n's Notion node.
Frequently asked questions
Why does the Notion API return "object not found" for my database?
Usually the database isn't shared with your connection. Open the database, click •••, choose Add connections and pick your connection. Notion's authorization guide says requests for pages you haven't shared return an error.
Should I use database_id or data_source_id as the parent?
Use data_source_id. Notion's 2025-09-03 upgrade guide moved page creation and queries to data sources, and requests that use the database ID fail once a database has a second data source.
How long can a Notion text block be?
Notion's request limits allow 2,000 characters per rich text content and 100 blocks per request. Split long text into several blocks, and append blocks past the first 100 in batches.
How do I stop the agent from creating random tags?
Limit the field in your structured output schema, for example with a Pydantic Literal of allowed values. Notion adds a new select option when you write an unknown name, so the schema is the right place to say no.
How should I handle Notion rate limits?
Wait for the number of seconds in the Retry-After header, then retry. Notion's docs say to retry 429 and 529 responses this way, but not a 429 with the code public_api_request_blocked.
Sources
Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.
- Notion API: Versioning
- Notion API: Upgrading to version 2025-09-03 (data sources)
- Notion API: Upgrading to version 2026-03-11
- Notion API: Create a page
- Notion API: Update page properties
- Notion API: Page property values
- Notion API: Block object
- Notion API: Working with markdown content
- Notion API: Request limits
- Notion API: Authorization (internal connections)
- notion-client on PyPI
- OpenAI API: Structured outputs
- OpenAI API: Models
AI Automation Engineer & Salesforce Developer
Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.



Comments
Loading comments...