Skip to content

RAG over Confluence: Indexing Pages, Attachments and Permissions

A Confluence page is not plain prose. It is XHTML full of macros, it sits somewhere in a page tree, it carries attachments, and it may be visible only to certain groups. Dump it into a vector store as-is and you get macro debris in answers, chunks with no context and, worst of all, passages served to people who were never allowed to read them. This tutorial builds an indexer that handles all four properly.

What are we building, and what does it produce?

We build a Python indexer that loads a Confluence Cloud space, converts each page to Markdown, splits it at headings and attaches the page path and the effective read restrictions to every chunk. The output is a JSONL file you can load into any vector database, plus a sync job that only fetches what changed.

Embedding models and vector databases are deliberately out of scope; that choice depends on your stack and is covered in Enterprise RAG: Architecture, Building Blocks and Pitfalls. That guide explains the general architecture. This one only deals with what is specific to Confluence. If you are still deciding whether you need your own index at all, or whether an off-the-shelf MCP server would do, start with Connecting an AI Agent to Confluence.

One output record looks like this:

{"id": "3-0", "text": "Path: Operations > Maintenance > Presses > Press 4 servicing\n\n# Press 4 servicing ...", "page_id": "3", "space_id": "42", "version": 7, "acl": [{"users": [], "groups": ["g1"]}]}

What do you need before you start?

You need a Confluence Cloud site, a service account with an API token, and Python 3.10 or later. The code was tested with Python 3.12, markdownify 1.2.4, beautifulsoup4 4.15.0 and requests 2.34.2 (as of November 2026). The API calls follow Atlassian's published OpenAPI specifications.

  • Authentication: for scripts, Atlassian documents basic auth using the Atlassian account email and an API token. Create a dedicated service user rather than using a personal account.
  • Visibility: the indexer only sees what that user can see. The search API states that it only returns entities the user has permission to view. A page the service user cannot read simply never reaches the index, without any error.
  • Libraries: according to PyPI, requests 2.34.2 requires Python 3.10 or newer.
python3.12 -m venv .venv && source .venv/bin/activate
pip install markdownify==1.2.4 beautifulsoup4==4.15.0 requests==2.34.2
export CONFLUENCE_BASE="https://your-site.atlassian.net"
export CONFLUENCE_EMAIL="indexer@example.com"
export CONFLUENCE_API_TOKEN="..."

Step 1: Load a space's pages through the REST API v2

The REST API v2 returns every page in a space, body included, one result page at a time. Request body-format=storage to get the content inline; according to the specification, limit accepts up to 250 pages per response. Further results come from the cursor link in _links.next.

The v2 API uses cursor-based pagination: a relative link to the next batch appears in the Link header and in _links.next. When it is missing, you have everything. You resolve the space from its key, because GET /spaces accepts a keys filter.

# api.py
import os
import requests

BASE = os.environ["CONFLUENCE_BASE"]      # e.g. https://your-site.atlassian.net
S = requests.Session()
S.auth = (os.environ["CONFLUENCE_EMAIL"], os.environ["CONFLUENCE_API_TOKEN"])

def _abs(link: str) -> str:
    """Make relative API links absolute (with or without /wiki prefix)."""
    if link.startswith("http"):
        return link
    return BASE + (link if link.startswith("/wiki") else "/wiki" + link)

def get_all(path: str, params: dict | None = None):
    """Yield every result of a v2 endpoint, following _links.next."""
    url = f"{BASE}/wiki/api/v2{path}"
    while url:
        r = S.get(url, params=params, timeout=30)
        r.raise_for_status()
        data = r.json()
        yield from data["results"]
        nxt = data.get("_links", {}).get("next")
        url, params = (_abs(nxt) if nxt else None), None

def load_space(key: str) -> tuple[dict, list[dict]]:
    space = next(get_all("/spaces", {"keys": key}))
    pages = list(get_all(f"/spaces/{space['id']}/pages",
                         {"body-format": "storage", "limit": 250}))
    return space, pages

Why not use search with expand=body.storage.value? The CQL documentation notes that this expansion returns at most 50 results, even if you ask for a higher limit. For a full import, the pages endpoint is the more direct route. Each page also carries parentId, parentType and version.number, which steps 3 and 6 rely on.

Step 2: Convert the storage format to Markdown

The storage format is XHTML with Confluence-specific elements for macros, links and images. A generic HTML-to-text converter drops code languages and callout boxes, or leaves macro parameters behind as noise. So the approach is to rewrite Confluence elements into plain HTML first and convert afterwards.

Macros appear as ac:structured-macro with their name in ac:name and parameters in ac:parameter. In Atlassian's example, the code macro keeps its content in ac:plain-text-body and its language in the language parameter. The code below sorts macros into three groups: code becomes a fenced block, callout panels become labelled quotes, and navigation-only macros such as the table of contents are dropped. Anything else, an expand section for instance, keeps its content.

