How to Summarise Notion with Haystack

Summarise public Notion pages in a Haystack pipeline using EnConvert Distill, which returns schema-defined fields from share URLs in one synchronous call

Get API key

A developer building a Haystack pipeline that reads Notion pages needs clean structured content from each page before the pipeline can reason over it. The Notion API returns a typed block tree rather than plain text, with headings, paragraphs, and toggles arriving as siblings with no parent-child context, and reading a full page requires recursive child block fetches for each nested element. EnConvert Distill accepts the public share link for each Notion page and a schema the developer defines, and returns structured fields in one synchronous call. The Haystack Tool function gets schema-defined page content with no block tree traversal and no recursive API calls.

Example

python
import os

import requests
from haystack import Pipeline
from haystack.components.builders import ChatPromptBuilder
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.tools import Tool
from haystack.components.tools import ToolInvoker

# OpenAIChatGenerator reads OPENAI_API_KEY from the environment
NOTION_SHARE_URL = os.environ["NOTION_SHARE_URL"]  # a public Notion page share link

BASE_URL = "https://api.enconvert.com/v2"
headers = {
    "X-API-Key": os.environ["ENCONVERT_API_KEY"],
    "Content-Type": "application/json",
}

# The fields the pipeline receives. The response keys match these names exactly.
# Each description tells the extractor to leave a field empty rather than guess.
NOTION_SCHEMA = {
    "page_title": "The page title",
    "summary": (
        "A three sentence summary of the page, using only text that is visible on the page. "
        "Return an empty string if the page has no text content."
    ),
    "key_points": (
        "The main points the page makes, as a list. "
        "Return an empty list if the page has no text content."
    ),
    "last_edited": "The last edited date, only if the page shows one. Return an empty string otherwise.",
}

def as_text(value) -> str:
    if isinstance(value, list):
        return "; ".join(str(item) for item in value) or "not stated"
    return str(value) if value else "not stated"

def summarise_notion_pages(urls: list[str]) -> str:
    """Reads public Notion pages from their share links and returns structured fields for each:
    title, summary, key points, and last edited date. Accepts up to 50 URLs."""
    # Distill accepts at most 50 URLs per call
    if len(urls) > 50:
        return "Too many URLs. Distill accepts at most 50 per call."

    # One synchronous call: no job_id, no polling, no download step
    response = requests.post(
        f"{BASE_URL}/distill",
        headers=headers,
        json={"urls": urls, "schema": NOTION_SCHEMA},
        timeout=300,
    )

    # Distill runs on paid plans only, and the free tier returns 402
    if response.status_code == 402:
        return "Distill requires a paid plan."
    response.raise_for_status()

    pages = []
    for result in response.json()["results"]:
        if result["status"] != "completed":
            pages.append(f"Source: {result['url']}\nCould not be read ({result['status']}).")
            continue

        # A render_quality below 0.5 may mean a login wall or challenge page
        render_quality = result.get("render_quality", 1.0)
        if render_quality < 0.5:
            pages.append(
                f"Source: {result['url']}\nLow render quality ({render_quality}), skipped."
            )
            continue

        data = result["data"]  # keys match NOTION_SCHEMA exactly

        if not data.get("page_title") and not data.get("summary"):
            pages.append(f"Source: {result['url']}\nNo page content was found.")
            continue

        pages.append(
            f"Source: {result['url']}\n"
            f"Title: {as_text(data['page_title'])}\n"
            f"Last edited: {as_text(data['last_edited'])}\n"
            f"Key points: {as_text(data['key_points'])}\n"
            f"Summary: {as_text(data['summary'])}"
        )
    return "\n\n---\n\n".join(pages)

notion_tool = Tool(
    name="summarise_notion_pages",
    description=(
        "Reads public Notion pages from their share links and returns structured fields for "
        "each: title, summary, key points, and last edited date. Accepts up to 50 URLs."
    ),
    parameters={
        "type": "object",
        "properties": {
            "urls": {
                "type": "array",
                "items": {"type": "string"},
                "description": "Public Notion share links to read, at most 50",
            }
        },
        "required": ["urls"],
    },
    function=summarise_notion_pages,
)

SYSTEM = (
    "You answer questions about Notion pages. Use summarise_notion_pages to read the pages you "
    "need, answer only from what it returns, and cite the page URL for every statement. If a "
    "field is not stated, say so and do not guess."
)

pipe = Pipeline()
pipe.add_component(
    "prompt_builder",
    ChatPromptBuilder(
        template=[ChatMessage.from_system(SYSTEM), ChatMessage.from_user("{{ query }}")]
    ),
)
pipe.add_component(
    "llm", OpenAIChatGenerator(model="gpt-4.1", tools=[notion_tool])
)
pipe.add_component("tool_invoker", ToolInvoker(tools=[notion_tool]))
pipe.connect("prompt_builder.prompt", "llm.messages")
pipe.connect("llm.replies", "tool_invoker.messages")

query = (
    f"Read {NOTION_SHARE_URL} and list its key points and last edited date."
)
result = pipe.run(
    {"prompt_builder": {"query": query}},
    include_outputs_from={"llm"},
)

reply = result["llm"]["replies"][0]
if not reply.tool_calls:
    print(reply.text)
else:
    # Send the tool result back to the model for the final answer
    final_llm = OpenAIChatGenerator(model="gpt-4.1")
    messages = [
        ChatMessage.from_system(SYSTEM),
        ChatMessage.from_user(query),
        reply,
        *result["tool_invoker"]["tool_messages"],
    ]
    print(final_llm.run(messages=messages)["replies"][0].text)

What you get back

Distill returns schema-defined fields inline as structured JSON in the data object, with no polling and no block tree traversal. The render_quality score lets the pipeline skip a page before indexing incomplete content. Reading Notion pages through the API requires fetching page metadata and recursively querying nested block children to assemble plain text from typed block objects, while Distill returns schema-defined fields from the share URL in one synchronous call.

Get free API key — 500 ops per month, no card required. Note: Distill runs on paid plans. Free tier returns 402.