> ## Content Index
> Fetch the complete content index at: https://blog.sudowl.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Mirroring My Markdown Notes Into Notion With a Python Sync
- URL: https://blog.sudowl.com/notion-api-sync-markdown-notes/
- Published: 2026-11-15T18:00:00.000Z
- Updated: 2026-12-04T12:22:14.000Z
- Description: Cleaning up an old Notion workspace, then a Python sync mirroring Markdown notes into Notion databases. Integration gotchas, secret filter, no duplicates.
- Author: Lukas
- Tags: business-ai

My real notes are Markdown files on my laptop. Projects, open tasks, servers, rules I work by, how-tos, a log of work sessions. Fast to write, easy to search, terrible on a phone.

Notion is the opposite. Nice boards, works everywhere, slow to type into. So I stopped choosing and built a one-way sync: Markdown stays the source, Notion is the view.

Before that I had to clean up the workspace. It was a mess, and part of it was public.

**TL;DR:** Inventory the workspace through the API, trash the old stuff (it stays restorable for 30 days). Create the root page in the browser, because an internal integration can't create top-level pages. Connect pages to the integration through `•••` → Connections, the bulk "edit access" dialog didn't save for me. Run every text through a secret filter and a redact list before it leaves the machine. Keep a state file with source key → page ID → content hash. When you archive a page through the API, also delete it from the state file, or it comes back.

## Step 1: find out what's actually in there

The Notion `search` endpoint with an empty query returns everything the integration can see, 100 per page. I dumped it all to JSON and printed the top-level pages with how many children each had.

```python
objs, cur = [], None
while True:
    body = {"page_size": 100}
    if cur:
        body["start_cursor"] = cur
    d = req("POST", "search", body)
    objs += d["results"]
    if not d["has_more"]:
        break
    cur = d["next_cursor"]

```

The worst find: an old freelancer template. Invoice tracker, clients, rates, a time tracker. Twelve pages, and the whole thing was still shared to the web on a public Notion site. Nothing tragic in it, but nothing that should be public either.

Plus old notes from 2020 to 2023, an old prompt pack, an old challenge page. All dead.

## Step 2: trash, don't delete

I archived 18 top-level objects through the API, 16 pages and 2 databases. Archived in the API means "in the trash" in the UI, and Notion keeps the trash for 30 days. I also wrote the list of IDs and titles to a JSON file, so I know exactly what to restore if I miss something.

```python
r = urllib.request.Request(
    f"https://api.notion.com/v1/{kind}/{obj_id}",
    data=json.dumps({"archived": True}).encode(),
    headers=H, method="PATCH")
urllib.request.urlopen(r)

```

Two things I kept and moved: a set of work sheets and some project knowledge went under the new Knowledge page. A private finance page went into a Private section. The sync never touches Private, that's hardcoded.

After that the sidebar had one entry left: the new home page.

## Gotcha: internal integrations can't create top-level pages

An internal integration can only create pages under a parent it has access to. It can't create anything at the workspace root. So the home page was the one thing I made by hand in the browser, then shared with the integration. Everything else, the databases included, the script creates under that page.

## Gotcha: the "Edit access" dialog didn't save

In the integration settings there's a tab where you can pick which pages the integration may access. I picked the pages and saved. It didn't stick, the integration still couldn't see them.

What worked: open each page and go `•••` → Connections → add the integration. Child pages inherit it. So once the home page is connected, everything the sync creates below it is reachable too. Anything new you make at the top level, you have to connect by hand again.

## Step 3: what goes where

My notes are Markdown files with a small frontmatter block: name, description, type. The type decides the target.

| Source                             | Notion database                                 | Count after first import |
| ---------------------------------- | ----------------------------------------------- | ------------------------ |
| project notes                      | Projects (company, status, open points, folder) | 61                       |
| "open:" lines inside project notes | Tasks                                           | about 38                 |
| server notes                       | Infrastructure                                  | 9                        |
| rule notes                         | Work rules                                      | 26                       |
| references, runbooks, READMEs      | Knowledge                                       | 104                      |
| session log                        | Session log                                     | 633                      |

Tasks are the interesting part. A project note has a description like "Open: SPF record, admin password, test the restore". The script finds the "open" part, splits on commas, semicolons and plus signs, and makes one task per item. Each task gets a relation to its project.

Two things I had to fix there:

- **Brackets.** An item like "check the backup (daily, 3 AM)" would be split into two tasks. Now the splitter glues parts back together while a bracket is still open.
- **Short titles.** A task called "Bing" means nothing on a board. Titles under 25 characters get the project name in front, so it reads "Brand site: Bing".