# convert.py, part 1
from bs4 import BeautifulSoup
from markdownify import markdownify as md

PANELS = {"info": "Info", "note": "Note", "warning": "Warning", "tip": "Tip"}
DROP = {"toc", "children", "pagetree", "recently-updated", "anchor"}

def _macros(soup):
    for m in soup.find_all("ac:structured-macro"):
        name = m.get("ac:name", "")
        if name in ("code", "noformat"):
            lang = m.find("ac:parameter", attrs={"ac:name": "language"})
            body = m.find("ac:plain-text-body")
            pre, code = soup.new_tag("pre"), soup.new_tag("code")
            if lang:
                code["class"] = f"language-{lang.get_text(strip=True)}"
            code.string = body.get_text() if body else ""
            pre.append(code)
            m.replace_with(pre)
        elif name in PANELS:                 # callout panels
            body = m.find("ac:rich-text-body")
            quote, label = soup.new_tag("blockquote"), soup.new_tag("strong")
            label.string = PANELS[name] + ":"
            quote.append(label)
            if body:
                quote.extend(list(body.contents))
            m.replace_with(quote)
        elif name in DROP:                   # navigation, no content
            m.decompose()
        else:                                # e.g. expand: keep the content
            for p in m.find_all("ac:parameter"):
                p.decompose()
            m.unwrap()

Links to other pages (ac:link with ri:page) and to attachments (ri:attachment) become their link text, or the page title or file name when there is none. Images and emoticons add nothing to text retrieval and are removed, while task lists (ac:task-list) become Markdown checklists. Set heading_style="ATX": by default markdownify produces underlined headings, which the chunker in step 3 cannot split on.

# convert.py, part 2
def _links_and_tasks(soup):
    for link in soup.find_all("ac:link"):
        target = link.find(["ri:page", "ri:attachment"])
        text = link.get_text(strip=True) or (
            target.get("ri:content-title") or target.get("ri:filename", "")
            if target else "")
        link.replace_with(text)
    for tag in soup.find_all(["ac:image", "ac:emoticon", "ac:placeholder"]):
        tag.decompose()
    for task in soup.find_all("ac:task"):
        status = task.find("ac:task-status")
        done = status is not None and status.get_text(strip=True) == "complete"
        body = task.find("ac:task-body")
        li = soup.new_tag("li")
        li.string = ("[x] " if done else "[ ] ") + (
            body.get_text(" ", strip=True) if body else "")
        task.replace_with(li)
    for tl in soup.find_all("ac:task-list"):
        tl.name = "ul"

def _lang(pre):
    code = pre.find("code")
    cls = code.get("class") if code else None
    return cls[0].removeprefix("language-") if cls else None

def storage_to_markdown(xml: str) -> str:
    soup = BeautifulSoup(xml, "html.parser")
    _macros(soup)
    _links_and_tasks(soup)
    return md(str(soup), heading_style="ATX", code_language_callback=_lang).strip()

Tables come through as Markdown tables. Audit which macros your spaces actually use and extend PANELS and DROP to match.

Step 3: Prefix every chunk with its page path

A chunk titled "Intervals" means nothing on its own; under "Operations > Maintenance > Presses > Press 4 servicing" it is unambiguous. Build each page's path from parentId and put it in front of every chunk. Vector search can then match terms that only appear in parent page titles.

Because step 1 already loaded the whole space, the path costs no extra API calls. For one-off lookups there is also GET /pages/{id}/ancestors, which per the specification returns ancestors top to bottom, though only with ID and type. Chunks are split at heading levels 1 to 3, and small sections are merged up to a size limit.

# hierarchy.py
import re

def breadcrumbs(pages: list[dict], space_name: str) -> dict[str, str]:
    """Page ID -> 'Space > Parent > ... > Title', built from parentId."""
    by_id = {p["id"]: p for p in pages}
    out = {}
    for p in pages:
        trail, cur = [], p
        while cur:
            trail.append(cur["title"])
            parent = cur.get("parentId") if cur.get("parentType") == "page" else None
            cur = by_id.get(parent)
        out[p["id"]] = " > ".join([space_name, *reversed(trail)])
    return out

def chunk(markdown: str, crumb: str, max_chars: int = 2500) -> list[str]:
    """Split at headings and prefix each chunk with the page path."""
    parts = re.split(r"(?m)^(?=#{1,3} )", markdown)
    chunks, buf = [], ""
    for part in parts:
        if buf and len(buf) + len(part) > max_chars:
            chunks.append(buf)
            buf = ""
        buf += part
    if buf.strip():
        chunks.append(buf)
    return [f"Path: {crumb}\n\n{c.strip()}" for c in chunks]

