0
# Client Configuration
1
2
Client classes and configuration options for the Notion API client library, supporting both synchronous and asynchronous operations with comprehensive configuration capabilities.
3
4
## Capabilities
5
6
### Client Classes
7
8
#### Synchronous Client
9
10
The main synchronous client for Notion API operations.
11
12
```python { .api }
13
class Client:
14
"""Synchronous client for Notion's API."""
15
16
def __init__(self, options=None, client=None, **kwargs):
17
"""
18
Initialize the synchronous client.
19
20
Parameters:
21
- options: ClientOptions or dict with configuration options
22
- client: Optional custom httpx.Client instance
23
- **kwargs: Configuration options passed directly (alternative to options dict)
24
"""
25
26
def __enter__(self):
27
"""Context manager entry."""
28
29
def __exit__(self, exc_type, exc_value, traceback):
30
"""Context manager exit."""
31
32
def close(self):
33
"""Close the connection pool of the current inner client."""
34
35
def request(self, path, method, query=None, body=None, form_data=None, auth=None):
36
"""
37
Send an HTTP request.
38
39
Parameters:
40
- path: str, API endpoint path
41
- method: str, HTTP method (GET, POST, PATCH, DELETE)
42
- query: dict, query parameters
43
- body: dict, request body for JSON requests
44
- form_data: dict, form data for multipart requests
45
- auth: str, optional auth token for this request
46
47
Returns:
48
Response data as dict
49
50
Raises:
51
- RequestTimeoutError: If request times out
52
- APIResponseError: If API returns an error
53
- HTTPResponseError: If HTTP request fails
54
"""
55
```
56
57
#### Asynchronous Client
58
59
The asynchronous client for use in async/await environments.
60
61
```python { .api }
62
class AsyncClient:
63
"""Asynchronous client for Notion's API."""
64
65
def __init__(self, options=None, client=None, **kwargs):
66
"""
67
Initialize the asynchronous client.
68
69
Parameters:
70
- options: ClientOptions or dict with configuration options
71
- client: Optional custom httpx.AsyncClient instance
72
- **kwargs: Configuration options passed directly (alternative to options dict)
73
"""
74
75
async def __aenter__(self):
76
"""Async context manager entry."""
77
78
async def __aexit__(self, exc_type, exc_value, traceback):
79
"""Async context manager exit."""
80
81
async def aclose(self):
82
"""Close the connection pool of the current inner client."""
83
84
async def request(self, path, method, query=None, body=None, form_data=None, auth=None):
85
"""
86
Send an HTTP request asynchronously.
87
88
Parameters:
89
- path: str, API endpoint path
90
- method: str, HTTP method (GET, POST, PATCH, DELETE)
91
- query: dict, query parameters
92
- body: dict, request body for JSON requests
93
- form_data: dict, form data for multipart requests
94
- auth: str, optional auth token for this request
95
96
Returns:
97
Response data as dict
98
99
Raises:
100
- RequestTimeoutError: If request times out
101
- APIResponseError: If API returns an error
102
- HTTPResponseError: If HTTP request fails
103
"""
104
```
105
106
### Client Configuration
107
108
#### ClientOptions
109
110
Configuration options for customizing client behavior.
111
112
```python { .api }
113
@dataclass
114
class ClientOptions:
115
"""Options to configure the client."""
116
117
auth: Optional[str] = None
118
"""Bearer token for authentication. If left undefined, the auth parameter should be set on each request."""
119
120
timeout_ms: int = 60_000
121
"""Number of milliseconds to wait before emitting a RequestTimeoutError."""
122
123
base_url: str = "https://api.notion.com"
124
"""The root URL for sending API requests. This can be changed to test with a mock server."""
125
126
log_level: int = logging.WARNING
127
"""Verbosity of logs the instance will produce. By default, logs are written to stdout."""
128
129
logger: Optional[logging.Logger] = None
130
"""A custom logger."""
131
132
notion_version: str = "2022-06-28"
133
"""Notion version to use."""
134
```
135
136
### Base Client
137
138
The shared base implementation for both sync and async clients.
139
140
```python { .api }
141
class BaseClient:
142
"""Base client with shared functionality."""
143
144
def __init__(self, client, options=None, **kwargs):
145
"""
146
Initialize the base client.
147
148
Parameters:
149
- client: httpx.Client or httpx.AsyncClient instance
150
- options: ClientOptions or dict with configuration options
151
- **kwargs: Configuration options passed directly
152
"""
153
154
# Endpoint instances
155
blocks: BlocksEndpoint
156
databases: DatabasesEndpoint
157
users: UsersEndpoint
158
pages: PagesEndpoint
159
search: SearchEndpoint
160
comments: CommentsEndpoint
161
file_uploads: FileUploadsEndpoint
162
163
# Properties
164
client: Union[httpx.Client, httpx.AsyncClient]
165
logger: logging.Logger
166
options: ClientOptions
167
```
168
169
## Usage Examples
170
171
### Basic Initialization
172
173
```python
174
from notion_client import Client, AsyncClient
175
import os
176
177
# Synchronous client with environment variable
178
notion = Client(auth=os.environ["NOTION_TOKEN"])
179
180
# Asynchronous client with environment variable
181
async_notion = AsyncClient(auth=os.environ["NOTION_TOKEN"])
182
```
183
184
### Advanced Configuration
185
186
```python
187
import logging
188
from notion_client import Client, ClientOptions
189
190
# Using ClientOptions dataclass
191
options = ClientOptions(
192
auth="your_token_here",
193
timeout_ms=30_000, # 30 seconds
194
log_level=logging.DEBUG,
195
base_url="https://api.notion.com" # Default, shown for example
196
)
197
notion = Client(options=options)
198
199
# Using keyword arguments
200
notion = Client(
201
auth="your_token_here",
202
timeout_ms=30_000,
203
log_level=logging.DEBUG
204
)
205
206
# Using options dictionary
207
notion = Client(options={
208
"auth": "your_token_here",
209
"timeout_ms": 30_000,
210
"log_level": logging.DEBUG
211
})
212
```
213
214
### Custom Logger
215
216
```python
217
import logging
218
from notion_client import Client
219
220
# Create custom logger
221
logger = logging.getLogger("my_notion_client")
222
handler = logging.FileHandler("notion_api.log")
223
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
224
handler.setFormatter(formatter)
225
logger.addHandler(handler)
226
logger.setLevel(logging.DEBUG)
227
228
# Use custom logger
229
notion = Client(
230
auth=os.environ["NOTION_TOKEN"],
231
logger=logger,
232
log_level=logging.DEBUG
233
)
234
```
235
236
### Context Managers
237
238
```python
239
# Synchronous context manager
240
with Client(auth=os.environ["NOTION_TOKEN"]) as notion:
241
users = notion.users.list()
242
# Connection automatically closed
243
244
# Asynchronous context manager
245
async with AsyncClient(auth=os.environ["NOTION_TOKEN"]) as notion:
246
users = await notion.users.list()
247
# Connection automatically closed
248
```
249
250
### Custom HTTP Client
251
252
```python
253
import httpx
254
from notion_client import Client, AsyncClient
255
256
# Custom synchronous HTTP client
257
custom_client = httpx.Client(
258
timeout=30.0,
259
limits=httpx.Limits(max_keepalive_connections=5, max_connections=10)
260
)
261
notion = Client(client=custom_client, auth="your_token")
262
263
# Custom asynchronous HTTP client
264
custom_async_client = httpx.AsyncClient(
265
timeout=30.0,
266
limits=httpx.Limits(max_keepalive_connections=5, max_connections=10)
267
)
268
async_notion = AsyncClient(client=custom_async_client, auth="your_token")
269
```
270
271
### Per-Request Authentication
272
273
```python
274
# Initialize client without default auth
275
notion = Client()
276
277
# Provide auth per request
278
users = notion.users.list(auth="token_for_this_request")
279
databases = notion.databases.query(
280
database_id="xxx",
281
auth="different_token_for_this_request"
282
)
283
```
284
285
### Testing with Mock Server
286
287
```python
288
from notion_client import Client
289
290
# Point to mock server for testing
291
notion = Client(
292
auth="test_token",
293
base_url="http://localhost:3000" # Your mock server
294
)
295
```
296
297
## Client Lifecycle
298
299
### Manual Resource Management
300
301
```python
302
# Create client
303
notion = Client(auth="your_token")
304
305
# Use client
306
users = notion.users.list()
307
308
# Manually close when done
309
notion.close()
310
311
# For async client
312
async_notion = AsyncClient(auth="your_token")
313
users = await async_notion.users.list()
314
await async_notion.aclose()
315
```
316
317
### Automatic Resource Management
318
319
```python
320
# Context managers handle cleanup automatically
321
with Client(auth="your_token") as notion:
322
users = notion.users.list()
323
# Automatically closed on exit
324
325
async with AsyncClient(auth="your_token") as notion:
326
users = await notion.users.list()
327
# Automatically closed on exit
328
```