notion-sdk-py

repository·main·Indexed 24 days ago

https://github.com/ramnes/notion-sdk-py

A simple Python client library for the official Notion API, designed to mirror the functionality of the official JavaScript SDK. It enables developers to search for items, create pages, query and sort databases, and manage blocks. The library includes examples for automating tasks such as syncing GitHub issues and pull requests to Notion, generating random test data with automatic schema detection, and sending email notifications via SendGrid based on database changes.

Tokens
7.1K
Snippets
30
Records
50
Agent score
80%

What's inside notion-sdk-py

  1. Overview of Notion SDK Python example tasks

    main

    The examples are categorized by difficulty and specific API tasks:

    Basic Tasks

    • 1_add_block.py: Create a new block and append it to an existing Notion page.
    • 2_add_linked_block.py: Create and append new blocks, and add a link to the text of a new block.
    • 3_add_styled_block.py: Create and append new blocks, and apply text styles to them.

    Intermediate Tasks

    • 1_create_a_database.py: Create a new database with defined properties.
    • 2_add_page_to_database.py: Create a new database and add new pages to it.
    • 3_query_database.py: Create a new database, add pages to it, and filter the database entries.
    • 4_sort_database.py: Create a new database, add pages to it, and filter/sort the database entries.
    • 5_upload_file.py: Upload a file to Notion and attach it to a page as an image block.
  2. Features of the Generate Random Data example

    main

    The generate_random_data.py script provides the following capabilities:

    • Automatic Schema Detection: Automatically detects the schema of a provided Notion database.
    • Realistic Data Generation: Creates 10 test entries using data appropriate for the property types.
    • Querying Examples: Demonstrates how to filter and query the newly generated data.

    Supported Property Types:

    • Title & Rich Text
    • Number
    • Select & Multi-select
    • Date
    • Checkbox
    • URL, Email, Phone Number
    • Files (generated as external URLs)
  3. Configure automatic retries

    main

    The client automatically retries requests that fail due to rate limiting (429) or transient server errors (500, 503).

    • 429 (Rate Limited): Retried for all HTTP methods.
    • 500/503 (Server Errors): Retried only for idempotent methods (GET, DELETE).

    By default, it retries up to 2 times using exponential back-off with jitter. You can customize this using RetryOptions or disable it by setting retry=False.

    from notion_client import Client, RetryOptions
    
    notion = Client(
        auth="secret_...",
        retry=RetryOptions(
            max_retries=5,
            initial_retry_delay_ms=500,
            max_retry_delay_ms=60000,
        ),
    )
  4. Iterate or collect paginated API results

    main

    The SDK provides utility functions to handle paginated endpoints easily.

    • iterate_paginated_api(function, **kwargs): Returns a generator that yields results page by page. Use this for large datasets to save memory.
    • collect_paginated_api(function, **kwargs): Returns an in-memory array of all results. Use this only if the dataset is small enough to fit in memory.

    Async versions async_iterate_paginated_api and async_collect_paginated_api are also available.

    from notion_client.helpers import iterate_paginated_api
    
    for block in iterate_paginated_api(
        notion.blocks.children.list, block_id=parent_block_id
    ):
        # Do something with block.
        ...
  5. Set up integrations for GitHub and Notion sync

    main

    To use this sync script, you must configure two integrations:

    1. Notion Integration: Create a new integration in the Notion integrations dashboard. Once created, you must explicitly connect it to your Notion task database by navigating to the database/page, clicking the ... menu, and selecting Add connections.
    2. GitHub Integration: Create a GitHub personal access token that has read access to pull requests.
  6. Run the Database Email Update example

    main

    This example demonstrates how to poll a Notion database every 5 seconds to track changes to a 'Status' property and send an email notification via SendGrid when a change is detected.

    Prerequisites

    1. Install dependencies:

      pip install -r requirements.txt
    2. Set up SendGrid: Create an API key at SendGrid.

    3. Set up Notion:

      • Create an integration key at My Integrations.
      • Duplicate the database template.
      • Share the database with your integration using the Notion menu (••• menu → Add connections).

    Configuration

    Create a .env file by copying .env.example and providing the following values:

    NOTION_KEY=<your-notion-api-key>
    SENDGRID_KEY=<your-sendgrid-api-key>
    NOTION_DATABASE_ID=<your-notion-database-id>
    EMAIL_TO_FIELD=<recipient@example.com>
    EMAIL_FROM_FIELD=<sender@example.com>

    Execution

    Run the script using:

    python database_email_update.py
  7. Handle API errors with APIResponseError

    main

    When the API returns an unsuccessful response, the SDK raises an APIResponseError. You can inspect the code property and compare it against APIErrorCode constants to handle specific error cases gracefully.

    import logging
    from notion_client import APIErrorCode, APIResponseError, Client
    
    try:
        notion = Client(auth=os.environ["NOTION_TOKEN"])
        # ... api call
    except APIResponseError as error:
        if error.code == APIErrorCode.ObjectNotFound:
            # Handle specific error
            ...
        else:
            print(error)
  8. Enable structured logging with structlog

    main

    To use structured logging with notion-sdk-py, you must integrate the structlog library. You can do this by wrapping the standard Python logging.getLogger("notion-client") with a structlog logger and passing it to the Client constructor via the logger argument. Ensure you also set the log_level (e.g., logging.DEBUG) to see the desired level of detail.

    Note: You must manually add structlog as a dependency to your project.

    import logging
    import structlog
    from notion_client import Client
    
    logger = structlog.wrap_logger(
        logging.getLogger("notion-client"),
        logger_factory=structlog.stdlib.LoggerFactory(),
        wrapper_class=structlog.stdlib.BoundLogger,
    )
    
    notion = Client(auth=token, logger=logger, log_level=logging.DEBUG)
  9. Configure the NOTION_TOKEN environment variable

    main

    To authenticate with the Notion API, create an integration at notion.so/my-integrations and copy the provided token. Set this token in your environment as NOTION_TOKEN.

    Note: export only applies to the current shell session. For persistent configuration, add the export command to your shell configuration file or use a library like dotenv.

    export NOTION_TOKEN=ntn_abcd12345