```python
title = item if len(item) > 25 else f"{short_project_name}: {item}"

```

## Step 4: nothing secret leaves the laptop

My notes contain things that must never be in a cloud tool. A password in a gotcha line, a key block, an API token inside a command. So every title and every body goes through `redact()` before it's sent.

Three layers:

```python
_PATTERNS = [
    # known token prefixes
    re.compile(r'\b(ntn_|secret_|sk-|sk_live_|rk_live_|ghp_|gho_|github_pat_|xox[abp]-|AKIA)[A-Za-z0-9_\-]{8,}'),
    # "password: xyz", "pw = xyz" and friends
    re.compile(r'(?i)((?:passwor[dt]|passwd|pw|pass|kennwort)\s*[:=]\s*)`?[^\s`,;]{4,}`?'),
    # long hex strings
    re.compile(r'\b[a-f0-9]{40,}\b'),
]

```

Then long base64-looking strings. Those are tricky because file paths and long file names look similar. A string only gets redacted if it has at least three uppercase letters, three lowercase and three digits, and doesn't look like a path or a readable file name.

And a `redact.txt` with literal strings, one per line, for anything the patterns can't know. At the end of each run the script prints how many spots it redacted, with only the start of each hit. That way I see when something new got caught. Keep that log local, it's still a hint.

It's a filter, not a guarantee. Still better than trusting myself to never paste a password into a note.

## Step 5: no duplicates, ever

The sync keeps a `state.json`: for every source item a key, the Notion page ID, and a hash of what was last sent.

```python
it = state["items"].get(key)
if it and it["hash"] == hh:
    return it["page"]          # unchanged, skip
if it:
    req("PATCH", f"pages/{it['page']}", {"properties": props})
    replace_body(it["page"], blocks)
else:
    pid = req("POST", "pages", {"parent": {"database_id": db}, "properties": props, "children": blocks[:90]})

```

Unchanged items cost nothing. Changed ones get updated in place. A page can only be created with up to 100 child blocks per request, so the first 90 go with the create and the rest gets appended after. Rich text is capped at 2,000 characters per item, so long fields get cut at 1,900.

Some rules on top:

- Pages with a **Manual** checkbox set are never overwritten. That's for things I edit in Notion on purpose.
- A task that disappears from my notes isn't deleted. It gets the status "No longer in notes".
- A page I delete in Notion gets recreated on the next run, because the source still exists. Delete the source, or tick Manual.

After the first import I ran it again as a dry run. No duplicates. If a cron job [can't run twice safely](/idempotency-cron-automation-duplicate-uploads/), it will eventually make a mess.

## Gotcha: archived tasks came back

The first version of the task splitter made some garbage: fragments like half a sentence, a lone bracket. I archived those through the API. Next run, they were still there on the board as "No longer in notes".

The reason: they were still in `state.json`. The sync saw a known key that wasn't in the notes anymore, and did what it's supposed to do. It set the status on that page.

Fix: when you clean up through the API, also remove those keys from the state file. Archive in Notion, delete from state, then run.

## Step 6: views and the nightly run

Board views (projects by company, tasks by status) are set up once by a separate script through the API. That needed a newer Notion API version than the rest, and grouping only worked when I passed the property ID plus a sort. I'm not going to pretend I understand why, it's what made the API stop complaining.

The sync runs every night at 03:30 as a Windows scheduled task, with "run as soon as possible after a missed start" on, in case the laptop was asleep at 03:30\. Output goes to a log file. How I set those tasks up is in [Windows Task Scheduler for PowerShell automation](/windows-task-scheduler-powershell-automation/).

The token sits in a file in my user folder, not in the repo and not in the script.

## What I'd do next time

Clean up first, sync second. An old public share is exactly the kind of thing you only find when you list everything. Make the root page by hand and connect it before writing any code. Build the secret filter before the first real run, not after. And treat the state file like part of the data: when you change something in Notion through the API, change the state file in the same step. Same thinking as with backups, the copy is only useful if you know [what it actually contains](/server-provider-outage-backup-lessons/).

---

### Related posts

- [Odoo: Send a Silent Internal Copy of Every Confirmed Booking (and Why the Customer Got It Instead)](https://blog.sudowl.com/odoo-automated-action-hidden-booking-copy-email/)
- [Gmail Inbox from 105 to 18 Threads Without Deleting Anything: Numbered Labels and a 14-Day Rule](https://blog.sudowl.com/gmail-numbered-labels-inbox-cleanup-without-deleting/)
- [From 2,782 Discord Messages to a Docs Site in Three Languages](https://blog.sudowl.com/discord-support-history-to-docs-site/)