def pick(base: Dict[Any, Any], *keys: str) -> Dict[Any, Any]:
"""Return a dict composed of key value pairs for keys passed as args."""
result = {}
for key in keys:
diff --git a/search/search_index.json b/search/search_index.json
index 7ad42c3..490cd14 100644
--- a/search/search_index.json
+++ b/search/search_index.json
@@ -1 +1 @@
-{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Home","text":"notion-sdk-py is a simple and easy to use client library for the official Notion API.
It is meant to be a Python version of the reference JavaScript SDK, so usage should be very similar between both. \ud83d\ude0a (If not, please open an issue or PR!)
\ud83d\udce2 Announcement (18-12-2024) \u2014 Release 2.3.0 is out! It adds in_trash
support for pages, Python 3.13 official support, fixes and security updates.
"},{"location":"#installation","title":"Installation","text":"pip install notion-client\n
"},{"location":"#usage","title":"Usage","text":"Use Notion's Getting Started Guide to get set up to use Notion's API.
Import and initialize a client using an integration token or an OAuth access token.
import os\nfrom notion_client import Client\n\nnotion = Client(auth=os.environ[\"NOTION_TOKEN\"])\n
In an asyncio environment, use the asynchronous client instead:
from notion_client import AsyncClient\n\nnotion = AsyncClient(auth=os.environ[\"NOTION_TOKEN\"])\n
Make a request to any Notion API endpoint.
See the complete list of endpoints in the API reference.
from pprint import pprint\n\nlist_users_response = notion.users.list()\npprint(list_users_response)\n
or with the asynchronous client:
list_users_response = await notion.users.list()\npprint(list_users_response)\n
This would output something like:
{'results': [{'avatar_url': 'https://secure.notion-static.com/e6a352a8-8381-44d0-a1dc-9ed80e62b53d.jpg',\n 'id': 'd40e767c-d7af-4b18-a86d-55c61f1e39a4',\n 'name': 'Avocado Lovelace',\n 'object': 'user',\n 'person': {'email': 'avo@example.org'},\n 'type': 'person'},\n ...]}\n
All API endpoints are available in both the synchronous and asynchronous clients.
Endpoint parameters are grouped into a single object. You don't need to remember which parameters go in the path, query, or body.
my_page = notion.databases.query(\n **{\n \"database_id\": \"897e5a76-ae52-4b48-9fdf-e71f5945d1af\",\n \"filter\": {\n \"property\": \"Landmark\",\n \"rich_text\": {\n \"contains\": \"Bridge\",\n },\n },\n }\n)\n
"},{"location":"#handling-errors","title":"Handling errors","text":"If the API returns an unsuccessful response, an APIResponseError
will be raised.
The error contains properties from the response, and the most helpful is code
. You can compare code
to the values in the APIErrorCode
object to avoid misspelling error codes.
import logging\nfrom notion_client import APIErrorCode, APIResponseError\n\ntry:\n my_page = notion.databases.query(\n **{\n \"database_id\": \"897e5a76-ae52-4b48-9fdf-e71f5945d1af\",\n \"filter\": {\n \"property\": \"Landmark\",\n \"rich_text\": {\n \"contains\": \"Bridge\",\n },\n },\n }\n )\nexcept APIResponseError as error:\n if error.code == APIErrorCode.ObjectNotFound:\n ... # For example: handle by asking the user to select a different database\n else:\n # Other error handling code\n logging.error(error)\n
"},{"location":"#logging","title":"Logging","text":"The client emits useful information to a logger. By default, it only emits warnings and errors.
If you're debugging an application, and would like the client to log request & response bodies, set the log_level
option to logging.DEBUG
.
notion = Client(\n auth=os.environ[\"NOTION_TOKEN\"],\n log_level=logging.DEBUG,\n)\n
You may also set a custom logger
to emit logs to a destination other than stdout
. Have a look at Python's logging cookbook if you want to create your own logger.
"},{"location":"#client-options","title":"Client options","text":"Client
and AsyncClient
both support the following options on initialization. These options are all keys in the single constructor parameter.
Option Default value Type Description auth
None
string
Bearer token for authentication. If left undefined, the auth
parameter should be set on each request. log_level
logging.WARNING
int
Verbosity of logs the instance will produce. By default, logs are written to stdout
. timeout_ms
60_000
int
Number of milliseconds to wait before emitting a RequestTimeoutError
base_url
\"https://api.notion.com\"
string
The root URL for sending API requests. This can be changed to test with a mock server. logger
Log to console logging.Logger
A custom logger."},{"location":"#full-api-responses","title":"Full API responses","text":"The following functions can distinguish between full and partial API responses.
Function Purpose is_full_page
Determine whether an object is a full Page object is_full_block
Determine whether an object is a full Block object is_full_database
Determine whether an object is a full Database object is_full_page_or_database
Determine whether an object is a full Page object or Database object is_full_user
Determine whether an object is a full User object is_full_comment
Determine whether an object is a full Comment object from notion_client.helpers import is_full_page\n\nfull_or_partial_pages = await notion.databases.query(\n database_id=\"897e5a76-ae52-4b48-9fdf-e71f5945d1af\"\n)\n\nfor page in full_or_partial_pages[\"results\"]:\n if not is_full_page_or_database(page):\n continue\n print(f\"Created at: {page['created_time']}\")\n
"},{"location":"#utility-functions","title":"Utility functions","text":"These functions can be helpful for dealing with any of the paginated APIs.
iterate_paginated_api(function, **kwargs)
and its async version async_iterate_paginated_api(function, **kwargs)
turn any paginated API into a generator.
The function
parameter must accept a start_cursor
argument. Example: notion.blocks.children.list
.
from notion_client.helpers import iterate_paginated_api\n\nfor block in iterate_paginated_api(\n notion.databases.query, database_id=\"897e5a76-ae52-4b48-9fdf-e71f5945d1af\"\n):\n # Do something with block.\n ...\n
If you don't need a generator, collect_paginated_api(function, **kwargs)
and its async version async_collect_paginated_api(function, **kwargs)
have the same behavior than the previous functions, but return a list of all results from the paginated API.
from notion_client.helpers import collect_paginated_api\n\nall_results = collect_paginated_api(\n notion.databases.query, database_id=\"897e5a76-ae52-4b48-9fdf-e71f5945d1af\"\n)\n
"},{"location":"#testing","title":"Testing","text":"Run the tests with the pytest
command. If you want to test against all Python versions, you can run tox
instead.
The tests are using pytest-vcr
's cassettes for simulating requests to the Notion API. To create new tests or run them without cassettes, you need to set up the environment variables NOTION_TOKEN
and NOTION_TEST_PAGE_ID
(a page where your integration has all the capabilities enabled).
The code will use the page at NOTION_TEST_PAGE_ID
to generate a temporary environment with the Notion objects to be tested, which will be deleted at the end of the session.
"},{"location":"#requirements","title":"Requirements","text":"This package supports the following minimum versions:
- Python >= 3.7
- httpx >= 0.15.0
Earlier versions may still work, but we encourage people building new applications to upgrade to the current stable.
"},{"location":"#getting-help","title":"Getting help","text":"If you want to submit a feature request for Notion's API, or are experiencing any issues with the API platform, please email developers@makenotion.com
.
If you found a bug with the library, please submit an issue.
"},{"location":"#_1","title":"Home","text":""},{"location":"SUMMARY/","title":"SUMMARY","text":" - Home
- User guides
- Quick start
- Structured logging
- More examples
- Reference
- Client
- API endpoints
- Errors
- Helpers
- Development
- Coverage report
- Contributing guidelines
- License
"},{"location":"license/","title":"License","text":"The MIT License (MIT)\n\nCopyright (c) 2021-2023 Guillaume Gelin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n
"},{"location":"contributing/contributing/","title":"Contributing guidelines","text":"Tip
If you are a first time contributor, please start by reading this fantastic guide.
Any serious contribution to notion-sdk-py is always welcome, regardless of your experience.
If you want to contribute on the code specifically:
- Install Git and Python on your system.
- Fork the repository and clone it.
-
Checkout a new feature branch from main
:
git checkout my-feature\n
-
Install dependencies inside a virtual environment:
python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements/dev.txt\n
-
Install pre-commit hooks:
pre-commit install\n
You should now be ready to hack!
You can run the tests with pytest
in the main directory. Please make sure the tests (and pre-commit hooks) pass before opening a pull request.
Coverage must stay at 100%. Write tests if you add new features.
Thanks for your help!
"},{"location":"reference/api_endpoints/","title":"API endpoints","text":"Notion API endpoints.
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.BlocksChildrenEndpoint","title":"BlocksChildrenEndpoint
","text":" Bases: Endpoint
Source code in notion_client/api_endpoints.py
class BlocksChildrenEndpoint(Endpoint):\n def append(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Create and append new children blocks to the block using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/patch-block-children)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}/children\",\n method=\"PATCH\",\n body=pick(kwargs, \"children\", \"after\"),\n auth=kwargs.get(\"auth\"),\n )\n\n def list(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Return a paginated array of child [block objects](https://developers.notion.com/reference/block) contained in the block.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-block-children)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}/children\",\n method=\"GET\",\n query=pick(kwargs, \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.BlocksChildrenEndpoint.append","title":"append(block_id, **kwargs)
","text":"Create and append new children blocks to the block using the ID specified.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def append(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Create and append new children blocks to the block using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/patch-block-children)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}/children\",\n method=\"PATCH\",\n body=pick(kwargs, \"children\", \"after\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.BlocksChildrenEndpoint.list","title":"list(block_id, **kwargs)
","text":"Return a paginated array of child block objects contained in the block.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def list(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Return a paginated array of child [block objects](https://developers.notion.com/reference/block) contained in the block.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-block-children)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}/children\",\n method=\"GET\",\n query=pick(kwargs, \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.BlocksEndpoint","title":"BlocksEndpoint
","text":" Bases: Endpoint
Source code in notion_client/api_endpoints.py
class BlocksEndpoint(Endpoint):\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n super().__init__(*args, **kwargs)\n self.children = BlocksChildrenEndpoint(*args, **kwargs)\n\n def retrieve(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a [Block object](https://developers.notion.com/reference/block) using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-block)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}\", method=\"GET\", auth=kwargs.get(\"auth\")\n )\n\n def update(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Update the content for the specified `block_id` based on the block type.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/update-a-block)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}\",\n method=\"PATCH\",\n body=pick(\n kwargs,\n \"embed\",\n \"type\",\n \"archived\",\n \"bookmark\",\n \"image\",\n \"video\",\n \"pdf\",\n \"file\",\n \"audio\",\n \"code\",\n \"equation\",\n \"divider\",\n \"breadcrumb\",\n \"table_of_contents\",\n \"link_to_page\",\n \"table_row\",\n \"heading_1\",\n \"heading_2\",\n \"heading_3\",\n \"paragraph\",\n \"bulleted_list_item\",\n \"numbered_list_item\",\n \"quote\",\n \"to_do\",\n \"toggle\",\n \"template\",\n \"callout\",\n \"synced_block\",\n \"table\",\n ),\n auth=kwargs.get(\"auth\"),\n )\n\n def delete(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Set a [Block object](https://developers.notion.com/reference/block), including page blocks, to `archived: true`.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/delete-a-block)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}\",\n method=\"DELETE\",\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.BlocksEndpoint.delete","title":"delete(block_id, **kwargs)
","text":"Set a Block object, including page blocks, to archived: true
.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def delete(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Set a [Block object](https://developers.notion.com/reference/block), including page blocks, to `archived: true`.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/delete-a-block)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}\",\n method=\"DELETE\",\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.BlocksEndpoint.retrieve","title":"retrieve(block_id, **kwargs)
","text":"Retrieve a Block object using the ID specified.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def retrieve(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a [Block object](https://developers.notion.com/reference/block) using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-block)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}\", method=\"GET\", auth=kwargs.get(\"auth\")\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.BlocksEndpoint.update","title":"update(block_id, **kwargs)
","text":"Update the content for the specified block_id
based on the block type.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def update(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Update the content for the specified `block_id` based on the block type.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/update-a-block)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}\",\n method=\"PATCH\",\n body=pick(\n kwargs,\n \"embed\",\n \"type\",\n \"archived\",\n \"bookmark\",\n \"image\",\n \"video\",\n \"pdf\",\n \"file\",\n \"audio\",\n \"code\",\n \"equation\",\n \"divider\",\n \"breadcrumb\",\n \"table_of_contents\",\n \"link_to_page\",\n \"table_row\",\n \"heading_1\",\n \"heading_2\",\n \"heading_3\",\n \"paragraph\",\n \"bulleted_list_item\",\n \"numbered_list_item\",\n \"quote\",\n \"to_do\",\n \"toggle\",\n \"template\",\n \"callout\",\n \"synced_block\",\n \"table\",\n ),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.CommentsEndpoint","title":"CommentsEndpoint
","text":" Bases: Endpoint
Source code in notion_client/api_endpoints.py
class CommentsEndpoint(Endpoint):\n def create(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Create a new comment in the specified page or existing discussion thread.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/create-a-comment)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"comments\",\n method=\"POST\",\n body=pick(kwargs, \"parent\", \"discussion_id\", \"rich_text\"),\n auth=kwargs.get(\"auth\"),\n )\n\n def list(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a list of un-resolved [Comment objects](https://developers.notion.com/reference/comment-object) from the specified block.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-comment)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"comments\",\n method=\"GET\",\n query=pick(kwargs, \"block_id\", \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.CommentsEndpoint.create","title":"create(**kwargs)
","text":"Create a new comment in the specified page or existing discussion thread.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def create(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Create a new comment in the specified page or existing discussion thread.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/create-a-comment)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"comments\",\n method=\"POST\",\n body=pick(kwargs, \"parent\", \"discussion_id\", \"rich_text\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.CommentsEndpoint.list","title":"list(**kwargs)
","text":"Retrieve a list of un-resolved Comment objects from the specified block.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def list(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a list of un-resolved [Comment objects](https://developers.notion.com/reference/comment-object) from the specified block.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-comment)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"comments\",\n method=\"GET\",\n query=pick(kwargs, \"block_id\", \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.DatabasesEndpoint","title":"DatabasesEndpoint
","text":" Bases: Endpoint
Source code in notion_client/api_endpoints.py
class DatabasesEndpoint(Endpoint):\n def list(self, **kwargs: Any) -> SyncAsync[Any]: # pragma: no cover\n \"\"\"List all [Databases](https://developers.notion.com/reference/database) shared with the authenticated integration.\n\n > \u26a0\ufe0f **Deprecated endpoint**\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-databases)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"databases\",\n method=\"GET\",\n query=pick(kwargs, \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n\n def query(self, database_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Get a list of [Pages](https://developers.notion.com/reference/page) contained in the database.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/post-database-query)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"databases/{database_id}/query\",\n method=\"POST\",\n query=pick(kwargs, \"filter_properties\"),\n body=pick(kwargs, \"filter\", \"sorts\", \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n\n def retrieve(self, database_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a [Database object](https://developers.notion.com/reference/database) using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-database)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"databases/{database_id}\", method=\"GET\", auth=kwargs.get(\"auth\")\n )\n\n def create(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Create a database as a subpage in the specified parent page.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/create-a-database)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"databases\",\n method=\"POST\",\n body=pick(\n kwargs, \"parent\", \"title\", \"properties\", \"icon\", \"cover\", \"is_inline\"\n ),\n auth=kwargs.get(\"auth\"),\n )\n\n def update(self, database_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Update an existing database as specified by the parameters.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/update-a-database)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"databases/{database_id}\",\n method=\"PATCH\",\n body=pick(\n kwargs,\n \"properties\",\n \"title\",\n \"description\",\n \"icon\",\n \"cover\",\n \"is_inline\",\n ),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.DatabasesEndpoint.create","title":"create(**kwargs)
","text":"Create a database as a subpage in the specified parent page.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def create(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Create a database as a subpage in the specified parent page.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/create-a-database)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"databases\",\n method=\"POST\",\n body=pick(\n kwargs, \"parent\", \"title\", \"properties\", \"icon\", \"cover\", \"is_inline\"\n ),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.DatabasesEndpoint.list","title":"list(**kwargs)
","text":"List all Databases shared with the authenticated integration.
\u26a0\ufe0f Deprecated endpoint
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def list(self, **kwargs: Any) -> SyncAsync[Any]: # pragma: no cover\n \"\"\"List all [Databases](https://developers.notion.com/reference/database) shared with the authenticated integration.\n\n > \u26a0\ufe0f **Deprecated endpoint**\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-databases)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"databases\",\n method=\"GET\",\n query=pick(kwargs, \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.DatabasesEndpoint.query","title":"query(database_id, **kwargs)
","text":"Get a list of Pages contained in the database.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def query(self, database_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Get a list of [Pages](https://developers.notion.com/reference/page) contained in the database.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/post-database-query)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"databases/{database_id}/query\",\n method=\"POST\",\n query=pick(kwargs, \"filter_properties\"),\n body=pick(kwargs, \"filter\", \"sorts\", \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.DatabasesEndpoint.retrieve","title":"retrieve(database_id, **kwargs)
","text":"Retrieve a Database object using the ID specified.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def retrieve(self, database_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a [Database object](https://developers.notion.com/reference/database) using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-database)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"databases/{database_id}\", method=\"GET\", auth=kwargs.get(\"auth\")\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.DatabasesEndpoint.update","title":"update(database_id, **kwargs)
","text":"Update an existing database as specified by the parameters.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def update(self, database_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Update an existing database as specified by the parameters.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/update-a-database)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"databases/{database_id}\",\n method=\"PATCH\",\n body=pick(\n kwargs,\n \"properties\",\n \"title\",\n \"description\",\n \"icon\",\n \"cover\",\n \"is_inline\",\n ),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.PagesEndpoint","title":"PagesEndpoint
","text":" Bases: Endpoint
Source code in notion_client/api_endpoints.py
class PagesEndpoint(Endpoint):\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n super().__init__(*args, **kwargs)\n self.properties = PagesPropertiesEndpoint(*args, **kwargs)\n\n def create(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Create a new page in the specified database or as a child of an existing page.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/post-page)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"pages\",\n method=\"POST\",\n body=pick(kwargs, \"parent\", \"properties\", \"children\", \"icon\", \"cover\"),\n auth=kwargs.get(\"auth\"),\n )\n\n def retrieve(self, page_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a [Page object](https://developers.notion.com/reference/page) using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-page)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"pages/{page_id}\",\n method=\"GET\",\n query=pick(kwargs, \"filter_properties\"),\n auth=kwargs.get(\"auth\"),\n )\n\n def update(self, page_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Update [page property values](https://developers.notion.com/reference/page#property-value-object) for the specified page.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/patch-page)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"pages/{page_id}\",\n method=\"PATCH\",\n body=pick(kwargs, \"in_trash\", \"archived\", \"properties\", \"icon\", \"cover\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.PagesEndpoint.create","title":"create(**kwargs)
","text":"Create a new page in the specified database or as a child of an existing page.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def create(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Create a new page in the specified database or as a child of an existing page.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/post-page)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"pages\",\n method=\"POST\",\n body=pick(kwargs, \"parent\", \"properties\", \"children\", \"icon\", \"cover\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.PagesEndpoint.retrieve","title":"retrieve(page_id, **kwargs)
","text":"Retrieve a Page object using the ID specified.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def retrieve(self, page_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a [Page object](https://developers.notion.com/reference/page) using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-page)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"pages/{page_id}\",\n method=\"GET\",\n query=pick(kwargs, \"filter_properties\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.PagesEndpoint.update","title":"update(page_id, **kwargs)
","text":"Update page property values for the specified page.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def update(self, page_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Update [page property values](https://developers.notion.com/reference/page#property-value-object) for the specified page.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/patch-page)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"pages/{page_id}\",\n method=\"PATCH\",\n body=pick(kwargs, \"in_trash\", \"archived\", \"properties\", \"icon\", \"cover\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.PagesPropertiesEndpoint","title":"PagesPropertiesEndpoint
","text":" Bases: Endpoint
Source code in notion_client/api_endpoints.py
class PagesPropertiesEndpoint(Endpoint):\n def retrieve(self, page_id: str, property_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a `property_item` object for a given `page_id` and `property_id`.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-page-property)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"pages/{page_id}/properties/{property_id}\",\n method=\"GET\",\n auth=kwargs.get(\"auth\"),\n query=pick(kwargs, \"start_cursor\", \"page_size\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.PagesPropertiesEndpoint.retrieve","title":"retrieve(page_id, property_id, **kwargs)
","text":"Retrieve a property_item
object for a given page_id
and property_id
.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def retrieve(self, page_id: str, property_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a `property_item` object for a given `page_id` and `property_id`.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-page-property)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"pages/{page_id}/properties/{property_id}\",\n method=\"GET\",\n auth=kwargs.get(\"auth\"),\n query=pick(kwargs, \"start_cursor\", \"page_size\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.SearchEndpoint","title":"SearchEndpoint
","text":" Bases: Endpoint
Source code in notion_client/api_endpoints.py
class SearchEndpoint(Endpoint):\n def __call__(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Search all pages and child pages that are shared with the integration.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/post-search)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"search\",\n method=\"POST\",\n body=pick(kwargs, \"query\", \"sort\", \"filter\", \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.SearchEndpoint.__call__","title":"__call__(**kwargs)
","text":"Search all pages and child pages that are shared with the integration.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def __call__(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Search all pages and child pages that are shared with the integration.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/post-search)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"search\",\n method=\"POST\",\n body=pick(kwargs, \"query\", \"sort\", \"filter\", \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.UsersEndpoint","title":"UsersEndpoint
","text":" Bases: Endpoint
Source code in notion_client/api_endpoints.py
class UsersEndpoint(Endpoint):\n def list(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Return a paginated list of [Users](https://developers.notion.com/reference/user) for the workspace.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-users)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"users\",\n method=\"GET\",\n query=pick(kwargs, \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n\n def retrieve(self, user_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a [User](https://developers.notion.com/reference/user) using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-user)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"users/{user_id}\", method=\"GET\", auth=kwargs.get(\"auth\")\n )\n\n def me(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve the bot [User](https://developers.notion.com/reference/user) associated with the API token.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-self)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"users/me\", method=\"GET\", auth=kwargs.get(\"auth\")\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.UsersEndpoint.list","title":"list(**kwargs)
","text":"Return a paginated list of Users for the workspace.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def list(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Return a paginated list of [Users](https://developers.notion.com/reference/user) for the workspace.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-users)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"users\",\n method=\"GET\",\n query=pick(kwargs, \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.UsersEndpoint.me","title":"me(**kwargs)
","text":"Retrieve the bot User associated with the API token.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def me(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve the bot [User](https://developers.notion.com/reference/user) associated with the API token.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-self)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"users/me\", method=\"GET\", auth=kwargs.get(\"auth\")\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.UsersEndpoint.retrieve","title":"retrieve(user_id, **kwargs)
","text":"Retrieve a User using the ID specified.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def retrieve(self, user_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a [User](https://developers.notion.com/reference/user) using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-user)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"users/{user_id}\", method=\"GET\", auth=kwargs.get(\"auth\")\n )\n
"},{"location":"reference/client/","title":"Client","text":"Synchronous and asynchronous clients for Notion's API.
"},{"location":"reference/client/#notion_client.client.AsyncClient","title":"AsyncClient
","text":" Bases: BaseClient
Asynchronous client for Notion's API.
Source code in notion_client/client.py
class AsyncClient(BaseClient):\n \"\"\"Asynchronous client for Notion's API.\"\"\"\n\n client: httpx.AsyncClient\n\n def __init__(\n self,\n options: Optional[Union[Dict[str, Any], ClientOptions]] = None,\n client: Optional[httpx.AsyncClient] = None,\n **kwargs: Any,\n ) -> None:\n if client is None:\n client = httpx.AsyncClient()\n super().__init__(client, options, **kwargs)\n\n async def __aenter__(self) -> \"AsyncClient\":\n self.client = httpx.AsyncClient()\n await self.client.__aenter__()\n return self\n\n async def __aexit__(\n self,\n exc_type: Type[BaseException],\n exc_value: BaseException,\n traceback: TracebackType,\n ) -> None:\n await self.client.__aexit__(exc_type, exc_value, traceback)\n del self._clients[-1]\n\n async def aclose(self) -> None:\n \"\"\"Close the connection pool of the current inner client.\"\"\"\n await self.client.aclose()\n\n async def request(\n self,\n path: str,\n method: str,\n query: Optional[Dict[Any, Any]] = None,\n body: Optional[Dict[Any, Any]] = None,\n auth: Optional[str] = None,\n ) -> Any:\n \"\"\"Send an HTTP request asynchronously.\"\"\"\n request = self._build_request(method, path, query, body, auth)\n try:\n response = await self.client.send(request)\n except httpx.TimeoutException:\n raise RequestTimeoutError()\n return self._parse_response(response)\n
"},{"location":"reference/client/#notion_client.client.AsyncClient.aclose","title":"aclose()
async
","text":"Close the connection pool of the current inner client.
Source code in notion_client/client.py
async def aclose(self) -> None:\n \"\"\"Close the connection pool of the current inner client.\"\"\"\n await self.client.aclose()\n
"},{"location":"reference/client/#notion_client.client.AsyncClient.request","title":"request(path, method, query=None, body=None, auth=None)
async
","text":"Send an HTTP request asynchronously.
Source code in notion_client/client.py
async def request(\n self,\n path: str,\n method: str,\n query: Optional[Dict[Any, Any]] = None,\n body: Optional[Dict[Any, Any]] = None,\n auth: Optional[str] = None,\n) -> Any:\n \"\"\"Send an HTTP request asynchronously.\"\"\"\n request = self._build_request(method, path, query, body, auth)\n try:\n response = await self.client.send(request)\n except httpx.TimeoutException:\n raise RequestTimeoutError()\n return self._parse_response(response)\n
"},{"location":"reference/client/#notion_client.client.Client","title":"Client
","text":" Bases: BaseClient
Synchronous client for Notion's API.
Source code in notion_client/client.py
class Client(BaseClient):\n \"\"\"Synchronous client for Notion's API.\"\"\"\n\n client: httpx.Client\n\n def __init__(\n self,\n options: Optional[Union[Dict[Any, Any], ClientOptions]] = None,\n client: Optional[httpx.Client] = None,\n **kwargs: Any,\n ) -> None:\n if client is None:\n client = httpx.Client()\n super().__init__(client, options, **kwargs)\n\n def __enter__(self) -> \"Client\":\n self.client = httpx.Client()\n self.client.__enter__()\n return self\n\n def __exit__(\n self,\n exc_type: Type[BaseException],\n exc_value: BaseException,\n traceback: TracebackType,\n ) -> None:\n self.client.__exit__(exc_type, exc_value, traceback)\n del self._clients[-1]\n\n def close(self) -> None:\n \"\"\"Close the connection pool of the current inner client.\"\"\"\n self.client.close()\n\n def request(\n self,\n path: str,\n method: str,\n query: Optional[Dict[Any, Any]] = None,\n body: Optional[Dict[Any, Any]] = None,\n auth: Optional[str] = None,\n ) -> Any:\n \"\"\"Send an HTTP request.\"\"\"\n request = self._build_request(method, path, query, body, auth)\n try:\n response = self.client.send(request)\n except httpx.TimeoutException:\n raise RequestTimeoutError()\n return self._parse_response(response)\n
"},{"location":"reference/client/#notion_client.client.Client.close","title":"close()
","text":"Close the connection pool of the current inner client.
Source code in notion_client/client.py
def close(self) -> None:\n \"\"\"Close the connection pool of the current inner client.\"\"\"\n self.client.close()\n
"},{"location":"reference/client/#notion_client.client.Client.request","title":"request(path, method, query=None, body=None, auth=None)
","text":"Send an HTTP request.
Source code in notion_client/client.py
def request(\n self,\n path: str,\n method: str,\n query: Optional[Dict[Any, Any]] = None,\n body: Optional[Dict[Any, Any]] = None,\n auth: Optional[str] = None,\n) -> Any:\n \"\"\"Send an HTTP request.\"\"\"\n request = self._build_request(method, path, query, body, auth)\n try:\n response = self.client.send(request)\n except httpx.TimeoutException:\n raise RequestTimeoutError()\n return self._parse_response(response)\n
"},{"location":"reference/client/#notion_client.client.ClientOptions","title":"ClientOptions
dataclass
","text":"Options to configure the client.
Attributes:
Name Type Description auth
Optional[str]
Bearer token for authentication. If left undefined, the auth
parameter should be set on each request.
timeout_ms
int
Number of milliseconds to wait before emitting a RequestTimeoutError
.
base_url
str
The root URL for sending API requests. This can be changed to test with a mock server.
log_level
int
Verbosity of logs the instance will produce. By default, logs are written to stdout
.
logger
Optional[Logger]
A custom logger.
notion_version
str
Notion version to use.
Source code in notion_client/client.py
@dataclass\nclass ClientOptions:\n \"\"\"Options to configure the client.\n\n Attributes:\n auth: Bearer token for authentication. If left undefined, the `auth` parameter\n should be set on each request.\n timeout_ms: Number of milliseconds to wait before emitting a\n `RequestTimeoutError`.\n base_url: The root URL for sending API requests. This can be changed to test with\n a mock server.\n log_level: Verbosity of logs the instance will produce. By default, logs are\n written to `stdout`.\n logger: A custom logger.\n notion_version: Notion version to use.\n \"\"\"\n\n auth: Optional[str] = None\n timeout_ms: int = 60_000\n base_url: str = \"https://api.notion.com\"\n log_level: int = logging.WARNING\n logger: Optional[logging.Logger] = None\n notion_version: str = \"2022-06-28\"\n
"},{"location":"reference/errors/","title":"Errors","text":"Custom exceptions for notion-sdk-py.
This module defines the exceptions that can be raised when an error occurs.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode","title":"APIErrorCode
","text":" Bases: str
, Enum
Source code in notion_client/errors.py
class APIErrorCode(str, Enum):\n Unauthorized = \"unauthorized\"\n \"\"\"The bearer token is not valid.\"\"\"\n\n RestrictedResource = \"restricted_resource\"\n \"\"\"Given the bearer token used, the client doesn't have permission to\n perform this operation.\"\"\"\n\n ObjectNotFound = \"object_not_found\"\n \"\"\"Given the bearer token used, the resource does not exist.\n This error can also indicate that the resource has not been shared with owner\n of the bearer token.\"\"\"\n\n RateLimited = \"rate_limited\"\n \"\"\"This request exceeds the number of requests allowed. Slow down and try again.\"\"\"\n\n InvalidJSON = \"invalid_json\"\n \"\"\"The request body could not be decoded as JSON.\"\"\"\n\n InvalidRequestURL = \"invalid_request_url\"\n \"\"\"The request URL is not valid.\"\"\"\n\n InvalidRequest = \"invalid_request\"\n \"\"\"This request is not supported.\"\"\"\n\n ValidationError = \"validation_error\"\n \"\"\"The request body does not match the schema for the expected parameters.\"\"\"\n\n ConflictError = \"conflict_error\"\n \"\"\"The transaction could not be completed, potentially due to a data collision.\n Make sure the parameters are up to date and try again.\"\"\"\n\n InternalServerError = \"internal_server_error\"\n \"\"\"An unexpected error occurred. Reach out to Notion support.\"\"\"\n\n ServiceUnavailable = \"service_unavailable\"\n \"\"\"Notion is unavailable. Try again later.\n This can occur when the time to respond to a request takes longer than 60 seconds,\n the maximum request timeout.\"\"\"\n
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.ConflictError","title":"ConflictError = 'conflict_error'
class-attribute
instance-attribute
","text":"The transaction could not be completed, potentially due to a data collision. Make sure the parameters are up to date and try again.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.InternalServerError","title":"InternalServerError = 'internal_server_error'
class-attribute
instance-attribute
","text":"An unexpected error occurred. Reach out to Notion support.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.InvalidJSON","title":"InvalidJSON = 'invalid_json'
class-attribute
instance-attribute
","text":"The request body could not be decoded as JSON.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.InvalidRequest","title":"InvalidRequest = 'invalid_request'
class-attribute
instance-attribute
","text":"This request is not supported.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.InvalidRequestURL","title":"InvalidRequestURL = 'invalid_request_url'
class-attribute
instance-attribute
","text":"The request URL is not valid.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.ObjectNotFound","title":"ObjectNotFound = 'object_not_found'
class-attribute
instance-attribute
","text":"Given the bearer token used, the resource does not exist. This error can also indicate that the resource has not been shared with owner of the bearer token.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.RateLimited","title":"RateLimited = 'rate_limited'
class-attribute
instance-attribute
","text":"This request exceeds the number of requests allowed. Slow down and try again.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.RestrictedResource","title":"RestrictedResource = 'restricted_resource'
class-attribute
instance-attribute
","text":"Given the bearer token used, the client doesn't have permission to perform this operation.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.ServiceUnavailable","title":"ServiceUnavailable = 'service_unavailable'
class-attribute
instance-attribute
","text":"Notion is unavailable. Try again later. This can occur when the time to respond to a request takes longer than 60 seconds, the maximum request timeout.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.Unauthorized","title":"Unauthorized = 'unauthorized'
class-attribute
instance-attribute
","text":"The bearer token is not valid.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.ValidationError","title":"ValidationError = 'validation_error'
class-attribute
instance-attribute
","text":"The request body does not match the schema for the expected parameters.
"},{"location":"reference/errors/#notion_client.errors.APIResponseError","title":"APIResponseError
","text":" Bases: HTTPResponseError
An error raised by Notion API.
Source code in notion_client/errors.py
class APIResponseError(HTTPResponseError):\n \"\"\"An error raised by Notion API.\"\"\"\n\n code: APIErrorCode\n\n def __init__(\n self, response: httpx.Response, message: str, code: APIErrorCode\n ) -> None:\n super().__init__(response, message)\n self.code = code\n
"},{"location":"reference/errors/#notion_client.errors.HTTPResponseError","title":"HTTPResponseError
","text":" Bases: Exception
Exception for HTTP errors.
Responses from the API use HTTP response codes that are used to indicate general classes of success and error.
Source code in notion_client/errors.py
class HTTPResponseError(Exception):\n \"\"\"Exception for HTTP errors.\n\n Responses from the API use HTTP response codes that are used to indicate general\n classes of success and error.\n \"\"\"\n\n code: str = \"notionhq_client_response_error\"\n status: int\n headers: httpx.Headers\n body: str\n\n def __init__(self, response: httpx.Response, message: Optional[str] = None) -> None:\n if message is None:\n message = (\n f\"Request to Notion API failed with status: {response.status_code}\"\n )\n super().__init__(message)\n self.status = response.status_code\n self.headers = response.headers\n self.body = response.text\n
"},{"location":"reference/errors/#notion_client.errors.RequestTimeoutError","title":"RequestTimeoutError
","text":" Bases: Exception
Exception for requests that timeout.
The request that we made waits for a specified period of time or maximum number of retries to get the response. But if no response comes within the limited time or retries, then this Exception is raised.
Source code in notion_client/errors.py
class RequestTimeoutError(Exception):\n \"\"\"Exception for requests that timeout.\n\n The request that we made waits for a specified period of time or maximum number of\n retries to get the response. But if no response comes within the limited time or\n retries, then this Exception is raised.\n \"\"\"\n\n code = \"notionhq_client_request_timeout\"\n\n def __init__(self, message: str = \"Request to Notion API has timed out\") -> None:\n super().__init__(message)\n
"},{"location":"reference/errors/#notion_client.errors.is_api_error_code","title":"is_api_error_code(code)
","text":"Check if given code belongs to the list of valid API error codes.
Source code in notion_client/errors.py
def is_api_error_code(code: str) -> bool:\n \"\"\"Check if given code belongs to the list of valid API error codes.\"\"\"\n if isinstance(code, str):\n return code in (error_code.value for error_code in APIErrorCode)\n return False\n
"},{"location":"reference/helpers/","title":"Helpers","text":"Utility functions for notion-sdk-py.
"},{"location":"reference/helpers/#notion_client.helpers.async_collect_paginated_api","title":"async_collect_paginated_api(function, **kwargs)
async
","text":"Collect asynchronously all the results of paginating an API into a list.
Source code in notion_client/helpers.py
async def async_collect_paginated_api(\n function: Callable[..., Awaitable[Any]], **kwargs: Any\n) -> List[Any]:\n \"\"\"Collect asynchronously all the results of paginating an API into a list.\"\"\"\n return [result async for result in async_iterate_paginated_api(function, **kwargs)]\n
"},{"location":"reference/helpers/#notion_client.helpers.async_iterate_paginated_api","title":"async_iterate_paginated_api(function, **kwargs)
async
","text":"Return an async iterator over the results of any paginated Notion API.
Source code in notion_client/helpers.py
async def async_iterate_paginated_api(\n function: Callable[..., Awaitable[Any]], **kwargs: Any\n) -> AsyncGenerator[List[Any], None]:\n \"\"\"Return an async iterator over the results of any paginated Notion API.\"\"\"\n next_cursor = kwargs.pop(\"start_cursor\", None)\n\n while True:\n response = await function(**kwargs, start_cursor=next_cursor)\n for result in response.get(\"results\"):\n yield result\n\n next_cursor = response.get(\"next_cursor\")\n if (not response[\"has_more\"]) | (next_cursor is None):\n return\n
"},{"location":"reference/helpers/#notion_client.helpers.collect_paginated_api","title":"collect_paginated_api(function, **kwargs)
","text":"Collect all the results of paginating an API into a list.
Source code in notion_client/helpers.py
def collect_paginated_api(function: Callable[..., Any], **kwargs: Any) -> List[Any]:\n \"\"\"Collect all the results of paginating an API into a list.\"\"\"\n return [result for result in iterate_paginated_api(function, **kwargs)]\n
"},{"location":"reference/helpers/#notion_client.helpers.get_id","title":"get_id(url)
","text":"Return the id of the object behind the given URL.
Source code in notion_client/helpers.py
def get_id(url: str) -> str:\n \"\"\"Return the id of the object behind the given URL.\"\"\"\n parsed = urlparse(url)\n if parsed.netloc not in (\"notion.so\", \"www.notion.so\"):\n raise ValueError(\"Not a valid Notion URL.\")\n path = parsed.path\n if len(path) < 32:\n raise ValueError(\"The path in the URL seems to be incorrect.\")\n raw_id = path[-32:]\n return str(UUID(raw_id))\n
"},{"location":"reference/helpers/#notion_client.helpers.get_url","title":"get_url(object_id)
","text":"Return the URL for the object with the given id.
Source code in notion_client/helpers.py
def get_url(object_id: str) -> str:\n \"\"\"Return the URL for the object with the given id.\"\"\"\n return f\"https://notion.so/{UUID(object_id).hex}\"\n
"},{"location":"reference/helpers/#notion_client.helpers.is_equation_rich_text_item_response","title":"is_equation_rich_text_item_response(rich_text)
","text":"Return True
if rich_text
is an equation.
Source code in notion_client/helpers.py
def is_equation_rich_text_item_response(rich_text: Dict[Any, Any]) -> bool:\n \"\"\"Return `True` if `rich_text` is an equation.\"\"\"\n return rich_text.get(\"type\") == \"equation\"\n
"},{"location":"reference/helpers/#notion_client.helpers.is_full_block","title":"is_full_block(response)
","text":"Return True
if response is a full block.
Source code in notion_client/helpers.py
def is_full_block(response: Dict[Any, Any]) -> bool:\n \"\"\"Return `True` if response is a full block.\"\"\"\n return response.get(\"object\") == \"block\" and \"type\" in response\n
"},{"location":"reference/helpers/#notion_client.helpers.is_full_comment","title":"is_full_comment(response)
","text":"Return True
if response is a full comment.
Source code in notion_client/helpers.py
def is_full_comment(response: Dict[Any, Any]) -> bool:\n \"\"\"Return `True` if response is a full comment.\"\"\"\n return \"type\" in response\n
"},{"location":"reference/helpers/#notion_client.helpers.is_full_database","title":"is_full_database(response)
","text":"Return True
if response is a full database.
Source code in notion_client/helpers.py
def is_full_database(response: Dict[Any, Any]) -> bool:\n \"\"\"Return `True` if response is a full database.\"\"\"\n return response.get(\"object\") == \"database\" and \"title\" in response\n
"},{"location":"reference/helpers/#notion_client.helpers.is_full_page","title":"is_full_page(response)
","text":"Return True
if response is a full page.
Source code in notion_client/helpers.py
def is_full_page(response: Dict[Any, Any]) -> bool:\n \"\"\"Return `True` if response is a full page.\"\"\"\n return response.get(\"object\") == \"page\" and \"url\" in response\n
"},{"location":"reference/helpers/#notion_client.helpers.is_full_page_or_database","title":"is_full_page_or_database(response)
","text":"Return True
if response
is a full database or a full page.
Source code in notion_client/helpers.py
def is_full_page_or_database(response: Dict[Any, Any]) -> bool:\n \"\"\"Return `True` if `response` is a full database or a full page.\"\"\"\n if response.get(\"object\") == \"database\":\n return is_full_database(response)\n return is_full_page(response)\n
"},{"location":"reference/helpers/#notion_client.helpers.is_full_user","title":"is_full_user(response)
","text":"Return True
if response is a full user.
Source code in notion_client/helpers.py
def is_full_user(response: Dict[Any, Any]) -> bool:\n \"\"\"Return `True` if response is a full user.\"\"\"\n return \"type\" in response\n
"},{"location":"reference/helpers/#notion_client.helpers.is_mention_rich_text_item_response","title":"is_mention_rich_text_item_response(rich_text)
","text":"Return True
if rich_text
is a mention.
Source code in notion_client/helpers.py
def is_mention_rich_text_item_response(rich_text: Dict[Any, Any]) -> bool:\n \"\"\"Return `True` if `rich_text` is a mention.\"\"\"\n return rich_text.get(\"type\") == \"mention\"\n
"},{"location":"reference/helpers/#notion_client.helpers.is_text_rich_text_item_response","title":"is_text_rich_text_item_response(rich_text)
","text":"Return True
if rich_text
is a text.
Source code in notion_client/helpers.py
def is_text_rich_text_item_response(rich_text: Dict[Any, Any]) -> bool:\n \"\"\"Return `True` if `rich_text` is a text.\"\"\"\n return rich_text.get(\"type\") == \"text\"\n
"},{"location":"reference/helpers/#notion_client.helpers.iterate_paginated_api","title":"iterate_paginated_api(function, **kwargs)
","text":"Return an iterator over the results of any paginated Notion API.
Source code in notion_client/helpers.py
def iterate_paginated_api(\n function: Callable[..., Any], **kwargs: Any\n) -> Generator[List[Any], None, None]:\n \"\"\"Return an iterator over the results of any paginated Notion API.\"\"\"\n next_cursor = kwargs.pop(\"start_cursor\", None)\n\n while True:\n response = function(**kwargs, start_cursor=next_cursor)\n for result in response.get(\"results\"):\n yield result\n\n next_cursor = response.get(\"next_cursor\")\n if not response.get(\"has_more\") or not next_cursor:\n return\n
"},{"location":"reference/helpers/#notion_client.helpers.pick","title":"pick(base, *keys)
","text":"Return a dict composed of key value pairs for keys passed as args.
Source code in notion_client/helpers.py
def pick(base: Dict[Any, Any], *keys: str) -> Dict[Any, Any]:\n \"\"\"Return a dict composed of key value pairs for keys passed as args.\"\"\"\n result = {}\n for key in keys:\n if key not in base:\n continue\n value = base.get(key)\n if value is None and key == \"start_cursor\":\n continue\n result[key] = value\n return result\n
"},{"location":"user_guides/quick_start/","title":"Quick start","text":"Get started with notion-sdk-py in just 5 minutes!
"},{"location":"user_guides/quick_start/#setup","title":"Setup","text":""},{"location":"user_guides/quick_start/#prerequisites","title":"Prerequisites","text":" -
Make sure you have python
and pip
properly installed in your system.
python --version\npip --version\n
-
Create a new directory and move into it to follow along with this tutorial.
mkdir learn-notion-sdk-py && cd learn-notion-sdk-py\n
"},{"location":"user_guides/quick_start/#installation","title":"Installation","text":" -
Create a virtual environment and activate it.
python -m venv .venv && source .venv/bin/activate\n
-
Install notion-sdk-py
using pip
pip install --upgrade notion-client\n
"},{"location":"user_guides/quick_start/#integration","title":"Integration","text":" -
Go to notion.so/my-integrations to create an integration. Copy the token given by Notion.
-
Make it available in your environment:
export NOTION_TOKEN=ntn_abcd12345\n
Tip
Don't forget that export
only puts the variable in the environment of the current shell. If you don't want to redo this step for every new shell, add the line in your shell configuration or use a configuration library like dotenv.
"},{"location":"user_guides/quick_start/#play","title":"Play","text":"Copy paste the code, and have fun tweaking it!
Let's start by initializing the client:
import os\nfrom notion_client import Client\n\nnotion = Client(auth=os.environ[\"NOTION_TOKEN\"])\n
Let's now fetch the list of users in the scope of our integration:
users = notion.users.list()\n\nfor user in users.get(\"results\"):\n name, user_type = user[\"name\"], user[\"type\"]\n emoji = \"\ud83d\ude05\" if user[\"type\"] == \"bot\" else \"\ud83d\ude4b\u200d\u2642\ufe0f\"\n print(f\"{name} is a {user_type} {emoji}\")\n
It should output something in those lines:
Aahnik Daw is a person \ud83d\ude4b\u200d\u2642\ufe0f\nTestIntegation is a bot \ud83d\ude05\n
Do you see your name and the name of your integration?
\ud83c\udf89 Congratulations, you are now ready to use notion-sdk-py!
"},{"location":"user_guides/structured_logging/","title":"Structured logging","text":"You can easily get structured logging with notion-sdk-py by using structlog:
logger = structlog.wrap_logger(\n logging.getLogger(\"notion-client\"),\n logger_factory=structlog.stdlib.LoggerFactory(),\n wrapper_class=structlog.stdlib.BoundLogger,\n)\n\nnotion = Client(auth=token, logger=logger, log_level=logging.DEBUG)\n
Don't forget to add the dependency to your project!
"},{"location":"coverage/","title":"Coverage report","text":""}]}
\ No newline at end of file
+{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Home","text":"notion-sdk-py is a simple and easy to use client library for the official Notion API.
It is meant to be a Python version of the reference JavaScript SDK, so usage should be very similar between both. \ud83d\ude0a (If not, please open an issue or PR!)
\ud83d\udce2 Announcement (18-12-2024) \u2014 Release 2.3.0 is out! It adds in_trash
support for pages, Python 3.13 official support, fixes and security updates.
"},{"location":"#installation","title":"Installation","text":"pip install notion-client\n
"},{"location":"#usage","title":"Usage","text":"Use Notion's Getting Started Guide to get set up to use Notion's API.
Import and initialize a client using an integration token or an OAuth access token.
import os\nfrom notion_client import Client\n\nnotion = Client(auth=os.environ[\"NOTION_TOKEN\"])\n
In an asyncio environment, use the asynchronous client instead:
from notion_client import AsyncClient\n\nnotion = AsyncClient(auth=os.environ[\"NOTION_TOKEN\"])\n
Make a request to any Notion API endpoint.
See the complete list of endpoints in the API reference.
from pprint import pprint\n\nlist_users_response = notion.users.list()\npprint(list_users_response)\n
or with the asynchronous client:
list_users_response = await notion.users.list()\npprint(list_users_response)\n
This would output something like:
{'results': [{'avatar_url': 'https://secure.notion-static.com/e6a352a8-8381-44d0-a1dc-9ed80e62b53d.jpg',\n 'id': 'd40e767c-d7af-4b18-a86d-55c61f1e39a4',\n 'name': 'Avocado Lovelace',\n 'object': 'user',\n 'person': {'email': 'avo@example.org'},\n 'type': 'person'},\n ...]}\n
All API endpoints are available in both the synchronous and asynchronous clients.
Endpoint parameters are grouped into a single object. You don't need to remember which parameters go in the path, query, or body.
my_page = notion.databases.query(\n **{\n \"database_id\": \"897e5a76-ae52-4b48-9fdf-e71f5945d1af\",\n \"filter\": {\n \"property\": \"Landmark\",\n \"rich_text\": {\n \"contains\": \"Bridge\",\n },\n },\n }\n)\n
"},{"location":"#handling-errors","title":"Handling errors","text":"If the API returns an unsuccessful response, an APIResponseError
will be raised.
The error contains properties from the response, and the most helpful is code
. You can compare code
to the values in the APIErrorCode
object to avoid misspelling error codes.
import logging\nfrom notion_client import APIErrorCode, APIResponseError\n\ntry:\n my_page = notion.databases.query(\n **{\n \"database_id\": \"897e5a76-ae52-4b48-9fdf-e71f5945d1af\",\n \"filter\": {\n \"property\": \"Landmark\",\n \"rich_text\": {\n \"contains\": \"Bridge\",\n },\n },\n }\n )\nexcept APIResponseError as error:\n if error.code == APIErrorCode.ObjectNotFound:\n ... # For example: handle by asking the user to select a different database\n else:\n # Other error handling code\n logging.error(error)\n
"},{"location":"#logging","title":"Logging","text":"The client emits useful information to a logger. By default, it only emits warnings and errors.
If you're debugging an application, and would like the client to log request & response bodies, set the log_level
option to logging.DEBUG
.
notion = Client(\n auth=os.environ[\"NOTION_TOKEN\"],\n log_level=logging.DEBUG,\n)\n
You may also set a custom logger
to emit logs to a destination other than stdout
. Have a look at Python's logging cookbook if you want to create your own logger.
"},{"location":"#client-options","title":"Client options","text":"Client
and AsyncClient
both support the following options on initialization. These options are all keys in the single constructor parameter.
Option Default value Type Description auth
None
string
Bearer token for authentication. If left undefined, the auth
parameter should be set on each request. log_level
logging.WARNING
int
Verbosity of logs the instance will produce. By default, logs are written to stdout
. timeout_ms
60_000
int
Number of milliseconds to wait before emitting a RequestTimeoutError
base_url
\"https://api.notion.com\"
string
The root URL for sending API requests. This can be changed to test with a mock server. logger
Log to console logging.Logger
A custom logger."},{"location":"#full-api-responses","title":"Full API responses","text":"The following functions can distinguish between full and partial API responses.
Function Purpose is_full_page
Determine whether an object is a full Page object is_full_block
Determine whether an object is a full Block object is_full_database
Determine whether an object is a full Database object is_full_page_or_database
Determine whether an object is a full Page object or Database object is_full_user
Determine whether an object is a full User object is_full_comment
Determine whether an object is a full Comment object from notion_client.helpers import is_full_page\n\nfull_or_partial_pages = await notion.databases.query(\n database_id=\"897e5a76-ae52-4b48-9fdf-e71f5945d1af\"\n)\n\nfor page in full_or_partial_pages[\"results\"]:\n if not is_full_page_or_database(page):\n continue\n print(f\"Created at: {page['created_time']}\")\n
"},{"location":"#utility-functions","title":"Utility functions","text":"These functions can be helpful for dealing with any of the paginated APIs.
iterate_paginated_api(function, **kwargs)
and its async version async_iterate_paginated_api(function, **kwargs)
turn any paginated API into a generator.
The function
parameter must accept a start_cursor
argument. Example: notion.blocks.children.list
.
from notion_client.helpers import iterate_paginated_api\n\nfor block in iterate_paginated_api(\n notion.databases.query, database_id=\"897e5a76-ae52-4b48-9fdf-e71f5945d1af\"\n):\n # Do something with block.\n ...\n
If you don't need a generator, collect_paginated_api(function, **kwargs)
and its async version async_collect_paginated_api(function, **kwargs)
have the same behavior than the previous functions, but return a list of all results from the paginated API.
from notion_client.helpers import collect_paginated_api\n\nall_results = collect_paginated_api(\n notion.databases.query, database_id=\"897e5a76-ae52-4b48-9fdf-e71f5945d1af\"\n)\n
"},{"location":"#testing","title":"Testing","text":"Run the tests with the pytest
command. If you want to test against all Python versions, you can run tox
instead.
The tests are using pytest-vcr
's cassettes for simulating requests to the Notion API. To create new tests or run them without cassettes, you need to set up the environment variables NOTION_TOKEN
and NOTION_TEST_PAGE_ID
(a page where your integration has all the capabilities enabled).
The code will use the page at NOTION_TEST_PAGE_ID
to generate a temporary environment with the Notion objects to be tested, which will be deleted at the end of the session.
"},{"location":"#requirements","title":"Requirements","text":"This package supports the following minimum versions:
- Python >= 3.7
- httpx >= 0.15.0
Earlier versions may still work, but we encourage people building new applications to upgrade to the current stable.
"},{"location":"#getting-help","title":"Getting help","text":"If you want to submit a feature request for Notion's API, or are experiencing any issues with the API platform, please email developers@makenotion.com
.
If you found a bug with the library, please submit an issue.
"},{"location":"#_1","title":"Home","text":""},{"location":"SUMMARY/","title":"SUMMARY","text":" - Home
- User guides
- Quick start
- Structured logging
- More examples
- Reference
- Client
- API endpoints
- Errors
- Helpers
- Development
- Coverage report
- Contributing guidelines
- License
"},{"location":"license/","title":"License","text":"The MIT License (MIT)\n\nCopyright (c) 2021-2023 Guillaume Gelin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n
"},{"location":"contributing/contributing/","title":"Contributing guidelines","text":"Tip
If you are a first time contributor, please start by reading this fantastic guide.
Any serious contribution to notion-sdk-py is always welcome, regardless of your experience.
If you want to contribute on the code specifically:
- Install Git and Python on your system.
- Fork the repository and clone it.
-
Checkout a new feature branch from main
:
git checkout my-feature\n
-
Install dependencies inside a virtual environment:
python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements/dev.txt\n
-
Install pre-commit hooks:
pre-commit install\n
You should now be ready to hack!
You can run the tests with pytest
in the main directory. Please make sure the tests (and pre-commit hooks) pass before opening a pull request.
Coverage must stay at 100%. Write tests if you add new features.
Thanks for your help!
"},{"location":"reference/api_endpoints/","title":"API endpoints","text":"Notion API endpoints.
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.BlocksChildrenEndpoint","title":"BlocksChildrenEndpoint
","text":" Bases: Endpoint
Source code in notion_client/api_endpoints.py
class BlocksChildrenEndpoint(Endpoint):\n def append(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Create and append new children blocks to the block using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/patch-block-children)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}/children\",\n method=\"PATCH\",\n body=pick(kwargs, \"children\", \"after\"),\n auth=kwargs.get(\"auth\"),\n )\n\n def list(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Return a paginated array of child [block objects](https://developers.notion.com/reference/block) contained in the block.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-block-children)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}/children\",\n method=\"GET\",\n query=pick(kwargs, \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.BlocksChildrenEndpoint.append","title":"append(block_id, **kwargs)
","text":"Create and append new children blocks to the block using the ID specified.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def append(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Create and append new children blocks to the block using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/patch-block-children)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}/children\",\n method=\"PATCH\",\n body=pick(kwargs, \"children\", \"after\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.BlocksChildrenEndpoint.list","title":"list(block_id, **kwargs)
","text":"Return a paginated array of child block objects contained in the block.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def list(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Return a paginated array of child [block objects](https://developers.notion.com/reference/block) contained in the block.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-block-children)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}/children\",\n method=\"GET\",\n query=pick(kwargs, \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.BlocksEndpoint","title":"BlocksEndpoint
","text":" Bases: Endpoint
Source code in notion_client/api_endpoints.py
class BlocksEndpoint(Endpoint):\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n super().__init__(*args, **kwargs)\n self.children = BlocksChildrenEndpoint(*args, **kwargs)\n\n def retrieve(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a [Block object](https://developers.notion.com/reference/block) using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-block)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}\", method=\"GET\", auth=kwargs.get(\"auth\")\n )\n\n def update(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Update the content for the specified `block_id` based on the block type.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/update-a-block)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}\",\n method=\"PATCH\",\n body=pick(\n kwargs,\n \"embed\",\n \"type\",\n \"archived\",\n \"bookmark\",\n \"image\",\n \"video\",\n \"pdf\",\n \"file\",\n \"audio\",\n \"code\",\n \"equation\",\n \"divider\",\n \"breadcrumb\",\n \"table_of_contents\",\n \"link_to_page\",\n \"table_row\",\n \"heading_1\",\n \"heading_2\",\n \"heading_3\",\n \"paragraph\",\n \"bulleted_list_item\",\n \"numbered_list_item\",\n \"quote\",\n \"to_do\",\n \"toggle\",\n \"template\",\n \"callout\",\n \"synced_block\",\n \"table\",\n ),\n auth=kwargs.get(\"auth\"),\n )\n\n def delete(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Set a [Block object](https://developers.notion.com/reference/block), including page blocks, to `archived: true`.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/delete-a-block)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}\",\n method=\"DELETE\",\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.BlocksEndpoint.delete","title":"delete(block_id, **kwargs)
","text":"Set a Block object, including page blocks, to archived: true
.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def delete(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Set a [Block object](https://developers.notion.com/reference/block), including page blocks, to `archived: true`.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/delete-a-block)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}\",\n method=\"DELETE\",\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.BlocksEndpoint.retrieve","title":"retrieve(block_id, **kwargs)
","text":"Retrieve a Block object using the ID specified.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def retrieve(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a [Block object](https://developers.notion.com/reference/block) using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-block)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}\", method=\"GET\", auth=kwargs.get(\"auth\")\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.BlocksEndpoint.update","title":"update(block_id, **kwargs)
","text":"Update the content for the specified block_id
based on the block type.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def update(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Update the content for the specified `block_id` based on the block type.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/update-a-block)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"blocks/{block_id}\",\n method=\"PATCH\",\n body=pick(\n kwargs,\n \"embed\",\n \"type\",\n \"archived\",\n \"bookmark\",\n \"image\",\n \"video\",\n \"pdf\",\n \"file\",\n \"audio\",\n \"code\",\n \"equation\",\n \"divider\",\n \"breadcrumb\",\n \"table_of_contents\",\n \"link_to_page\",\n \"table_row\",\n \"heading_1\",\n \"heading_2\",\n \"heading_3\",\n \"paragraph\",\n \"bulleted_list_item\",\n \"numbered_list_item\",\n \"quote\",\n \"to_do\",\n \"toggle\",\n \"template\",\n \"callout\",\n \"synced_block\",\n \"table\",\n ),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.CommentsEndpoint","title":"CommentsEndpoint
","text":" Bases: Endpoint
Source code in notion_client/api_endpoints.py
class CommentsEndpoint(Endpoint):\n def create(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Create a new comment in the specified page or existing discussion thread.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/create-a-comment)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"comments\",\n method=\"POST\",\n body=pick(kwargs, \"parent\", \"discussion_id\", \"rich_text\"),\n auth=kwargs.get(\"auth\"),\n )\n\n def list(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a list of un-resolved [Comment objects](https://developers.notion.com/reference/comment-object) from the specified block.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-comment)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"comments\",\n method=\"GET\",\n query=pick(kwargs, \"block_id\", \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.CommentsEndpoint.create","title":"create(**kwargs)
","text":"Create a new comment in the specified page or existing discussion thread.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def create(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Create a new comment in the specified page or existing discussion thread.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/create-a-comment)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"comments\",\n method=\"POST\",\n body=pick(kwargs, \"parent\", \"discussion_id\", \"rich_text\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.CommentsEndpoint.list","title":"list(**kwargs)
","text":"Retrieve a list of un-resolved Comment objects from the specified block.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def list(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a list of un-resolved [Comment objects](https://developers.notion.com/reference/comment-object) from the specified block.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-comment)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"comments\",\n method=\"GET\",\n query=pick(kwargs, \"block_id\", \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.DatabasesEndpoint","title":"DatabasesEndpoint
","text":" Bases: Endpoint
Source code in notion_client/api_endpoints.py
class DatabasesEndpoint(Endpoint):\n def list(self, **kwargs: Any) -> SyncAsync[Any]: # pragma: no cover\n \"\"\"List all [Databases](https://developers.notion.com/reference/database) shared with the authenticated integration.\n\n > \u26a0\ufe0f **Deprecated endpoint**\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-databases)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"databases\",\n method=\"GET\",\n query=pick(kwargs, \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n\n def query(self, database_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Get a list of [Pages](https://developers.notion.com/reference/page) contained in the database.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/post-database-query)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"databases/{database_id}/query\",\n method=\"POST\",\n query=pick(kwargs, \"filter_properties\"),\n body=pick(kwargs, \"filter\", \"sorts\", \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n\n def retrieve(self, database_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a [Database object](https://developers.notion.com/reference/database) using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-database)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"databases/{database_id}\", method=\"GET\", auth=kwargs.get(\"auth\")\n )\n\n def create(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Create a database as a subpage in the specified parent page.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/create-a-database)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"databases\",\n method=\"POST\",\n body=pick(\n kwargs, \"parent\", \"title\", \"properties\", \"icon\", \"cover\", \"is_inline\"\n ),\n auth=kwargs.get(\"auth\"),\n )\n\n def update(self, database_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Update an existing database as specified by the parameters.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/update-a-database)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"databases/{database_id}\",\n method=\"PATCH\",\n body=pick(\n kwargs,\n \"properties\",\n \"title\",\n \"description\",\n \"icon\",\n \"cover\",\n \"is_inline\",\n ),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.DatabasesEndpoint.create","title":"create(**kwargs)
","text":"Create a database as a subpage in the specified parent page.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def create(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Create a database as a subpage in the specified parent page.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/create-a-database)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"databases\",\n method=\"POST\",\n body=pick(\n kwargs, \"parent\", \"title\", \"properties\", \"icon\", \"cover\", \"is_inline\"\n ),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.DatabasesEndpoint.list","title":"list(**kwargs)
","text":"List all Databases shared with the authenticated integration.
\u26a0\ufe0f Deprecated endpoint
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def list(self, **kwargs: Any) -> SyncAsync[Any]: # pragma: no cover\n \"\"\"List all [Databases](https://developers.notion.com/reference/database) shared with the authenticated integration.\n\n > \u26a0\ufe0f **Deprecated endpoint**\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-databases)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"databases\",\n method=\"GET\",\n query=pick(kwargs, \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.DatabasesEndpoint.query","title":"query(database_id, **kwargs)
","text":"Get a list of Pages contained in the database.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def query(self, database_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Get a list of [Pages](https://developers.notion.com/reference/page) contained in the database.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/post-database-query)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"databases/{database_id}/query\",\n method=\"POST\",\n query=pick(kwargs, \"filter_properties\"),\n body=pick(kwargs, \"filter\", \"sorts\", \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.DatabasesEndpoint.retrieve","title":"retrieve(database_id, **kwargs)
","text":"Retrieve a Database object using the ID specified.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def retrieve(self, database_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a [Database object](https://developers.notion.com/reference/database) using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-database)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"databases/{database_id}\", method=\"GET\", auth=kwargs.get(\"auth\")\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.DatabasesEndpoint.update","title":"update(database_id, **kwargs)
","text":"Update an existing database as specified by the parameters.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def update(self, database_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Update an existing database as specified by the parameters.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/update-a-database)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"databases/{database_id}\",\n method=\"PATCH\",\n body=pick(\n kwargs,\n \"properties\",\n \"title\",\n \"description\",\n \"icon\",\n \"cover\",\n \"is_inline\",\n ),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.PagesEndpoint","title":"PagesEndpoint
","text":" Bases: Endpoint
Source code in notion_client/api_endpoints.py
class PagesEndpoint(Endpoint):\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n super().__init__(*args, **kwargs)\n self.properties = PagesPropertiesEndpoint(*args, **kwargs)\n\n def create(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Create a new page in the specified database or as a child of an existing page.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/post-page)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"pages\",\n method=\"POST\",\n body=pick(kwargs, \"parent\", \"properties\", \"children\", \"icon\", \"cover\"),\n auth=kwargs.get(\"auth\"),\n )\n\n def retrieve(self, page_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a [Page object](https://developers.notion.com/reference/page) using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-page)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"pages/{page_id}\",\n method=\"GET\",\n query=pick(kwargs, \"filter_properties\"),\n auth=kwargs.get(\"auth\"),\n )\n\n def update(self, page_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Update [page property values](https://developers.notion.com/reference/page#property-value-object) for the specified page.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/patch-page)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"pages/{page_id}\",\n method=\"PATCH\",\n body=pick(kwargs, \"in_trash\", \"archived\", \"properties\", \"icon\", \"cover\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.PagesEndpoint.create","title":"create(**kwargs)
","text":"Create a new page in the specified database or as a child of an existing page.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def create(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Create a new page in the specified database or as a child of an existing page.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/post-page)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"pages\",\n method=\"POST\",\n body=pick(kwargs, \"parent\", \"properties\", \"children\", \"icon\", \"cover\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.PagesEndpoint.retrieve","title":"retrieve(page_id, **kwargs)
","text":"Retrieve a Page object using the ID specified.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def retrieve(self, page_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a [Page object](https://developers.notion.com/reference/page) using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-page)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"pages/{page_id}\",\n method=\"GET\",\n query=pick(kwargs, \"filter_properties\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.PagesEndpoint.update","title":"update(page_id, **kwargs)
","text":"Update page property values for the specified page.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def update(self, page_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Update [page property values](https://developers.notion.com/reference/page#property-value-object) for the specified page.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/patch-page)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"pages/{page_id}\",\n method=\"PATCH\",\n body=pick(kwargs, \"in_trash\", \"archived\", \"properties\", \"icon\", \"cover\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.PagesPropertiesEndpoint","title":"PagesPropertiesEndpoint
","text":" Bases: Endpoint
Source code in notion_client/api_endpoints.py
class PagesPropertiesEndpoint(Endpoint):\n def retrieve(self, page_id: str, property_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a `property_item` object for a given `page_id` and `property_id`.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-page-property)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"pages/{page_id}/properties/{property_id}\",\n method=\"GET\",\n auth=kwargs.get(\"auth\"),\n query=pick(kwargs, \"start_cursor\", \"page_size\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.PagesPropertiesEndpoint.retrieve","title":"retrieve(page_id, property_id, **kwargs)
","text":"Retrieve a property_item
object for a given page_id
and property_id
.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def retrieve(self, page_id: str, property_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a `property_item` object for a given `page_id` and `property_id`.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/retrieve-a-page-property)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"pages/{page_id}/properties/{property_id}\",\n method=\"GET\",\n auth=kwargs.get(\"auth\"),\n query=pick(kwargs, \"start_cursor\", \"page_size\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.SearchEndpoint","title":"SearchEndpoint
","text":" Bases: Endpoint
Source code in notion_client/api_endpoints.py
class SearchEndpoint(Endpoint):\n def __call__(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Search all pages and child pages that are shared with the integration.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/post-search)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"search\",\n method=\"POST\",\n body=pick(kwargs, \"query\", \"sort\", \"filter\", \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.SearchEndpoint.__call__","title":"__call__(**kwargs)
","text":"Search all pages and child pages that are shared with the integration.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def __call__(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Search all pages and child pages that are shared with the integration.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/post-search)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"search\",\n method=\"POST\",\n body=pick(kwargs, \"query\", \"sort\", \"filter\", \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.UsersEndpoint","title":"UsersEndpoint
","text":" Bases: Endpoint
Source code in notion_client/api_endpoints.py
class UsersEndpoint(Endpoint):\n def list(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Return a paginated list of [Users](https://developers.notion.com/reference/user) for the workspace.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-users)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"users\",\n method=\"GET\",\n query=pick(kwargs, \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n\n def retrieve(self, user_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a [User](https://developers.notion.com/reference/user) using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-user)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"users/{user_id}\", method=\"GET\", auth=kwargs.get(\"auth\")\n )\n\n def me(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve the bot [User](https://developers.notion.com/reference/user) associated with the API token.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-self)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"users/me\", method=\"GET\", auth=kwargs.get(\"auth\")\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.UsersEndpoint.list","title":"list(**kwargs)
","text":"Return a paginated list of Users for the workspace.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def list(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Return a paginated list of [Users](https://developers.notion.com/reference/user) for the workspace.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-users)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"users\",\n method=\"GET\",\n query=pick(kwargs, \"start_cursor\", \"page_size\"),\n auth=kwargs.get(\"auth\"),\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.UsersEndpoint.me","title":"me(**kwargs)
","text":"Retrieve the bot User associated with the API token.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def me(self, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve the bot [User](https://developers.notion.com/reference/user) associated with the API token.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-self)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=\"users/me\", method=\"GET\", auth=kwargs.get(\"auth\")\n )\n
"},{"location":"reference/api_endpoints/#notion_client.api_endpoints.UsersEndpoint.retrieve","title":"retrieve(user_id, **kwargs)
","text":"Retrieve a User using the ID specified.
\ud83d\udd17 Endpoint documentation
Source code in notion_client/api_endpoints.py
def retrieve(self, user_id: str, **kwargs: Any) -> SyncAsync[Any]:\n \"\"\"Retrieve a [User](https://developers.notion.com/reference/user) using the ID specified.\n\n *[\ud83d\udd17 Endpoint documentation](https://developers.notion.com/reference/get-user)*\n \"\"\" # noqa: E501\n return self.parent.request(\n path=f\"users/{user_id}\", method=\"GET\", auth=kwargs.get(\"auth\")\n )\n
"},{"location":"reference/client/","title":"Client","text":"Synchronous and asynchronous clients for Notion's API.
"},{"location":"reference/client/#notion_client.client.AsyncClient","title":"AsyncClient
","text":" Bases: BaseClient
Asynchronous client for Notion's API.
Source code in notion_client/client.py
class AsyncClient(BaseClient):\n \"\"\"Asynchronous client for Notion's API.\"\"\"\n\n client: httpx.AsyncClient\n\n def __init__(\n self,\n options: Optional[Union[Dict[str, Any], ClientOptions]] = None,\n client: Optional[httpx.AsyncClient] = None,\n **kwargs: Any,\n ) -> None:\n if client is None:\n client = httpx.AsyncClient()\n super().__init__(client, options, **kwargs)\n\n async def __aenter__(self) -> \"AsyncClient\":\n self.client = httpx.AsyncClient()\n await self.client.__aenter__()\n return self\n\n async def __aexit__(\n self,\n exc_type: Type[BaseException],\n exc_value: BaseException,\n traceback: TracebackType,\n ) -> None:\n await self.client.__aexit__(exc_type, exc_value, traceback)\n del self._clients[-1]\n\n async def aclose(self) -> None:\n \"\"\"Close the connection pool of the current inner client.\"\"\"\n await self.client.aclose()\n\n async def request(\n self,\n path: str,\n method: str,\n query: Optional[Dict[Any, Any]] = None,\n body: Optional[Dict[Any, Any]] = None,\n auth: Optional[str] = None,\n ) -> Any:\n \"\"\"Send an HTTP request asynchronously.\"\"\"\n request = self._build_request(method, path, query, body, auth)\n try:\n response = await self.client.send(request)\n except httpx.TimeoutException:\n raise RequestTimeoutError()\n return self._parse_response(response)\n
"},{"location":"reference/client/#notion_client.client.AsyncClient.aclose","title":"aclose()
async
","text":"Close the connection pool of the current inner client.
Source code in notion_client/client.py
async def aclose(self) -> None:\n \"\"\"Close the connection pool of the current inner client.\"\"\"\n await self.client.aclose()\n
"},{"location":"reference/client/#notion_client.client.AsyncClient.request","title":"request(path, method, query=None, body=None, auth=None)
async
","text":"Send an HTTP request asynchronously.
Source code in notion_client/client.py
async def request(\n self,\n path: str,\n method: str,\n query: Optional[Dict[Any, Any]] = None,\n body: Optional[Dict[Any, Any]] = None,\n auth: Optional[str] = None,\n) -> Any:\n \"\"\"Send an HTTP request asynchronously.\"\"\"\n request = self._build_request(method, path, query, body, auth)\n try:\n response = await self.client.send(request)\n except httpx.TimeoutException:\n raise RequestTimeoutError()\n return self._parse_response(response)\n
"},{"location":"reference/client/#notion_client.client.Client","title":"Client
","text":" Bases: BaseClient
Synchronous client for Notion's API.
Source code in notion_client/client.py
class Client(BaseClient):\n \"\"\"Synchronous client for Notion's API.\"\"\"\n\n client: httpx.Client\n\n def __init__(\n self,\n options: Optional[Union[Dict[Any, Any], ClientOptions]] = None,\n client: Optional[httpx.Client] = None,\n **kwargs: Any,\n ) -> None:\n if client is None:\n client = httpx.Client()\n super().__init__(client, options, **kwargs)\n\n def __enter__(self) -> \"Client\":\n self.client = httpx.Client()\n self.client.__enter__()\n return self\n\n def __exit__(\n self,\n exc_type: Type[BaseException],\n exc_value: BaseException,\n traceback: TracebackType,\n ) -> None:\n self.client.__exit__(exc_type, exc_value, traceback)\n del self._clients[-1]\n\n def close(self) -> None:\n \"\"\"Close the connection pool of the current inner client.\"\"\"\n self.client.close()\n\n def request(\n self,\n path: str,\n method: str,\n query: Optional[Dict[Any, Any]] = None,\n body: Optional[Dict[Any, Any]] = None,\n auth: Optional[str] = None,\n ) -> Any:\n \"\"\"Send an HTTP request.\"\"\"\n request = self._build_request(method, path, query, body, auth)\n try:\n response = self.client.send(request)\n except httpx.TimeoutException:\n raise RequestTimeoutError()\n return self._parse_response(response)\n
"},{"location":"reference/client/#notion_client.client.Client.close","title":"close()
","text":"Close the connection pool of the current inner client.
Source code in notion_client/client.py
def close(self) -> None:\n \"\"\"Close the connection pool of the current inner client.\"\"\"\n self.client.close()\n
"},{"location":"reference/client/#notion_client.client.Client.request","title":"request(path, method, query=None, body=None, auth=None)
","text":"Send an HTTP request.
Source code in notion_client/client.py
def request(\n self,\n path: str,\n method: str,\n query: Optional[Dict[Any, Any]] = None,\n body: Optional[Dict[Any, Any]] = None,\n auth: Optional[str] = None,\n) -> Any:\n \"\"\"Send an HTTP request.\"\"\"\n request = self._build_request(method, path, query, body, auth)\n try:\n response = self.client.send(request)\n except httpx.TimeoutException:\n raise RequestTimeoutError()\n return self._parse_response(response)\n
"},{"location":"reference/client/#notion_client.client.ClientOptions","title":"ClientOptions
dataclass
","text":"Options to configure the client.
Attributes:
Name Type Description auth
Optional[str]
Bearer token for authentication. If left undefined, the auth
parameter should be set on each request.
timeout_ms
int
Number of milliseconds to wait before emitting a RequestTimeoutError
.
base_url
str
The root URL for sending API requests. This can be changed to test with a mock server.
log_level
int
Verbosity of logs the instance will produce. By default, logs are written to stdout
.
logger
Optional[Logger]
A custom logger.
notion_version
str
Notion version to use.
Source code in notion_client/client.py
@dataclass\nclass ClientOptions:\n \"\"\"Options to configure the client.\n\n Attributes:\n auth: Bearer token for authentication. If left undefined, the `auth` parameter\n should be set on each request.\n timeout_ms: Number of milliseconds to wait before emitting a\n `RequestTimeoutError`.\n base_url: The root URL for sending API requests. This can be changed to test with\n a mock server.\n log_level: Verbosity of logs the instance will produce. By default, logs are\n written to `stdout`.\n logger: A custom logger.\n notion_version: Notion version to use.\n \"\"\"\n\n auth: Optional[str] = None\n timeout_ms: int = 60_000\n base_url: str = \"https://api.notion.com\"\n log_level: int = logging.WARNING\n logger: Optional[logging.Logger] = None\n notion_version: str = \"2022-06-28\"\n
"},{"location":"reference/errors/","title":"Errors","text":"Custom exceptions for notion-sdk-py.
This module defines the exceptions that can be raised when an error occurs.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode","title":"APIErrorCode
","text":" Bases: str
, Enum
Source code in notion_client/errors.py
class APIErrorCode(str, Enum):\n Unauthorized = \"unauthorized\"\n \"\"\"The bearer token is not valid.\"\"\"\n\n RestrictedResource = \"restricted_resource\"\n \"\"\"Given the bearer token used, the client doesn't have permission to\n perform this operation.\"\"\"\n\n ObjectNotFound = \"object_not_found\"\n \"\"\"Given the bearer token used, the resource does not exist.\n This error can also indicate that the resource has not been shared with owner\n of the bearer token.\"\"\"\n\n RateLimited = \"rate_limited\"\n \"\"\"This request exceeds the number of requests allowed. Slow down and try again.\"\"\"\n\n InvalidJSON = \"invalid_json\"\n \"\"\"The request body could not be decoded as JSON.\"\"\"\n\n InvalidRequestURL = \"invalid_request_url\"\n \"\"\"The request URL is not valid.\"\"\"\n\n InvalidRequest = \"invalid_request\"\n \"\"\"This request is not supported.\"\"\"\n\n ValidationError = \"validation_error\"\n \"\"\"The request body does not match the schema for the expected parameters.\"\"\"\n\n ConflictError = \"conflict_error\"\n \"\"\"The transaction could not be completed, potentially due to a data collision.\n Make sure the parameters are up to date and try again.\"\"\"\n\n InternalServerError = \"internal_server_error\"\n \"\"\"An unexpected error occurred. Reach out to Notion support.\"\"\"\n\n ServiceUnavailable = \"service_unavailable\"\n \"\"\"Notion is unavailable. Try again later.\n This can occur when the time to respond to a request takes longer than 60 seconds,\n the maximum request timeout.\"\"\"\n
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.ConflictError","title":"ConflictError = 'conflict_error'
class-attribute
instance-attribute
","text":"The transaction could not be completed, potentially due to a data collision. Make sure the parameters are up to date and try again.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.InternalServerError","title":"InternalServerError = 'internal_server_error'
class-attribute
instance-attribute
","text":"An unexpected error occurred. Reach out to Notion support.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.InvalidJSON","title":"InvalidJSON = 'invalid_json'
class-attribute
instance-attribute
","text":"The request body could not be decoded as JSON.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.InvalidRequest","title":"InvalidRequest = 'invalid_request'
class-attribute
instance-attribute
","text":"This request is not supported.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.InvalidRequestURL","title":"InvalidRequestURL = 'invalid_request_url'
class-attribute
instance-attribute
","text":"The request URL is not valid.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.ObjectNotFound","title":"ObjectNotFound = 'object_not_found'
class-attribute
instance-attribute
","text":"Given the bearer token used, the resource does not exist. This error can also indicate that the resource has not been shared with owner of the bearer token.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.RateLimited","title":"RateLimited = 'rate_limited'
class-attribute
instance-attribute
","text":"This request exceeds the number of requests allowed. Slow down and try again.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.RestrictedResource","title":"RestrictedResource = 'restricted_resource'
class-attribute
instance-attribute
","text":"Given the bearer token used, the client doesn't have permission to perform this operation.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.ServiceUnavailable","title":"ServiceUnavailable = 'service_unavailable'
class-attribute
instance-attribute
","text":"Notion is unavailable. Try again later. This can occur when the time to respond to a request takes longer than 60 seconds, the maximum request timeout.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.Unauthorized","title":"Unauthorized = 'unauthorized'
class-attribute
instance-attribute
","text":"The bearer token is not valid.
"},{"location":"reference/errors/#notion_client.errors.APIErrorCode.ValidationError","title":"ValidationError = 'validation_error'
class-attribute
instance-attribute
","text":"The request body does not match the schema for the expected parameters.
"},{"location":"reference/errors/#notion_client.errors.APIResponseError","title":"APIResponseError
","text":" Bases: HTTPResponseError
An error raised by Notion API.
Source code in notion_client/errors.py
class APIResponseError(HTTPResponseError):\n \"\"\"An error raised by Notion API.\"\"\"\n\n code: APIErrorCode\n\n def __init__(\n self, response: httpx.Response, message: str, code: APIErrorCode\n ) -> None:\n super().__init__(response, message)\n self.code = code\n
"},{"location":"reference/errors/#notion_client.errors.HTTPResponseError","title":"HTTPResponseError
","text":" Bases: Exception
Exception for HTTP errors.
Responses from the API use HTTP response codes that are used to indicate general classes of success and error.
Source code in notion_client/errors.py
class HTTPResponseError(Exception):\n \"\"\"Exception for HTTP errors.\n\n Responses from the API use HTTP response codes that are used to indicate general\n classes of success and error.\n \"\"\"\n\n code: str = \"notionhq_client_response_error\"\n status: int\n headers: httpx.Headers\n body: str\n\n def __init__(self, response: httpx.Response, message: Optional[str] = None) -> None:\n if message is None:\n message = (\n f\"Request to Notion API failed with status: {response.status_code}\"\n )\n super().__init__(message)\n self.status = response.status_code\n self.headers = response.headers\n self.body = response.text\n
"},{"location":"reference/errors/#notion_client.errors.RequestTimeoutError","title":"RequestTimeoutError
","text":" Bases: Exception
Exception for requests that timeout.
The request that we made waits for a specified period of time or maximum number of retries to get the response. But if no response comes within the limited time or retries, then this Exception is raised.
Source code in notion_client/errors.py
class RequestTimeoutError(Exception):\n \"\"\"Exception for requests that timeout.\n\n The request that we made waits for a specified period of time or maximum number of\n retries to get the response. But if no response comes within the limited time or\n retries, then this Exception is raised.\n \"\"\"\n\n code = \"notionhq_client_request_timeout\"\n\n def __init__(self, message: str = \"Request to Notion API has timed out\") -> None:\n super().__init__(message)\n
"},{"location":"reference/errors/#notion_client.errors.is_api_error_code","title":"is_api_error_code(code)
","text":"Check if given code belongs to the list of valid API error codes.
Source code in notion_client/errors.py
def is_api_error_code(code: str) -> bool:\n \"\"\"Check if given code belongs to the list of valid API error codes.\"\"\"\n if isinstance(code, str):\n return code in (error_code.value for error_code in APIErrorCode)\n return False\n
"},{"location":"reference/helpers/","title":"Helpers","text":"Utility functions for notion-sdk-py.
"},{"location":"reference/helpers/#notion_client.helpers.async_collect_paginated_api","title":"async_collect_paginated_api(function, **kwargs)
async
","text":"Collect asynchronously all the results of paginating an API into a list.
Source code in notion_client/helpers.py
async def async_collect_paginated_api(\n function: Callable[..., Awaitable[Any]], **kwargs: Any\n) -> List[Any]:\n \"\"\"Collect asynchronously all the results of paginating an API into a list.\"\"\"\n return [result async for result in async_iterate_paginated_api(function, **kwargs)]\n
"},{"location":"reference/helpers/#notion_client.helpers.async_iterate_paginated_api","title":"async_iterate_paginated_api(function, **kwargs)
async
","text":"Return an async iterator over the results of any paginated Notion API.
Source code in notion_client/helpers.py
async def async_iterate_paginated_api(\n function: Callable[..., Awaitable[Any]], **kwargs: Any\n) -> AsyncGenerator[Any, None]:\n \"\"\"Return an async iterator over the results of any paginated Notion API.\"\"\"\n next_cursor = kwargs.pop(\"start_cursor\", None)\n\n while True:\n response = await function(**kwargs, start_cursor=next_cursor)\n for result in response.get(\"results\"):\n yield result\n\n next_cursor = response.get(\"next_cursor\")\n if (not response[\"has_more\"]) | (next_cursor is None):\n return\n
"},{"location":"reference/helpers/#notion_client.helpers.collect_paginated_api","title":"collect_paginated_api(function, **kwargs)
","text":"Collect all the results of paginating an API into a list.
Source code in notion_client/helpers.py
def collect_paginated_api(function: Callable[..., Any], **kwargs: Any) -> List[Any]:\n \"\"\"Collect all the results of paginating an API into a list.\"\"\"\n return [result for result in iterate_paginated_api(function, **kwargs)]\n
"},{"location":"reference/helpers/#notion_client.helpers.get_id","title":"get_id(url)
","text":"Return the id of the object behind the given URL.
Source code in notion_client/helpers.py
def get_id(url: str) -> str:\n \"\"\"Return the id of the object behind the given URL.\"\"\"\n parsed = urlparse(url)\n if parsed.netloc not in (\"notion.so\", \"www.notion.so\"):\n raise ValueError(\"Not a valid Notion URL.\")\n path = parsed.path\n if len(path) < 32:\n raise ValueError(\"The path in the URL seems to be incorrect.\")\n raw_id = path[-32:]\n return str(UUID(raw_id))\n
"},{"location":"reference/helpers/#notion_client.helpers.get_url","title":"get_url(object_id)
","text":"Return the URL for the object with the given id.
Source code in notion_client/helpers.py
def get_url(object_id: str) -> str:\n \"\"\"Return the URL for the object with the given id.\"\"\"\n return f\"https://notion.so/{UUID(object_id).hex}\"\n
"},{"location":"reference/helpers/#notion_client.helpers.is_equation_rich_text_item_response","title":"is_equation_rich_text_item_response(rich_text)
","text":"Return True
if rich_text
is an equation.
Source code in notion_client/helpers.py
def is_equation_rich_text_item_response(rich_text: Dict[Any, Any]) -> bool:\n \"\"\"Return `True` if `rich_text` is an equation.\"\"\"\n return rich_text.get(\"type\") == \"equation\"\n
"},{"location":"reference/helpers/#notion_client.helpers.is_full_block","title":"is_full_block(response)
","text":"Return True
if response is a full block.
Source code in notion_client/helpers.py
def is_full_block(response: Dict[Any, Any]) -> bool:\n \"\"\"Return `True` if response is a full block.\"\"\"\n return response.get(\"object\") == \"block\" and \"type\" in response\n
"},{"location":"reference/helpers/#notion_client.helpers.is_full_comment","title":"is_full_comment(response)
","text":"Return True
if response is a full comment.
Source code in notion_client/helpers.py
def is_full_comment(response: Dict[Any, Any]) -> bool:\n \"\"\"Return `True` if response is a full comment.\"\"\"\n return \"type\" in response\n
"},{"location":"reference/helpers/#notion_client.helpers.is_full_database","title":"is_full_database(response)
","text":"Return True
if response is a full database.
Source code in notion_client/helpers.py
def is_full_database(response: Dict[Any, Any]) -> bool:\n \"\"\"Return `True` if response is a full database.\"\"\"\n return response.get(\"object\") == \"database\" and \"title\" in response\n
"},{"location":"reference/helpers/#notion_client.helpers.is_full_page","title":"is_full_page(response)
","text":"Return True
if response is a full page.
Source code in notion_client/helpers.py
def is_full_page(response: Dict[Any, Any]) -> bool:\n \"\"\"Return `True` if response is a full page.\"\"\"\n return response.get(\"object\") == \"page\" and \"url\" in response\n
"},{"location":"reference/helpers/#notion_client.helpers.is_full_page_or_database","title":"is_full_page_or_database(response)
","text":"Return True
if response
is a full database or a full page.
Source code in notion_client/helpers.py
def is_full_page_or_database(response: Dict[Any, Any]) -> bool:\n \"\"\"Return `True` if `response` is a full database or a full page.\"\"\"\n if response.get(\"object\") == \"database\":\n return is_full_database(response)\n return is_full_page(response)\n
"},{"location":"reference/helpers/#notion_client.helpers.is_full_user","title":"is_full_user(response)
","text":"Return True
if response is a full user.
Source code in notion_client/helpers.py
def is_full_user(response: Dict[Any, Any]) -> bool:\n \"\"\"Return `True` if response is a full user.\"\"\"\n return \"type\" in response\n
"},{"location":"reference/helpers/#notion_client.helpers.is_mention_rich_text_item_response","title":"is_mention_rich_text_item_response(rich_text)
","text":"Return True
if rich_text
is a mention.
Source code in notion_client/helpers.py
def is_mention_rich_text_item_response(rich_text: Dict[Any, Any]) -> bool:\n \"\"\"Return `True` if `rich_text` is a mention.\"\"\"\n return rich_text.get(\"type\") == \"mention\"\n
"},{"location":"reference/helpers/#notion_client.helpers.is_text_rich_text_item_response","title":"is_text_rich_text_item_response(rich_text)
","text":"Return True
if rich_text
is a text.
Source code in notion_client/helpers.py
def is_text_rich_text_item_response(rich_text: Dict[Any, Any]) -> bool:\n \"\"\"Return `True` if `rich_text` is a text.\"\"\"\n return rich_text.get(\"type\") == \"text\"\n
"},{"location":"reference/helpers/#notion_client.helpers.iterate_paginated_api","title":"iterate_paginated_api(function, **kwargs)
","text":"Return an iterator over the results of any paginated Notion API.
Source code in notion_client/helpers.py
def iterate_paginated_api(\n function: Callable[..., Any], **kwargs: Any\n) -> Generator[Any, None, None]:\n \"\"\"Return an iterator over the results of any paginated Notion API.\"\"\"\n next_cursor = kwargs.pop(\"start_cursor\", None)\n\n while True:\n response = function(**kwargs, start_cursor=next_cursor)\n for result in response.get(\"results\"):\n yield result\n\n next_cursor = response.get(\"next_cursor\")\n if not response.get(\"has_more\") or not next_cursor:\n return\n
"},{"location":"reference/helpers/#notion_client.helpers.pick","title":"pick(base, *keys)
","text":"Return a dict composed of key value pairs for keys passed as args.
Source code in notion_client/helpers.py
def pick(base: Dict[Any, Any], *keys: str) -> Dict[Any, Any]:\n \"\"\"Return a dict composed of key value pairs for keys passed as args.\"\"\"\n result = {}\n for key in keys:\n if key not in base:\n continue\n value = base.get(key)\n if value is None and key == \"start_cursor\":\n continue\n result[key] = value\n return result\n
"},{"location":"user_guides/quick_start/","title":"Quick start","text":"Get started with notion-sdk-py in just 5 minutes!
"},{"location":"user_guides/quick_start/#setup","title":"Setup","text":""},{"location":"user_guides/quick_start/#prerequisites","title":"Prerequisites","text":" -
Make sure you have python
and pip
properly installed in your system.
python --version\npip --version\n
-
Create a new directory and move into it to follow along with this tutorial.
mkdir learn-notion-sdk-py && cd learn-notion-sdk-py\n
"},{"location":"user_guides/quick_start/#installation","title":"Installation","text":" -
Create a virtual environment and activate it.
python -m venv .venv && source .venv/bin/activate\n
-
Install notion-sdk-py
using pip
pip install --upgrade notion-client\n
"},{"location":"user_guides/quick_start/#integration","title":"Integration","text":" -
Go to notion.so/my-integrations to create an integration. Copy the token given by Notion.
-
Make it available in your environment:
export NOTION_TOKEN=ntn_abcd12345\n
Tip
Don't forget that export
only puts the variable in the environment of the current shell. If you don't want to redo this step for every new shell, add the line in your shell configuration or use a configuration library like dotenv.
"},{"location":"user_guides/quick_start/#play","title":"Play","text":"Copy paste the code, and have fun tweaking it!
Let's start by initializing the client:
import os\nfrom notion_client import Client\n\nnotion = Client(auth=os.environ[\"NOTION_TOKEN\"])\n
Let's now fetch the list of users in the scope of our integration:
users = notion.users.list()\n\nfor user in users.get(\"results\"):\n name, user_type = user[\"name\"], user[\"type\"]\n emoji = \"\ud83d\ude05\" if user[\"type\"] == \"bot\" else \"\ud83d\ude4b\u200d\u2642\ufe0f\"\n print(f\"{name} is a {user_type} {emoji}\")\n
It should output something in those lines:
Aahnik Daw is a person \ud83d\ude4b\u200d\u2642\ufe0f\nTestIntegation is a bot \ud83d\ude05\n
Do you see your name and the name of your integration?
\ud83c\udf89 Congratulations, you are now ready to use notion-sdk-py!
"},{"location":"user_guides/structured_logging/","title":"Structured logging","text":"You can easily get structured logging with notion-sdk-py by using structlog:
logger = structlog.wrap_logger(\n logging.getLogger(\"notion-client\"),\n logger_factory=structlog.stdlib.LoggerFactory(),\n wrapper_class=structlog.stdlib.BoundLogger,\n)\n\nnotion = Client(auth=token, logger=logger, log_level=logging.DEBUG)\n
Don't forget to add the dependency to your project!
"},{"location":"coverage/","title":"Coverage report","text":""}]}
\ No newline at end of file
diff --git a/sitemap.xml.gz b/sitemap.xml.gz
index 969953a..2ef01e8 100644
Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ
diff --git a/user_guides/quick_start/index.html b/user_guides/quick_start/index.html
index 8bab06a..732b24d 100644
--- a/user_guides/quick_start/index.html
+++ b/user_guides/quick_start/index.html
@@ -865,8 +865,8 @@ Integration
Play
Copy paste the code, and have fun tweaking it!
Let's start by initializing the client:
-import os
-from notion_client import Client
+import os
+from notion_client import Client
notion = Client(auth=os.environ["NOTION_TOKEN"])