How to Build Notion Sync Watcher Script for Specific Page Updates
🔍 WiseChecker

How to Build Notion Sync Watcher Script for Specific Page Updates

You want to automatically detect when a specific Notion page is updated and trigger a custom action such as sending a notification, syncing data to another app, or logging changes. Notion does not include a built-in webhook or change-tracking feature for individual pages, so you need a script that polls the Notion API and compares page versions. This article explains how to build a Notion sync watcher script that monitors a specific page for updates using Python and the Notion API.

The watcher script works by periodically fetching the page content and comparing it with a stored snapshot. When a change is detected, the script can execute any custom action you define. You will learn how to set up the Notion API integration, write the polling logic, and handle rate limits and common errors.

Key Takeaways: Building a Notion Sync Watcher Script

  • Notion API Integration: Create an internal integration in Notion and share the target page to get a read-only API key.
  • Python Requests Library: Use the requests library to fetch page properties and content from the Notion API endpoint.
  • Hash Comparison Logic: Store a SHA-256 hash of the page JSON response and compare it on each poll to detect changes.

ADVERTISEMENT

How the Notion Sync Watcher Script Works

The Notion API does not provide push-based webhooks or real-time change notifications. To watch for updates on a specific page, you must build a polling script that checks the page state at regular intervals. The script retrieves the page object from the Notion API, generates a cryptographic hash of the response, and compares it to the hash from the previous check. If the hashes differ, the page has been updated.

The script runs on a loop with a configurable sleep interval. Each iteration fetches the page, computes a hash, and triggers your custom action only when the hash changes. This approach avoids redundant actions and keeps the script lightweight. You need a Notion integration token with read access to the target page, and the page must be shared with the integration. The script can run on any system with Python 3.6 or later installed.

Prerequisites

Before writing the script, complete these setup steps:

  • A Notion account with access to the page you want to watch.
  • Python 3.6 or later installed on your machine.
  • The requests library installed via pip: pip install requests.
  • A Notion internal integration token. Go to https://www.notion.so/my-integrations, click New Integration, name it, and copy the Internal Integration Secret.
  • Share the target page with the integration. Open the page in Notion, click the three-dot menu in the top right, select Add connections, and choose your integration.

Steps to Write the Notion Sync Watcher Script

  1. Set up environment variables
    Store your Notion API token and the page ID in environment variables or a config file. The page ID is the 32-character string in the page URL after the workspace name and before the question mark. For example, in https://www.notion.so/MyPage-abc123def456..., the ID is abc123def456.
  2. Write the page fetch function
    Create a function that sends a GET request to the Notion API endpoint https://api.notion.com/v1/pages/{page_id}. Include headers: Authorization: Bearer YOUR_TOKEN, Notion-Version: 2022-06-28, and Content-Type: application/json. Return the JSON response.
  3. Implement the hash comparator
    Use Python’s hashlib library to compute a SHA-256 hash of the JSON response string. Store the hash in a variable. On each poll, compute the new hash and compare it to the stored hash. If they match, skip the action. If they differ, update the stored hash and run your custom action.
  4. Add the polling loop
    Wrap the fetch-and-compare logic in a while True loop. Call time.sleep(60) to wait 60 seconds between checks. Adjust the interval based on your needs but stay within Notion API rate limits of 3 requests per second per integration.
  5. Define the custom action
    Inside the change-detection block, write code for your desired action. For example, send an email via SMTP, log the change to a file, or update a local database. The action runs only when the page hash changes.

Full Script Example

Below is a complete Python script that watches a Notion page and prints a message when the page is updated. Replace YOUR_TOKEN and YOUR_PAGE_ID with your actual values.

import requests
import hashlib
import time
import json

NOTION_TOKEN = "YOUR_TOKEN"
PAGE_ID = "YOUR_PAGE_ID"
HEADERS = {
    "Authorization": f"Bearer {NOTION_TOKEN}",
    "Notion-Version": "2022-06-28",
    "Content-Type": "application/json"
}
URL = f"https://api.notion.com/v1/pages/{PAGE_ID}"

stored_hash = None

while True:
    try:
        response = requests.get(URL, headers=HEADERS)
        if response.status_code != 200:
            print(f"Error: {response.status_code} - {response.text}")
            time.sleep(60)
            continue
        page_data = response.json()
        current_hash = hashlib.sha256(json.dumps(page_data, sort_keys=True).encode()).hexdigest()
        if stored_hash is None:
            stored_hash = current_hash
            print("Initial page state recorded.")
        elif current_hash != stored_hash:
            stored_hash = current_hash
            print("Page has been updated!")
            # Insert your custom action here
        else:
            print("No changes detected.")
    except Exception as e:
        print(f"Exception occurred: {e}")
    time.sleep(60)

ADVERTISEMENT

Common Issues and How to Handle Them

Notion API Returns 404 Not Found

This error means the page ID is incorrect or the integration does not have access to the page. Verify the page ID is exactly 32 characters and that you have shared the page with the integration. Go to the page, click the three-dot menu, and check Add connections lists your integration.

Rate Limit Errors (HTTP 429)

The Notion API allows up to 3 requests per second per integration. If you set the sleep interval too low, you will hit the limit. Increase the sleep interval to at least 1 second between requests, or implement exponential backoff. In the example above, a 60-second interval keeps you well under the limit.

Script Detects Changes When No Changes Were Made

The Notion API may return different metadata on each request, such as timestamps or editor IDs, even if the page content has not changed. To avoid false positives, compute the hash only on the properties field of the page response instead of the entire object. Modify the hash line to: current_hash = hashlib.sha256(json.dumps(page_data.get('properties', {}), sort_keys=True).encode()).hexdigest().

Script Stops Running Unexpectedly

Network interruptions or API timeouts can crash the script. Wrap the entire loop body in a try-except block as shown in the example. Add logging to a file so you can review errors after a crash. Consider running the script as a systemd service on Linux or a scheduled task on Windows for persistence.

Polling Script vs Notion Automation: Key Differences

Item Polling Script Notion Automation (Notion AI / Zapier)
Trigger method Time-based polling Event-based (webhook or scheduled)
Custom logic Full Python control Limited to pre-built actions
Cost Free (your own hardware) Subscription required for Zapier premium
Real-time detection Delayed by polling interval Near real-time with webhooks
Complexity Requires coding No-code setup

This article covered building a Notion sync watcher script using Python and the Notion API. You can now monitor any specific page for updates and trigger custom actions like notifications, data exports, or local backups. To extend the script, add support for watching multiple pages by storing hashes in a dictionary keyed by page ID. For advanced use, integrate with Slack or Microsoft Teams using their webhook APIs.

ADVERTISEMENT