0
# Notion Client
1
2
A comprehensive Python client library for the official Notion API, providing both synchronous and asynchronous interfaces. This package enables seamless integration with Notion's database and page management capabilities, offering full coverage of Notion's API endpoints including databases, pages, blocks, users, comments, and file uploads with built-in support for structured logging, error handling, and proper authentication mechanisms.
3
4
## Package Information
5
6
- **Package Name**: notion-client
7
- **Language**: Python
8
- **Installation**: `pip install notion-client`
9
- **Python Requirements**: Python 3.7+
10
- **Dependencies**: httpx >= 0.23.0
11
12
## Core Imports
13
14
```python
15
from notion_client import Client, AsyncClient
16
```
17
18
Import error handling classes:
19
20
```python
21
from notion_client import APIErrorCode, APIResponseError
22
```
23
24
## Basic Usage
25
26
### Synchronous Client
27
28
```python
29
import os
30
from notion_client import Client
31
32
# Initialize client with authentication token
33
notion = Client(auth=os.environ["NOTION_TOKEN"])
34
35
# Query a database
36
response = notion.databases.query(
37
database_id="897e5a76-ae52-4b48-9fdf-e71f5945d1af",
38
filter={
39
"property": "Status",
40
"select": {
41
"equals": "Active"
42
}
43
}
44
)
45
46
# List users
47
users = notion.users.list()
48
49
# Create a new page
50
page = notion.pages.create(
51
parent={"database_id": "897e5a76-ae52-4b48-9fdf-e71f5945d1af"},
52
properties={
53
"Title": {
54
"title": [{"text": {"content": "New Page"}}]
55
}
56
}
57
)
58
```
59
60
### Asynchronous Client
61
62
```python
63
import asyncio
64
from notion_client import AsyncClient
65
66
async def main():
67
notion = AsyncClient(auth=os.environ["NOTION_TOKEN"])
68
69
# All the same methods available asynchronously
70
response = await notion.databases.query(
71
database_id="897e5a76-ae52-4b48-9fdf-e71f5945d1af"
72
)
73
74
users = await notion.users.list()
75
76
await notion.aclose() # Close connection when done
77
78
asyncio.run(main())
79
```
80
81
### Context Manager Usage
82
83
```python
84
# Synchronous context manager
85
with Client(auth=os.environ["NOTION_TOKEN"]) as notion:
86
response = notion.users.list()
87
88
# Asynchronous context manager
89
async with AsyncClient(auth=os.environ["NOTION_TOKEN"]) as notion:
90
response = await notion.users.list()
91
```
92
93
## Architecture
94
95
The notion-client follows a modular endpoint-based architecture:
96
97
- **Client Classes**: `Client` (sync) and `AsyncClient` (async) provide the main interface
98
- **Endpoint Classes**: Each API resource (databases, pages, blocks, etc.) has its own endpoint class
99
- **Error Handling**: Comprehensive exception hierarchy for different error types
100
- **Helper Utilities**: Functions for pagination, URL handling, and response validation
101
- **Type Safety**: Full type annotations and py.typed marker for static analysis
102
103
## Capabilities
104
105
### Client Configuration
106
107
Client initialization and configuration options including authentication, timeouts, logging, and custom base URLs.
108
109
```python { .api }
110
class Client:
111
def __init__(self, options=None, client=None, **kwargs): ...
112
def close(self): ...
113
def request(self, path, method, query=None, body=None, form_data=None, auth=None): ...
114
115
class AsyncClient:
116
def __init__(self, options=None, client=None, **kwargs): ...
117
async def aclose(self): ...
118
async def request(self, path, method, query=None, body=None, form_data=None, auth=None): ...
119
120
class ClientOptions:
121
auth: Optional[str] = None
122
timeout_ms: int = 60_000
123
base_url: str = "https://api.notion.com"
124
log_level: int = logging.WARNING
125
logger: Optional[logging.Logger] = None
126
notion_version: str = "2022-06-28"
127
```
128
129
[Client Configuration](./client.md)
130
131
### API Endpoints
132
133
Complete interface to all Notion API endpoints including databases, pages, blocks, users, search, comments, and file uploads. Each endpoint provides CRUD operations with proper parameter handling.
134
135
```python { .api }
136
# Database operations
137
def databases.query(database_id, **kwargs): ...
138
def databases.retrieve(database_id, **kwargs): ...
139
def databases.create(**kwargs): ...
140
def databases.update(database_id, **kwargs): ...
141
142
# Page operations
143
def pages.create(**kwargs): ...
144
def pages.retrieve(page_id, **kwargs): ...
145
def pages.update(page_id, **kwargs): ...
146
147
# Block operations
148
def blocks.retrieve(block_id, **kwargs): ...
149
def blocks.update(block_id, **kwargs): ...
150
def blocks.delete(block_id, **kwargs): ...
151
def blocks.children.list(block_id, **kwargs): ...
152
def blocks.children.append(block_id, **kwargs): ...
153
```
154
155
[API Endpoints](./api-endpoints.md)
156
157
### Error Handling
158
159
Comprehensive error handling with specific exception types for different API error conditions and HTTP errors.
160
161
```python { .api }
162
class APIResponseError(Exception):
163
code: APIErrorCode
164
status: int
165
headers: httpx.Headers
166
body: str
167
168
class APIErrorCode(Enum):
169
Unauthorized = "unauthorized"
170
ObjectNotFound = "object_not_found"
171
RateLimited = "rate_limited"
172
ValidationError = "validation_error"
173
# ... and others
174
```
175
176
[Error Handling](./error-handling.md)
177
178
### Helper Utilities
179
180
Utility functions for pagination, URL handling, response validation, and rich text processing.
181
182
```python { .api }
183
def get_url(object_id: str) -> str: ...
184
def get_id(url: str) -> str: ...
185
def iterate_paginated_api(function, **kwargs): ...
186
def collect_paginated_api(function, **kwargs): ...
187
def is_full_page(response): ...
188
def is_full_database(response): ...
189
```
190
191
[Helper Utilities](./helpers.md)
192
193
## Types
194
195
```python { .api }
196
import logging
197
from typing import TypeVar, Union, Awaitable, Optional
198
199
T = TypeVar("T")
200
SyncAsync = Union[T, Awaitable[T]]
201
```
202
203
## Authentication
204
205
The client supports two authentication methods:
206
207
1. **Integration Token**: For server-side applications
208
2. **OAuth Access Token**: For user-facing applications
209
210
```python
211
# Using integration token
212
notion = Client(auth="secret_xxxxxxxxxxxxx")
213
214
# Using OAuth access token
215
notion = Client(auth="oauth_token_xxxxxxxxxxxxx")
216
```
217
218
## Common Patterns
219
220
### Pagination
221
222
```python
223
from notion_client.helpers import iterate_paginated_api, collect_paginated_api
224
225
# Iterator approach (memory efficient)
226
for page in iterate_paginated_api(notion.databases.query, database_id="xxx"):
227
print(page)
228
229
# Collect all results (loads everything into memory)
230
all_pages = collect_paginated_api(notion.databases.query, database_id="xxx")
231
```
232
233
### Error Handling
234
235
```python
236
from notion_client import APIErrorCode, APIResponseError
237
238
try:
239
page = notion.pages.retrieve(page_id="invalid-id")
240
except APIResponseError as error:
241
if error.code == APIErrorCode.ObjectNotFound:
242
print("Page not found")
243
elif error.code == APIErrorCode.Unauthorized:
244
print("Authentication failed")
245
else:
246
print(f"API error: {error}")
247
```