One caveat: the regular expression also treats shell comments starting with # inside code blocks as headings. If your spaces are full of such snippets, split on the HTML tree before conversion instead.

Step 4: Index attachments

The API v2 lists attachments per page and lets you filter by media type. Only index formats you can reliably extract text from, and give each attachment the path and permissions of its page. Skip images, archives and CAD files.

According to the specification, GET /pages/{id}/attachments returns fields including mediaType, fileSize, title and downloadLink, again with up to 250 results per call. Text extraction from PDF and Word files is a topic of its own. What matters here is that the chunk text later starts with Path: … > page title > file name, so the agent's answer can point people to the right page.

# attachments.py
from api import S, _abs, get_all

TEXT_TYPES = {"text/plain", "text/markdown", "text/csv"}
EXTRACT_TYPES = {"application/pdf",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}

def page_attachments(page_id: str):
    """Yield (metadata, bytes) for indexable attachments of a page."""
    for att in get_all(f"/pages/{page_id}/attachments", {"limit": 250}):
        mt = att.get("mediaType", "")
        if mt not in TEXT_TYPES | EXTRACT_TYPES:
            continue                      # skip images, archives, CAD files
        if att.get("fileSize", 0) > 20_000_000:
            continue                      # handle very large files separately
        r = S.get(_abs(att["downloadLink"]), timeout=120)
        r.raise_for_status()
        yield att, r.content

Step 5: Carry read permissions into the index

Confluence controls read access at two levels: space permissions and page restrictions. Atlassian's documentation states that restrictions inherited from ancestors still apply. So store the read restrictions of the page and every ancestor, and at query time require the user to satisfy each of them.

The v1 endpoint GET /wiki/rest/api/content/{id}/restriction/byOperation/read returns the users (accountId) and groups of a read restriction; per the specification both lists are expanded by default. A page without its own restriction returns empty lists and restricts nothing. The cache stops shared ancestors from being fetched again for every child page.

# acl.py
from functools import lru_cache
from api import BASE, S

@lru_cache(maxsize=None)
def read_restriction(content_id: str) -> tuple[frozenset, frozenset]:
    """Direct read restriction of a page: (accountIds, groupIds)."""
    r = S.get(f"{BASE}/wiki/rest/api/content/{content_id}"
              "/restriction/byOperation/read", timeout=30)
    r.raise_for_status()
    res = r.json().get("restrictions", {})
    users = frozenset(u["accountId"] for u in res.get("user", {}).get("results", [])
                      if "accountId" in u)
    groups = frozenset(g["id"] for g in res.get("group", {}).get("results", []))
    return users, groups

def effective_acl(page_id: str, by_id: dict) -> list[dict]:
    """Restrictions of the page and all ancestors; each must be satisfied."""
    sets, cur = [], by_id.get(page_id)
    while cur:
        users, groups = read_restriction(cur["id"])
        if users or groups:
            sets.append({"users": sorted(users), "groups": sorted(groups)})
        parent = cur.get("parentId") if cur.get("parentType") == "page" else None
        cur = by_id.get(parent)
    return sets

def may_read(acl: list[dict], account_id: str, group_ids: set[str]) -> bool:
    return all(account_id in s["users"] or group_ids & set(s["groups"])
               for s in acl)

The space level is stored as space_id on each chunk. GET /spaces/{id}/permissions in the API v2 tells you who may read a space: each assignment names a principal of type user, group or role and an operation such as read with target type space. At query time, filter to permitted spaces first, then apply may_read to the chunks. You need the asking user's group IDs from your identity provider for that.

Putting it together:

# index_space.py
import json
from api import load_space
from convert import storage_to_markdown
from hierarchy import breadcrumbs, chunk
from acl import effective_acl

space, pages = load_space("OPS")
by_id = {p["id"]: p for p in pages}
crumbs = breadcrumbs(pages, space["name"])
with open("chunks.jsonl", "w", encoding="utf-8") as f:
    for p in pages:
        text = storage_to_markdown(p["body"]["storage"]["value"])
        meta = {"page_id": p["id"], "space_id": space["id"],
                "version": p["version"]["number"],
                "acl": effective_acl(p["id"], by_id)}
        for i, c in enumerate(chunk(text, crumbs[p["id"]])):
            rec = {"id": f"{p['id']}-{i}", "text": c, **meta}
            f.write(json.dumps(rec, ensure_ascii=False) + "\n")

Step 6: Sync incrementally with CQL lastmodified

Reloading a whole space every night wastes API calls and embedding compute. A CQL search returns every page and attachment changed since the last run; you reload those and replace all existing chunks for the same page ID. Everything else in the index stays untouched.

Per the CQL documentation, lastmodified accepts "yyyy/MM/dd HH:mm", "yyyy-MM-dd HH:mm", "yyyy/MM/dd" and "yyyy-MM-dd", with the operators >, >=, < and <=. Results are relative to the configured time zone. Your sync host probably runs on UTC, so the code subtracts a two-hour overlap; pages caught twice can be skipped when version.number has not changed.

