### Install Example Dependencies Source: https://github.com/ramnes/notion-sdk-py/blob/main/examples/intro_to_notion_api/README.md Install the necessary Python dependencies for the examples, either globally or within a virtual environment. ```bash cd examples/intro_to_notion_api pip install -r requirements.txt ``` ```bash cd examples/intro_to_notion_api python -m venv venv source venv/bin/activate # On Windows use: venv\Scripts\activate pip install -r requirements.txt ``` -------------------------------- ### Clone and Install Dependencies Source: https://github.com/ramnes/notion-sdk-py/blob/main/examples/generate_random_data/README.md Clone the repository and install the necessary Python dependencies for the example. ```bash git clone https://github.com/ramnes/notion-sdk-py.git cd notion-sdk-py/examples/generate_random_data pip install -r requirements.txt ``` -------------------------------- ### Install notion-client Source: https://github.com/ramnes/notion-sdk-py/blob/main/examples/databases/README.md Install the notion-client package using pip. Ensure you have Python and pip installed. ```shell pip install notion-client ``` -------------------------------- ### Initialize Databases API Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Setup for interacting with Notion databases. ```python from notion_client import Client import os notion = Client(auth=os.environ["NOTION_TOKEN"]) ``` -------------------------------- ### Setup Virtual Environment Source: https://github.com/ramnes/notion-sdk-py/blob/main/docs/user_guides/quick_start.md Create and activate a Python virtual environment. ```shell python -m venv .venv && source .venv/bin/activate ``` -------------------------------- ### Run Notion API Examples as Modules Source: https://github.com/ramnes/notion-sdk-py/blob/main/examples/intro_to_notion_api/README.md Execute Notion API examples by running their respective Python modules directly. ```python python -m basic.1_add_block ``` ```python python -m intermediate.1_create_a_database ``` -------------------------------- ### Initialize Notion Client for Blocks Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Setup the Notion client instance to begin interacting with page content blocks. ```python from notion_client import Client import os notion = Client(auth=os.environ["NOTION_TOKEN"]) page_id = "5c6a28216bb14a7eb6e1c50111515c3d" ``` -------------------------------- ### Verify Python and Pip Installation Source: https://github.com/ramnes/notion-sdk-py/blob/main/docs/user_guides/quick_start.md Check that Python and pip are installed on your system. ```shell python --version pip --version ``` -------------------------------- ### Example Output Source: https://github.com/ramnes/notion-sdk-py/blob/main/docs/user_guides/quick_start.md Expected console output after running the user retrieval script. ```shell Aahnik Daw is a person 🙋‍♂️ TestIntegation is a bot 😅 ``` -------------------------------- ### Run Basic Notion API Examples Source: https://github.com/ramnes/notion-sdk-py/blob/main/examples/intro_to_notion_api/README.md Execute individual Python scripts to perform basic operations like adding blocks and styled blocks to a Notion page. ```python python basic/1_add_block.py ``` ```python python basic/2_add_linked_block.py ``` ```python python basic/3_add_styled_block.py ``` -------------------------------- ### Run Intermediate Notion API Examples Source: https://github.com/ramnes/notion-sdk-py/blob/main/examples/intro_to_notion_api/README.md Execute individual Python scripts for intermediate tasks such as creating databases, adding pages, querying, sorting, and uploading files. ```python python intermediate/1_create_a_database.py ``` ```python python intermediate/2_add_page_to_database.py ``` ```python python intermediate/3_query_database.py ``` ```python python intermediate/4_sort_database.py ``` ```python python intermediate/5_upload_file.py ``` -------------------------------- ### Configure structlog for Notion Client Source: https://github.com/ramnes/notion-sdk-py/blob/main/docs/user_guides/structured_logging.md Wraps the standard library logger with structlog and passes it to the Notion Client instance. Ensure the structlog dependency is installed in your project. ```python 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) ``` -------------------------------- ### GET /databases/{database_id} Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Retrieves the details of a specific database by its ID. ```APIDOC ## GET /databases/{database_id} ### Description Retrieves the metadata and configuration of a database. ### Method GET ### Endpoint /databases/{database_id} ### Parameters #### Path Parameters - **database_id** (string) - Required - The unique identifier of the database. ``` -------------------------------- ### Users API Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Endpoints for retrieving information about users, including listing all workspace users, retrieving a specific user by ID, and getting the current bot user. ```APIDOC ## GET /users ### Description List all users in the workspace. ### Method GET ### Endpoint /users ### Response #### Success Response (200) - **results** (array) - List of user objects ## GET /users/{user_id} ### Description Retrieve a specific user by their unique ID. ### Method GET ### Endpoint /users/{user_id} ### Parameters #### Path Parameters - **user_id** (string) - Required - The unique identifier of the user ## GET /users/me ### Description Get the bot user associated with the current integration token. ### Method GET ### Endpoint /users/me ``` -------------------------------- ### Update a Block Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Modifies the content of an existing block. This example updates a paragraph block. Ensure 'block-id-here' is a valid block ID. ```python notion.blocks.update( block_id="block-id-here", paragraph={ "rich_text": [{"type": "text", "text": {"content": "Updated content"}}] } ) ``` -------------------------------- ### Make Custom Notion API Requests Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Perform direct requests to Notion API endpoints using the `request` method for POST, GET, and other HTTP methods. Allows specifying path, method, body, query parameters, and custom authentication tokens or httpx clients. ```python from notion_client import Client import os import json notion = Client(auth=os.environ["NOTION_TOKEN"]) # POST request with body response = notion.request( path="comments", method="POST", body={ "parent": {"page_id": "5c6a28216bb14a7eb6e1c50111515c3d"}, "rich_text": [{"text": {"content": "Hello from custom request!"}}], } ) print(json.dumps(response, indent=2)) # GET request with query parameters response = notion.request( path="users", method="GET", query={"page_size": 10} ) # Use a different auth token for a specific request response = notion.request( path="users/me", method="GET", auth="different-token-here" ) # Using custom httpx client import httpx custom_http_client = httpx.Client( limits=httpx.Limits(max_connections=100), timeout=httpx.Timeout(30.0) ) notion = Client( auth=os.environ["NOTION_TOKEN"], client=custom_http_client ) ``` -------------------------------- ### Create Project Directory Source: https://github.com/ramnes/notion-sdk-py/blob/main/docs/user_guides/quick_start.md Create and enter a new directory for the project. ```shell mkdir learn-notion-sdk-py && cd learn-notion-sdk-py ``` -------------------------------- ### Initialize Notion Client Source: https://github.com/ramnes/notion-sdk-py/blob/main/docs/user_guides/quick_start.md Initialize the Notion client using the token from environment variables. ```python import os from notion_client import Client notion = Client(auth=os.environ["NOTION_TOKEN"]) ``` -------------------------------- ### Initialize Notion Client Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Configure the Notion client using an integration token. Supports synchronous, asynchronous, and custom-configured clients. ```python import os import logging from notion_client import Client, AsyncClient, RetryOptions # Basic synchronous client notion = Client(auth=os.environ["NOTION_TOKEN"]) # Asynchronous client async_notion = AsyncClient(auth=os.environ["NOTION_TOKEN"]) # Client with custom options notion = Client( auth=os.environ["NOTION_TOKEN"], log_level=logging.DEBUG, timeout_ms=120000, retry=RetryOptions( max_retries=5, initial_retry_delay_ms=500, max_retry_delay_ms=60000, ), ) # Disable automatic retries notion = Client(auth=os.environ["NOTION_TOKEN"], retry=False) # Using context manager with Client(auth=os.environ["NOTION_TOKEN"]) as notion: users = notion.users.list() print(users) ``` -------------------------------- ### Configure and Run Data Generation Source: https://github.com/ramnes/notion-sdk-py/blob/main/examples/generate_random_data/README.md Set your Notion integration token as an environment variable and then run the Python script to generate data. ```bash export NOTION_TOKEN=your-integration-token python generate_random_data.py ``` -------------------------------- ### Iterate and Collect Data Source Templates Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Demonstrates using helper functions to iterate through or collect all data source templates. Requires importing specific helper functions and initializing a Notion client. ```python from notion_client.helpers import ( iterate_data_source_templates, collect_data_source_templates, ) # Iterate through data source templates for template in iterate_data_source_templates( notion.data_sources.list_templates, data_source_id="data-source-id-here" ): print(f"Template: {template['name']}") ``` ```python templates = collect_data_source_templates( notion.data_sources.list_templates, data_source_id="data-source-id-here" ) ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/ramnes/notion-sdk-py/blob/main/examples/intro_to_notion_api/README.md Set your Notion API key and a target Notion page ID in a .env file for authentication and targeting. ```bash NOTION_API_KEY= NOTION_PAGE_ID= ``` -------------------------------- ### Run Create Database Script Source: https://github.com/ramnes/notion-sdk-py/blob/main/examples/databases/README.md Execute the Python script to create a database in Notion. The script requires the NOTION_TOKEN environment variable to be set. ```shell python create_database.py ``` -------------------------------- ### Iterate and Collect Paginated API Results (Async) Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Shows how to use asynchronous utility functions for iterating through or collecting paginated API results. Requires importing async helpers and initializing an AsyncClient. ```python from notion_client import AsyncClient from notion_client.helpers import ( async_iterate_paginated_api, async_collect_paginated_api, ) import os import asyncio # Async pagination async def fetch_all_users(): async_notion = AsyncClient(auth=os.environ["NOTION_TOKEN"]) # Async iteration async for user in async_iterate_paginated_api(async_notion.users.list): print(f"User: {user['name']}") # Async collection all_users = await async_collect_paginated_api(async_notion.users.list) return all_users users = asyncio.run(fetch_all_users()) ``` -------------------------------- ### Handle File Uploads Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Upload files to Notion using single-part for small files or multi-part for files exceeding 20MB. ```python from notion_client import Client import os notion = Client(auth=os.environ["NOTION_TOKEN"]) # Single-part file upload (files <= 20MB) file_path = "document.pdf" file_name = os.path.basename(file_path) # Create the file upload upload = notion.file_uploads.create( mode="single_part", filename=file_name, content_type="application/pdf" ) file_upload_id = upload["id"] # Send the file content with open(file_path, "rb") as f: response = notion.file_uploads.send( file_upload_id=file_upload_id, file=f ) if response["status"] == "uploaded": # Add file to a page property notion.pages.create( parent={"database_id": "database-id-here"}, properties={ "Name": {"title": [{"text": {"content": file_name}}]}, "Attachments": { "type": "files", "files": [{"type": "file_upload", "file_upload": {"id": file_upload_id}}] } } ) # Multi-part file upload (files > 20MB) large_file_upload = notion.file_uploads.create( mode="multi_part", filename="large_video.mp4", content_type="video/mp4", number_of_parts=5 ) # Send each part for part_number in range(1, 6): with open(f"chunk_{part_number}.bin", "rb") as chunk: notion.file_uploads.send( file_upload_id=large_file_upload["id"], file=chunk, part_number=part_number ) # Complete the multi-part upload notion.file_uploads.complete(file_upload_id=large_file_upload["id"]) # List all file uploads uploads = notion.file_uploads.list(status="uploaded") # Retrieve file upload status upload_status = notion.file_uploads.retrieve(file_upload_id=file_upload_id) ``` -------------------------------- ### Create Pages in Notion Database Source: https://github.com/ramnes/notion-sdk-py/wiki/Examples Authenticates with a Notion token, searches for a specific database by name, and creates multiple pages with predefined properties. Ensure your Notion token is valid and the database exists with the correct name and column labels. ```python # CRUD Example 1 import sys import random import notion_client # replace with your Token NOTION_TOKEN = 'secret_XyZXyZXyZXyZXyZXyZXyZXyZXyZXyZ' NOTION_DATABASE_NAME = "Test Notion SDK for Python Database" notion = notion_client.Client(auth=NOTION_TOKEN) print(f"Searching database '{NOTION_DATABASE_NAME}' ...", end="", flush=True) search_database = notion.search(**{ 'query': NOTION_DATABASE_NAME, 'property': 'object', 'value': 'database' }) if len(search_database['results']) == 0: print(" not found!") sys.exit() print(" found!") my_database_id = search_database['results'][0]['id'] # this is a bit useless since we already have the database id my_database = notion.databases.retrieve(database_id=my_database_id) # this will create 3 pages for page_id in range(1, 4): rand_page_type = random.choice(['Animal', 'Vegetal']) # set how other properties types here: # https://developers.notion.com/reference/database#database-property new_page_props = { 'Name': {'title': [{'text': {'content': f"My Page of {rand_page_type} {page_id}"}}}}, 'Value': {'number': page_id}, 'Link': {'type': 'url', 'url': f"http://examples.org/page/{page_id}"}, 'Tags': {'type': 'multi_select', 'multi_select': [{'name': rand_page_type}]} } notion_page = notion.pages.create( parent={'database_id': my_database['id']}, properties=new_page_props ) if notion_page['object'] == 'error': print("ERROR", notion_page['message']) continue print(f"Page for {rand_page_type} {page_id} created with id {notion_page['id']}") ``` -------------------------------- ### Clone Notion SDK Repository Source: https://github.com/ramnes/notion-sdk-py/blob/main/examples/intro_to_notion_api/README.md Clone the Notion SDK for Python repository and navigate into the project directory. ```bash git clone https://github.com/ramnes/notion-sdk-py.git cd notion-sdk-py ``` -------------------------------- ### Search for Pages and Databases Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Searches across Notion for pages and databases containing the query term. Requires the NOTION_TOKEN environment variable to be set. ```python from notion_client import Client import os notion = Client(auth=os.environ["NOTION_TOKEN"]) # Search for pages and databases results = notion.search(query="Project") for result in results["results"]: if result["object"] == "page": title = result["properties"].get("title", result["properties"].get("Name", {})) print(f"Page: {result['id']}") elif result["object"] == "database": print(f"Database: {result['title'][0]['plain_text']}") ``` -------------------------------- ### Initialize Asynchronous Notion Client Source: https://github.com/ramnes/notion-sdk-py/blob/main/README.md Initialize the asynchronous client for use in an asyncio environment. ```python from notion_client import AsyncClient notion = AsyncClient(auth=os.environ["NOTION_TOKEN"]) ``` -------------------------------- ### Fetch and List Users Source: https://github.com/ramnes/notion-sdk-py/blob/main/docs/user_guides/quick_start.md Retrieve and iterate through the list of users accessible to the integration. ```python users = notion.users.list() for user in users.get("results"): name, user_type = user["name"], user["type"] emoji = "😅" if user["type"] == "bot" else "🙋‍♂️" print(f"{name} is a {user_type} {emoji}") ``` -------------------------------- ### Iterate and Collect Paginated API Results (Sync) Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Provides synchronous utility functions to efficiently iterate through or collect all items from paginated API endpoints. Requires importing helper functions and initializing a Notion client. ```python from notion_client import Client from notion_client.helpers import ( iterate_paginated_api, collect_paginated_api, ) import os notion = Client(auth=os.environ["NOTION_TOKEN"]) # Iterate through all blocks in a page (memory efficient) for block in iterate_paginated_api( notion.blocks.children.list, block_id="page-id-here" ): print(f"Block: {block['type']}") ``` ```python all_blocks = collect_paginated_api( notion.blocks.children.list, block_id="page-id-here" ) print(f"Total blocks: {len(all_blocks)}") ``` -------------------------------- ### List and Search Custom Emojis Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Demonstrates how to list all custom emojis and filter them by name. Requires authentication with a Notion client. ```python emojis = notion.custom_emojis.list() for emoji in emojis["results"]: print(f"Emoji: {emoji['name']} - {emoji['url']}") ``` ```python filtered_emojis = notion.custom_emojis.list(name="celebration") ``` -------------------------------- ### Manage Notion Databases Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Create, retrieve, and update database properties using the Notion API. ```python new_database = notion.databases.create( parent={"type": "page_id", "page_id": "parent-page-id"}, title=[{"type": "text", "text": {"content": "Project Tracker"}}], icon={"type": "emoji", "emoji": "📊"}, initial_data_source={ "properties": { "Name": {"type": "title", "title": {}}, "Description": {"type": "rich_text", "rich_text": {}}, "Status": { "type": "select", "select": { "options": [ {"name": "Not Started", "color": "gray"}, {"name": "In Progress", "color": "blue"}, {"name": "Completed", "color": "green"}, ] } }, "Priority": { "type": "select", "select": { "options": [ {"name": "High", "color": "red"}, {"name": "Medium", "color": "yellow"}, {"name": "Low", "color": "green"}, ] } }, "Due Date": {"type": "date", "date": {}}, "Assignee": {"type": "people", "people": {}}, "Budget": {"type": "number", "number": {"format": "dollar"}}, "Completed": {"type": "checkbox", "checkbox": {}}, "Attachments": {"type": "files", "files": {}}, } } ) print(f"Database created: {new_database['url']}") # Retrieve a database database = notion.databases.retrieve(database_id="897e5a76-ae52-4b48-9fdf-e71f5945d1af") print(f"Database title: {database['title'][0]['plain_text']}") # Update database properties notion.databases.update( database_id="897e5a76-ae52-4b48-9fdf-e71f5945d1af", title=[{"type": "text", "text": {"content": "Updated Database Name"}}], description=[{"type": "text", "text": {"content": "Database for tracking projects"}}] ) ``` -------------------------------- ### POST /databases Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Creates a new database within a specified parent page with defined property types. ```APIDOC ## POST /databases ### Description Creates a new database with various property types such as title, select, date, people, number, and checkbox. ### Method POST ### Endpoint /databases ### Request Body - **parent** (object) - Required - The parent page ID. - **title** (array) - Required - The title of the database. - **icon** (object) - Optional - The icon for the database. - **initial_data_source** (object) - Required - The schema definition for database properties. ``` -------------------------------- ### Set Notion Integration Token Source: https://github.com/ramnes/notion-sdk-py/blob/main/docs/user_guides/quick_start.md Export the Notion integration token as an environment variable. ```shell export NOTION_TOKEN=ntn_abcd12345 ``` -------------------------------- ### Implement OAuth Authentication Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Manage OAuth token exchange, refresh, introspection, and revocation for third-party integrations. ```python from notion_client import Client # OAuth token exchange (after user authorization) notion = Client() # No auth needed for OAuth endpoints # Exchange authorization code for access token token_response = notion.oauth.token( client_id="your-client-id", client_secret="your-client-secret", grant_type="authorization_code", code="authorization-code-from-callback", redirect_uri="https://your-app.com/callback" ) access_token = token_response["access_token"] workspace_id = token_response["workspace_id"] print(f"Access token obtained for workspace: {workspace_id}") # Refresh an access token refreshed_token = notion.oauth.token( client_id="your-client-id", client_secret="your-client-secret", grant_type="refresh_token", refresh_token="existing-refresh-token" ) # Introspect a token to check its validity and scope token_info = notion.oauth.introspect( client_id="your-client-id", client_secret="your-client-secret", token=access_token ) print(f"Token active: {token_info['active']}") print(f"Scope: {token_info.get('scope')}") # Revoke a token notion.oauth.revoke( client_id="your-client-id", client_secret="your-client-secret", token=access_token ) ``` -------------------------------- ### Configure Client Logging Level Source: https://github.com/ramnes/notion-sdk-py/blob/main/README.md Set the log level to DEBUG to capture request and response bodies for debugging. Ensure logging is imported. ```python import logging from notion_client import Client notion = Client( auth=os.environ["NOTION_TOKEN"], log_level=logging.DEBUG, ) ``` -------------------------------- ### Paginated Custom Emoji Listing Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Shows how to retrieve all custom emojis using pagination, handling 'has_more' and 'next_cursor' for complete retrieval. Assumes a Notion client is initialized. ```python all_emojis = [] start_cursor = None while True: response = notion.custom_emojis.list(start_cursor=start_cursor, page_size=100) all_emojis.extend(response["results"]) if not response.get("has_more"): break start_cursor = response["next_cursor"] ``` -------------------------------- ### Make a Synchronous API Request Source: https://github.com/ramnes/notion-sdk-py/blob/main/README.md Make a request to a Notion API endpoint using the synchronous client and print the response. ```python from pprint import pprint list_users_response = notion.users.list() pprint(list_users_response) ``` -------------------------------- ### Import Default Constants Source: https://github.com/ramnes/notion-sdk-py/blob/main/README.md Import named constants for default client values, such as base URL, timeout, and retry parameters. ```python from notion_client import ( DEFAULT_BASE_URL, DEFAULT_TIMEOUT_MS, DEFAULT_MAX_RETRIES, DEFAULT_INITIAL_RETRY_DELAY_MS, DEFAULT_MAX_RETRY_DELAY_MS, MIN_VIEW_COLUMN_WIDTH, ) ``` -------------------------------- ### Configure Client with Custom Retry Options Source: https://github.com/ramnes/notion-sdk-py/blob/main/README.md Customize automatic retry behavior by providing a RetryOptions object. This allows adjusting the maximum number of retries and delay intervals. ```python from notion_client import Client, RetryOptions notion = Client( auth="secret_...", retry=RetryOptions( max_retries=5, # Maximum retry attempts (default: 2) initial_retry_delay_ms=500, # Initial delay in ms (default: 1000) max_retry_delay_ms=60000, # Maximum delay in ms (default: 60000) ), ) ``` -------------------------------- ### Make an Asynchronous API Request Source: https://github.com/ramnes/notion-sdk-py/blob/main/README.md Make a request to a Notion API endpoint using the asynchronous client. ```python list_users_response = await notion.users.list() pprint(list_users_response) ``` -------------------------------- ### Check for Full API Responses Source: https://github.com/ramnes/notion-sdk-py/blob/main/README.md Use helper functions to verify if an API object is a full representation before accessing its properties. ```python from notion_client.helpers import is_full_page full_or_partial_pages = notion.data_sources.query( data_source_id="897e5a76-ae52-4b48-9fdf-e71f5945d1af" ) for page in full_or_partial_pages["results"]: if not is_full_page_or_data_source(page): continue print(f"Created at: {page['created_time']}") ``` -------------------------------- ### Views API Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Create, retrieve, update, and delete database views. Views define how database content is displayed (table, board, calendar, etc.) with custom filters and sorts. ```APIDOC ## Views API Create, retrieve, update, and delete database views. Views define how database content is displayed (table, board, calendar, etc.) with custom filters and sorts. ### Create a database view **Method**: POST **Endpoint**: `/v1/views` **Description**: Creates a new view for a database. **Parameters**: - **database_id** (string) - Required - The ID of the database to create the view for. - **properties** (object) - Required - Properties of the view, including its type, name, and configuration. ### Retrieve a database view **Method**: GET **Endpoint**: `/v1/views/{view_id}` **Description**: Retrieves a specific database view. **Parameters**: - **view_id** (string) - Required - The ID of the view to retrieve. ### Update a database view **Method**: PATCH **Endpoint**: `/v1/views/{view_id}` **Description**: Updates an existing database view. **Parameters**: - **view_id** (string) - Required - The ID of the view to update. - **properties** (object) - Optional - New properties for the view. ### Delete a database view **Method**: DELETE **Endpoint**: `/v1/views/{view_id}` **Description**: Deletes a database view. **Parameters**: - **view_id** (string) - Required - The ID of the view to delete. ``` -------------------------------- ### Search Only for Pages Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Filters search results to include only pages, with a specified page size. Requires the NOTION_TOKEN environment variable. ```python pages = notion.search( query="Meeting Notes", filter={"property": "object", "value": "page"}, page_size=10 ) ``` -------------------------------- ### Make a custom POST request to the Notion API Source: https://github.com/ramnes/notion-sdk-py/blob/main/README.md Use this method to access endpoints not yet supported by dedicated SDK methods or to test new API versions. Prefer dedicated methods like notion.comments.create() when available. ```python response = notion.request( path="comments", method="post", body={ "parent": {"page_id": "5c6a28216bb14a7eb6e1c50111515c3d"}, "rich_text": [{"text": {"content": "Hello, world!"}}], }, # No `query` params in this example, only `body`. ) print(json.dumps(response, indent=2)) ``` -------------------------------- ### Query and Retrieve Data Sources Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Perform filtered queries, text searches, and retrieve metadata or templates for data sources. ```python from notion_client import Client import os notion = Client(auth=os.environ["NOTION_TOKEN"]) # Query a data source with filters results = notion.data_sources.query( data_source_id="897e5a76-ae52-4b48-9fdf-e71f5945d1af", filter={ "and": [ {"property": "Status", "select": {"equals": "In Progress"}}, {"property": "Due Date", "date": {"on_or_before": "2024-12-31"}}, ] }, sorts=[ {"property": "Due Date", "direction": "ascending"}, {"property": "Priority", "direction": "descending"}, ], page_size=50 ) for page in results["results"]: title = page["properties"]["Name"]["title"][0]["plain_text"] print(f"Task: {title}") # Query with text search results = notion.data_sources.query( data_source_id="897e5a76-ae52-4b48-9fdf-e71f5945d1af", filter={ "property": "Name", "rich_text": {"contains": "Bridge"} } ) # Retrieve a data source data_source = notion.data_sources.retrieve( data_source_id="897e5a76-ae52-4b48-9fdf-e71f5945d1af" ) # List templates available for a data source templates = notion.data_sources.list_templates( data_source_id="897e5a76-ae52-4b48-9fdf-e71f5945d1af" ) for template in templates["templates"]: print(f"Template: {template['name']} (default: {template['is_default']})") ``` -------------------------------- ### Make Custom API Requests Source: https://github.com/ramnes/notion-sdk-py/blob/main/README.md Use the request method to interact directly with Notion API endpoints. ```python import json ``` -------------------------------- ### File Uploads API Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Handles file uploads to Notion, supporting both single-part and multi-part uploads for different file sizes. ```APIDOC ## POST /file_uploads/create ### Description Initiates a file upload process. ### Method POST ### Endpoint /file_uploads/create ### Parameters #### Request Body - **mode** (string) - Required - Upload mode ('single_part' or 'multi_part'). - **filename** (string) - Required - The name of the file. - **content_type** (string) - Required - The MIME type of the file. - **number_of_parts** (integer) - Optional - Required for 'multi_part' mode, specifies the total number of parts. ### Response #### Success Response (200) - **id** (string) - The ID of the file upload. - **status** (string) - The initial status of the upload. #### Response Example ```json { "id": "upload-id-here", "status": "pending" } ``` ## POST /file_uploads/send ### Description Sends a part of the file content during an upload. ### Method POST ### Endpoint /file_uploads/send ### Parameters #### Request Body - **file_upload_id** (string) - Required - The ID of the file upload. - **file** (binary) - Required - The file content or chunk. - **part_number** (integer) - Optional - The number of the part being sent (for multi-part uploads). ### Response #### Success Response (200) - **status** (string) - The status of the upload part. #### Response Example ```json { "status": "uploaded" } ``` ## POST /file_uploads/complete ### Description Completes a multi-part file upload. ### Method POST ### Endpoint /file_uploads/complete ### Parameters #### Request Body - **file_upload_id** (string) - Required - The ID of the file upload. ### Response #### Success Response (200) - **status** (string) - The final status of the upload. #### Response Example ```json { "status": "completed" } ``` ## GET /file_uploads/list ### Description Lists all file uploads with a specified status. ### Method GET ### Endpoint /file_uploads/list ### Parameters #### Query Parameters - **status** (string) - Optional - Filter uploads by status (e.g., 'uploaded', 'pending', 'completed'). ### Response #### Success Response (200) - **results** (array) - An array of file upload objects. #### Response Example ```json { "results": [ {...} ] } ``` ## GET /file_uploads/retrieve ### Description Retrieves the status of a specific file upload. ### Method GET ### Endpoint /file_uploads/retrieve ### Parameters #### Query Parameters - **file_upload_id** (string) - Required - The ID of the file upload. ### Response #### Success Response (200) - **id** (string) - The ID of the file upload. - **status** (string) - The current status of the upload. #### Response Example ```json { "id": "upload-id-here", "status": "uploaded" } ``` ``` -------------------------------- ### Set Minimum Column Width in Table View Source: https://github.com/ramnes/notion-sdk-py/blob/main/README.md Use `MIN_VIEW_COLUMN_WIDTH` when creating or updating a table view to set the minimum possible width for a column, useful for collapsed columns. ```python await notion.views.create( database_id=database_id, name="My view", type="table", configuration={ "table": { "properties": [ { "property_id": checkbox_prop_id, "visible": True, "width": MIN_VIEW_COLUMN_WIDTH, }, ], }, }, ) ``` -------------------------------- ### POST /data_sources/{data_source_id}/query Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Queries and filters data sources to retrieve pages matching specific criteria. ```APIDOC ## POST /data_sources/{data_source_id}/query ### Description Queries a data source with support for complex filters, sorting, and pagination. ### Method POST ### Endpoint /data_sources/{data_source_id}/query ### Parameters #### Path Parameters - **data_source_id** (string) - Required - The unique identifier of the data source. #### Request Body - **filter** (object) - Optional - Filter criteria for the query. - **sorts** (array) - Optional - Sorting criteria for the results. - **page_size** (integer) - Optional - Number of results per page. ``` -------------------------------- ### Interact with Users API Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Retrieve workspace user information, including bot details and individual user profiles. ```python from notion_client import Client import os notion = Client(auth=os.environ["NOTION_TOKEN"]) # List all users in the workspace users_response = notion.users.list() for user in users_response["results"]: print(f"User: {user['name']} ({user['type']})") if user["type"] == "person": print(f" Email: {user['person'].get('email')}") # Retrieve a specific user by ID user_id = "d40e767c-d7af-4b18-a86d-55c61f1e39a4" user = notion.users.retrieve(user_id=user_id) print(f"Retrieved user: {user['name']}") # Get the bot user associated with the current token me = notion.users.me() print(f"Bot name: {me['name']}") print(f"Bot ID: {me['id']}") # Expected output: # {'results': [{'id': 'd40e767c-...', 'name': 'Avocado Lovelace', 'type': 'person', ...}]} ``` -------------------------------- ### Manage Database Views Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Perform CRUD operations on database views and execute queries for data retrieval. ```python view = notion.views.create( database_id="database-id-here", name="Active Tasks", type="table", filter={ "property": "Status", "select": {"does_not_equal": "Completed"} }, sorts=[ {"property": "Due Date", "direction": "ascending"} ], configuration={ "table": { "properties": [ {"property_id": "title", "visible": True, "width": 300}, {"property_id": "status-prop-id", "visible": True, "width": 150}, {"property_id": "checkbox-prop-id", "visible": True, "width": MIN_VIEW_COLUMN_WIDTH}, # Collapsed column ] } } ) print(f"View created: {view['id']}") # List views for a database views = notion.views.list(database_id="database-id-here") for view in views["results"]: print(f"View: {view['name']} ({view['type']})") # Retrieve a view view = notion.views.retrieve(view_id="view-id-here") # Update a view notion.views.update( view_id="view-id-here", name="Renamed View", filter={"property": "Priority", "select": {"equals": "High"}} ) # Delete a view notion.views.delete(view_id="view-id-here") # Create and execute a view query for efficient data retrieval query = notion.views.queries.create(view_id="view-id-here", page_size=50) results = notion.views.queries.results( view_id="view-id-here", query_id=query["id"] ) notion.views.queries.delete(view_id="view-id-here", query_id=query["id"]) ``` -------------------------------- ### Search Only for Databases Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Filters search results to include only databases, sorted by last edited time in descending order. Requires the NOTION_TOKEN environment variable. ```python databases = notion.search( query="Tasks", filter={"property": "object", "value": "database"}, sort={"direction": "descending", "timestamp": "last_edited_time"} ) ``` -------------------------------- ### Create a Comment on a Page Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Creates a new comment on a specified page, including text and user mentions. Requires a valid page_id and user_id. ```python from notion_client import Client import os notion = Client(auth=os.environ["NOTION_TOKEN"]) # Create a comment on a page comment = notion.comments.create( parent={"page_id": "5c6a28216bb14a7eb6e1c50111515c3d"}, rich_text=[ {"type": "text", "text": {"content": "Great progress on this task! "}}, {"type": "mention", "mention": {"type": "user", "user": {"id": "user-id-here"}}}, {"type": "text", "text": {"content": " please review."}} ] ) print(f"Comment created: {comment['id']}") ``` -------------------------------- ### Custom Requests Source: https://github.com/ramnes/notion-sdk-py/blob/main/README.md Allows making direct requests to Notion API endpoints using the `request()` method for flexibility beyond pre-built client methods. ```APIDOC ## Custom Requests ### Description For scenarios not covered by the SDK's pre-built methods, you can use the `request()` method to make direct calls to Notion API endpoints. ### Method Signature `request(method, path, **kwargs)` ### Parameters - **`method`** (string) - Required - The HTTP method (e.g., 'GET', 'POST', 'PATCH', 'DELETE'). - **`path`** (string) - Required - The API endpoint path (e.g., '/v1/pages'). - **`**kwargs`** - Optional - Additional arguments to pass to the request, such as `json` for request body or `params` for query parameters. ### Example Usage ```python import json # Assuming 'notion' is an initialized Notion client instance # response = notion.request( # method='POST', # path='/v1/pages', # json={ # "parent": {"page_id": "YOUR_PAGE_ID"}, # "properties": {"title": "Untitled" # } # } # ) ``` ``` -------------------------------- ### Paginated Search Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Performs a paginated search to retrieve all results for a query, handling 'has_more' and 'next_cursor'. Requires the NOTION_TOKEN environment variable. ```python all_results = [] start_cursor = None while True: response = notion.search(query="Documentation", start_cursor=start_cursor) all_results.extend(response["results"]) if not response["has_more"]: break start_cursor = response["next_cursor"] print(f"Total results: {len(all_results)}") ``` -------------------------------- ### Pages API Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Endpoints for creating, retrieving, updating, and managing Notion pages, including support for properties, children blocks, and archiving. ```APIDOC ## POST /pages ### Description Create a new page in a database or as a child of another page. ### Method POST ### Endpoint /pages ### Request Body - **parent** (object) - Required - The parent database or page ID - **properties** (object) - Required - Page property values - **children** (array) - Optional - Initial blocks for the page ## GET /pages/{page_id} ### Description Retrieve a page by its unique ID. ### Method GET ### Endpoint /pages/{page_id} ### Parameters #### Path Parameters - **page_id** (string) - Required - The unique identifier of the page ## PATCH /pages/{page_id} ### Description Update page properties, icon, or archive status. ### Method PATCH ### Endpoint /pages/{page_id} ### Parameters #### Path Parameters - **page_id** (string) - Required - The unique identifier of the page ### Request Body - **properties** (object) - Optional - Updated page properties - **icon** (object) - Optional - Page icon - **archived** (boolean) - Optional - Set to true to archive the page ``` -------------------------------- ### PATCH /databases/{database_id} Source: https://context7.com/ramnes/notion-sdk-py/llms.txt Updates the title and description of an existing database. ```APIDOC ## PATCH /databases/{database_id} ### Description Updates the properties of an existing database. ### Method PATCH ### Endpoint /databases/{database_id} ### Parameters #### Path Parameters - **database_id** (string) - Required - The unique identifier of the database. #### Request Body - **title** (array) - Optional - The new title for the database. - **description** (array) - Optional - The new description for the database. ``` -------------------------------- ### Collect Paginated API Results Source: https://github.com/ramnes/notion-sdk-py/blob/main/README.md Retrieve all results from a paginated API into an in-memory array. Ensure the dataset is small enough to fit in memory before use. ```python from notion_client.helpers import collect_paginated_api blocks = collect_paginated_api( notion.blocks.children.list, block_id=parent_block_id ) # Do something with blocks. ``` -------------------------------- ### Query Data Source with Filter Source: https://github.com/ramnes/notion-sdk-py/blob/main/README.md Query a data source with specific filter parameters. Endpoint parameters are grouped into a single object. ```python my_page = notion.data_sources.query( **{ "data_source_id": "897e5a76-ae52-4b48-9fdf-e71f5945d1af", "filter": { "property": "Landmark", "rich_text": { "contains": "Bridge", }, }, } ) ```