Skip to content

Client

Synchronous and asynchronous clients for Notion's API.

AsyncClient

Bases: BaseClient

Asynchronous client for Notion's API.

Source code in notion_client/client.py
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
class AsyncClient(BaseClient):
    """Asynchronous client for Notion's API."""

    client: httpx.AsyncClient

    def __init__(
        self,
        options: Optional[Union[Dict[str, Any], ClientOptions]] = None,
        client: Optional[httpx.AsyncClient] = None,
        **kwargs: Any,
    ) -> None:
        if client is None:
            client = httpx.AsyncClient()
        super().__init__(client, options, **kwargs)

    async def __aenter__(self) -> "AsyncClient":
        self.client = httpx.AsyncClient()
        await self.client.__aenter__()
        return self

    async def __aexit__(
        self,
        exc_type: Type[BaseException],
        exc_value: BaseException,
        traceback: TracebackType,
    ) -> None:
        await self.client.__aexit__(exc_type, exc_value, traceback)
        del self._clients[-1]

    async def aclose(self) -> None:
        """Close the connection pool of the current inner client."""
        await self.client.aclose()

    async def request(
        self,
        path: str,
        method: str,
        query: Optional[Dict[Any, Any]] = None,
        body: Optional[Dict[Any, Any]] = None,
        form_data: Optional[Dict[Any, Any]] = None,
        auth: Optional[Union[str, Dict[str, str]]] = None,
    ) -> Any:
        """Send an HTTP request asynchronously."""
        request = self._build_request(method, path, query, body, form_data, auth)
        return await self._execute(request, method, path)

    async def _execute(
        self,
        request: Request,
        method: str,
        path: str,
    ) -> Any:
        """Executes the request with retry logic."""
        try:
            return await self._execute_single_request(request, method, path)
        except Exception as error:
            if not is_notion_client_error(error):
                raise error

            self._log_request_error(error)
            raise error

    async def _execute_single_request(
        self, request: Request, method: str, path: str
    ) -> Any:
        """Executes a single HTTP request (no retry)."""
        try:
            response = await self.client.send(request)
        except httpx.TimeoutException:
            raise RequestTimeoutError()
        response_body = self._parse_response(response)
        self._log_request_success(method, path, response_body)
        return response_body

aclose() async

Close the connection pool of the current inner client.

Source code in notion_client/client.py
312
313
314
async def aclose(self) -> None:
    """Close the connection pool of the current inner client."""
    await self.client.aclose()

request(path, method, query=None, body=None, form_data=None, auth=None) async

Send an HTTP request asynchronously.

Source code in notion_client/client.py
316
317
318
319
320
321
322
323
324
325
326
327
async def request(
    self,
    path: str,
    method: str,
    query: Optional[Dict[Any, Any]] = None,
    body: Optional[Dict[Any, Any]] = None,
    form_data: Optional[Dict[Any, Any]] = None,
    auth: Optional[Union[str, Dict[str, str]]] = None,
) -> Any:
    """Send an HTTP request asynchronously."""
    request = self._build_request(method, path, query, body, form_data, auth)
    return await self._execute(request, method, path)

BaseClient