# sync.py
from datetime import datetime, timedelta
from api import BASE, S, _abs

def changed_since(space_key: str, since: datetime, overlap_h: int = 2):
    """IDs of pages and attachments changed since a point in time."""
    t = (since - timedelta(hours=overlap_h)).strftime("%Y/%m/%d %H:%M")
    cql = (f'space = "{space_key}" and type in (page, attachment) '
           f'and lastmodified >= "{t}"')
    url, params = f"{BASE}/wiki/rest/api/search", {"cql": cql, "limit": 100}
    while url:
        r = S.get(url, params=params, timeout=30)
        r.raise_for_status()
        data = r.json()
        for hit in data["results"]:
            c = hit.get("content", {})
            yield c.get("type"), c.get("id")
        nxt = data.get("_links", {}).get("next")
        url, params = (_abs(nxt) if nxt else None), None

lastmodified leaves two gaps. Deleted pages cannot show up in a search for changes, so reconcile the full list of page IDs per space against the index once a night. And the documentation does not say whether changing only a page's restrictions updates lastmodified. Recompute permissions in a separate scheduled run rather than relying on the content sync.

How do you test the pipeline?

Test three things separately: conversion, permissions and retrieval. For conversion, export a handful of typical pages with code, tables, callouts and task lists and read the Markdown yourself. For permissions, create a restricted test page and query it as two different test users.

  • Conversion: search the generated Markdown for ac: and ri:. Every hit is an element your converter does not handle yet.
  • Permissions: a page below a restricted parent must never appear for a user outside the permitted group, even if the page itself has no restriction. This case exercises the inheritance logic from step 5.
  • Retrieval: collect 20 to 30 real questions from the business team where you know the right page, and check whether that page lands among the top results. Re-run the set after every change to chunking.

Operations, cost and security

Three things matter in production: the API token, which unlocks everything the service user can read; embedding compute; and where the index lives. Most of the cost comes from embedding the full space on the first import. After that, the incremental sync keeps the load small.

  • Token: keep the API token in a secrets manager, never in code. Grant the service user access only to the spaces that belong in the index; what it cannot see cannot leak.
  • Error handling: add retries with back-off for failed and throttled requests, and log which page IDs were skipped.
  • Where the index lives: the index holds Confluence content in clear text and needs the same protection as Confluence itself. If content must stay on your own infrastructure, the embedding model and vector database can run there as well; see sovereign AI.
  • Limits: the API v2 with cursor pagination is a Cloud API. On Confluence Data Center the approach is the same, but page loading has to be adapted to that REST API.

Where to go next

The index is the foundation for a knowledge agent that answers questions and links back to the source page. Next, load the JSONL file into your vector database and build retrieval with the permission filter in front of it.

To see what such an agent looks like in daily use, from a question in chat to an answer with a page link, have a look at the knowledge management agent. For an overview of other specialist agents and how they connect to existing systems, see AI agents.

Frequently asked questions

Can I skip the index and use Confluence search instead?

For simple keyword look-ups, yes. Confluence search does not match paraphrased questions and does not return section-sized passages for a language model, so a dedicated index pays off once pages are long and attachments matter.

Does this work with Confluence Data Center?

Partly. Data Center also uses the storage format, but the REST API v2 with cursor pagination is a Cloud API, so the page-loading code has to be rewritten against the Data Center REST API.

How do deleted pages leave the index?

A lastmodified query never returns them. Compare the full list of page IDs in each space with your index on a schedule and remove anything that no longer exists.

Should I request atlas_doc_format instead of storage?

Not for retrieval. The API v2 offers both, but storage is XHTML that standard HTML tooling can parse, while atlas_doc_format is a JSON document tree that needs a converter of its own.

Sources

  1. Atlassian: Confluence Cloud REST API v2 – introduction and pagination developer.atlassian.com
  2. Atlassian: REST API v2 – Page developer.atlassian.com
  3. Atlassian: OpenAPI specification, Confluence REST API v2 dac-static.atlassian.com
  4. Atlassian: OpenAPI specification, Confluence REST API v1 dac-static.atlassian.com
  5. Atlassian: Advanced searching using CQL developer.atlassian.com
  6. Atlassian: REST API v1 – Search developer.atlassian.com
  7. Atlassian: REST API v1 – Content restrictions developer.atlassian.com
  8. Atlassian: REST API v2 – Space permissions developer.atlassian.com
  9. Atlassian: Confluence Storage Format confluence.atlassian.com
  10. Atlassian: Code Block Macro (storage format example) confluence.atlassian.com
  11. Atlassian: Basic auth for REST APIs developer.atlassian.com
  12. PyPI: markdownify pypi.org