Source code in notion_client/client.py
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
class BaseClient:
    def __init__(
        self,
        client: Union[httpx.Client, httpx.AsyncClient],
        options: Optional[Union[Dict[str, Any], ClientOptions]] = None,
        **kwargs: Any,
    ) -> None:
        if options is None:
            options = ClientOptions(**kwargs)
        elif isinstance(options, dict):
            options = ClientOptions(**options)

        self.logger = options.logger or make_console_logger()
        self.logger.setLevel(options.log_level)
        self.options = options

        self._clients: List[Union[httpx.Client, httpx.AsyncClient]] = []
        self.client = client

        self.blocks = BlocksEndpoint(self)
        self.databases = DatabasesEndpoint(self)
        self.data_sources = DataSourcesEndpoint(self)
        self.users = UsersEndpoint(self)
        self.pages = PagesEndpoint(self)
        self.search = SearchEndpoint(self)
        self.comments = CommentsEndpoint(self)
        self.file_uploads = FileUploadsEndpoint(self)
        self.oauth = OAuthEndpoint(self)

    @property
    def client(self) -> Union[httpx.Client, httpx.AsyncClient]:
        return self._clients[-1]

    @client.setter
    def client(self, client: Union[httpx.Client, httpx.AsyncClient]) -> None:
        client.base_url = httpx.URL(f"{self.options.base_url}/v1/")
        client.timeout = httpx.Timeout(timeout=self.options.timeout_ms / 1_000)
        client.headers = httpx.Headers(
            {
                "Notion-Version": self.options.notion_version,
                "User-Agent": "ramnes/notion-sdk-py@3.0.0",
            }
        )
        if self.options.auth:
            client.headers["Authorization"] = f"Bearer {self.options.auth}"
        self._clients.append(client)

    def _build_request(
        self,
        method: str,
        path: str,
        query: Optional[Dict[Any, Any]] = None,
        body: Optional[Dict[Any, Any]] = None,
        form_data: Optional[Dict[Any, Any]] = None,
        auth: Optional[Union[str, Dict[str, str]]] = None,
    ) -> Request:
        headers = httpx.Headers()
        validate_request_path(path)
        if auth:
            if isinstance(auth, dict):
                client_id = auth.get("client_id", "")
                client_secret = auth.get("client_secret", "")
                credentials = f"{client_id}:{client_secret}"
                encoded_credentials = base64.b64encode(credentials.encode()).decode()
                headers["Authorization"] = f"Basic {encoded_credentials}"
            else:
                headers["Authorization"] = f"Bearer {auth}"
        self.logger.info(f"{method} {self.client.base_url}{path}")
        self.logger.debug(f"=> {query} -- {body} -- {form_data}")

        if not form_data:
            return self.client.build_request(
                method,
                path,
                params=query,
                json=body,
                headers=headers,
            )

        files: Dict[str, Any] = {}
        data: Dict[str, Any] = {}
        for key, value in form_data.items():
            if isinstance(value, tuple) and len(value) >= 2:
                files[key] = value
            elif hasattr(value, "read"):
                files[key] = value
            elif isinstance(value, str):
                data[key] = value
            else:
                data[key] = str(value)

        return self.client.build_request(
            method,
            path,
            params=query,
            files=files,
            data=data,
            headers=headers,
        )

    def _parse_response(self, response: Response) -> Any:
        try:
            response.raise_for_status()
        except httpx.HTTPStatusError as error:
            body_text = error.response.text
            raise build_request_error(error.response, body_text)

        return response.json()

    def _extract_request_id(self, obj: Any) -> Optional[str]:
        """Extracts request_id from an object if present."""
        if isinstance(obj, dict):
            return obj.get("request_id")
        else:
            request_id = getattr(obj, "request_id", None)
        return request_id if isinstance(request_id, str) else None

    def _log_request_success(self, method: str, path: str, response_body: Any) -> None:
        """Logs a successful request."""
        request_id = self._extract_request_id(response_body)
        msg = f"request success: method={method}, path={path}"
        if request_id:
            msg += f", request_id={request_id}"
        self.logger.info(msg)

    def _log_request_error(self, error: NotionClientError) -> None:
        """Logs a request error with appropriate detail level."""
        request_id = self._extract_request_id(error)
        msg = f"request fail: code={error.code}, message={error}"
        if request_id:
            msg += f", request_id={request_id}"
        self.logger.warning(msg)
        if is_http_response_error(error):
            self.logger.debug(f"failed response body: {error.body}")

    @abstractmethod
    def request(
        self,
        path: str,
        method: str,
        query: Optional[Dict[Any, Any]] = None,
        body: Optional[Dict[Any, Any]] = None,
        form_data: Optional[Dict[Any, Any]] = None,
        auth: Optional[Union[str, Dict[str, str]]] = None,
    ) -> SyncAsync[Any]:
        # noqa
        pass

Client

Bases: BaseClient

Synchronous client for Notion's API.

Source code in notion_client/client.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
class Client(BaseClient):
    """Synchronous client for Notion's API."""

    client: httpx.Client

    def __init__(
        self,
        options: Optional[Union[Dict[Any, Any], ClientOptions]] = None,
        client: Optional[httpx.Client] = None,
        **kwargs: Any,
    ) -> None:
        if client is None:
            client = httpx.Client()
        super().__init__(client, options, **kwargs)

    def __enter__(self) -> "Client":
        self.client = httpx.Client()
        self.client.__enter__()
        return self

    def __exit__(
        self,
        exc_type: Type[BaseException],
        exc_value: BaseException,
        traceback: TracebackType,
    ) -> None:
        self.client.__exit__(exc_type, exc_value, traceback)
        del self._clients[-1]

    def close(self) -> None:
        """Close the connection pool of the current inner client."""
        self.client.close()

    def request(
        self,
        path: str,
        method: str,
        query: Optional[Dict[Any, Any]] = None,
        body: Optional[Dict[Any, Any]] = None,
        form_data: Optional[Dict[Any, Any]] = None,
        auth: Optional[Union[str, Dict[str, str]]] = None,
    ) -> Any:
        """Send an HTTP request."""
        request = self._build_request(method, path, query, body, form_data, auth)
        return self._execute(request, method, path)

    def _execute(
        self,
        request: Request,
        method: str,
        path: str,
    ) -> Any:
        """Executes the request with retry logic."""
        try:
            return self._execute_single_request(request, method, path)
        except Exception as error:
            if not is_notion_client_error(error):
                raise error

            self._log_request_error(error)
            raise error

    def _execute_single_request(self, request: Request, method: str, path: str) -> Any:
        """Executes a single HTTP request (no retry)."""
        try:
            response = self.client.send(request)
        except httpx.TimeoutException:
            raise RequestTimeoutError()
        response_body = self._parse_response(response)
        self._log_request_success(method, path, response_body)
        return response_body

close()

Close the connection pool of the current inner client.

Source code in notion_client/client.py
239
240
241
def close(self) -> None:
    """Close the connection pool of the current inner client."""
    self.client.close()

request(path, method, query=None, body=None, form_data=None, auth=None)

Send an HTTP request.

Source code in notion_client/client.py
243
244
245
246
247
248
249
250
251
252
253
254
def request(
    self,
    path: str,
    method: str,
    query: Optional[Dict[Any, Any]] = None,
    body: Optional[Dict[Any, Any]] = None,
    form_data: Optional[Dict[Any, Any]] = None,
    auth: Optional[Union[str, Dict[str, str]]] = None,
) -> Any:
    """Send an HTTP request."""
    request = self._build_request(method, path, query, body, form_data, auth)
    return self._execute(request, method, path)

ClientOptions dataclass

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
@dataclass
class ClientOptions:
    """Options to configure the client.

    Attributes:
        auth: Bearer token for authentication. If left undefined, the `auth` parameter
            should be set on each request.
        timeout_ms: Number of milliseconds to wait before emitting a
            `RequestTimeoutError`.
        base_url: The root URL for sending API requests. This can be changed to test
            with a mock server.
        log_level: Verbosity of logs the instance will produce. By default, logs are
            written to `stdout`.
        logger: A custom logger.
        notion_version: Notion version to use.
    """

    auth: Optional[str] = None
    timeout_ms: int = 60_000
    base_url: str = "https://api.notion.com"
    log_level: int = logging.WARNING
    logger: Optional[logging.Logger] = None
    notion_version: str = "2025-09-03"