Skip to content
Open
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:

strategy:
matrix:
python-version: ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]

steps:

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ at the end of the session.

This package supports the following minimum versions:

* Python >= 3.7
* Python >= 3.8
* httpx >= 0.23.0

Earlier versions may still work, but we encourage people building new applications
Expand Down
38 changes: 38 additions & 0 deletions notion_client/api_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,3 +325,41 @@ def list(self, **kwargs: Any) -> SyncAsync[Any]:
query=pick(kwargs, "block_id", "start_cursor", "page_size"),
auth=kwargs.get("auth"),
)


class OAuthEndpoint(Endpoint):
def token(self, **kwargs: Any) -> SyncAsync[Any]:
"""Creates an access token that a third-party service can use to authenticate with Notion.

*[🔗 Endpoint documentation](https://developers.notion.com/reference/create-a-token)*
""" # noqa: E501
return self.parent.request(
path="oauth/token",
method="POST",
body=pick(kwargs, "grant_type", "code", "redirect_uri"),
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR 595 on notion-sdk-js added more to it: makenotion/notion-sdk-js#595

auth=kwargs.get("auth"),
)

def introspect(self, **kwargs: Any) -> SyncAsync[Any]:
"""Get a token's active status, scope, and issued time.

*[🔗 Endpoint documentation](https://developers.notion.com/reference/introspect-token)*
""" # noqa: E501
return self.parent.request(
path="oauth/introspect",
method="POST",
body=pick(kwargs, "token"),
auth=kwargs.get("auth"),
)

def revoke(self, **kwargs: Any) -> SyncAsync[Any]:
"""Revoke an access token.

*[🔗 Endpoint documentation](https://developers.notion.com/reference/revoke-token)*
""" # noqa: E501
return self.parent.request(
path="oauth/revoke",
method="POST",
body=pick(kwargs, "token"),
auth=kwargs.get("auth"),
)
25 changes: 22 additions & 3 deletions notion_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,26 @@
import httpx
from httpx import Request, Response

import base64

from notion_client.api_endpoints import (
BlocksEndpoint,
CommentsEndpoint,
DatabasesEndpoint,
PagesEndpoint,
SearchEndpoint,
UsersEndpoint,
OAuthEndpoint,
)
from notion_client.errors import (
APIResponseError,
HTTPResponseError,
RequestTimeoutError,
is_api_error_code,
APIErrorCode,
)
from notion_client.logging import make_console_logger
from notion_client.typing import SyncAsync
from notion_client.typing import SyncAsync, OAuthHeader


@dataclass
Expand Down Expand Up @@ -77,6 +81,7 @@ def __init__(
self.pages = PagesEndpoint(self)
self.search = SearchEndpoint(self)
self.comments = CommentsEndpoint(self)
self.oauth = OAuthEndpoint(self)

@property
def client(self) -> Union[httpx.Client, httpx.AsyncClient]:
Expand All @@ -102,11 +107,20 @@ def _build_request(
path: str,
query: Optional[Dict[Any, Any]] = None,
body: Optional[Dict[Any, Any]] = None,
auth: Optional[str] = None,
auth: Optional[Union[str, OAuthHeader]] = None,
) -> Request:
headers = httpx.Headers()
if auth:
headers["Authorization"] = f"Bearer {auth}"
# At runtime the TypedDict is the same type as a regular Dict
if isinstance(auth, Dict):
client_id = auth["client_id"]
client_secret = auth["client_secret"]
auth_header = base64.b64encode(
f"{client_id}:{client_secret}".encode()
).decode("utf-8")
headers["Authorization"] = f'Basic "{auth_header}"'
else:
headers["Authorization"] = f"Bearer {auth}"
self.logger.info(f"{method} {self.client.base_url}{path}")
self.logger.debug(f"=> {query} -- {body}")
return self.client.build_request(
Expand All @@ -120,6 +134,11 @@ def _parse_response(self, response: Response) -> Any:
try:
body = error.response.json()
code = body.get("code")
# Any oauth errors throw this exact error syntax, so handle them as so
if "code" not in body and body.get("error") == "invalid_client":
raise APIResponseError(
response, body["error"], APIErrorCode("unauthorized")
)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is weird, how does the JS SDK handle this?

except json.JSONDecodeError:
code = None
if code and is_api_error_code(code):
Expand Down
7 changes: 6 additions & 1 deletion notion_client/typing.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
"""Custom type definitions for notion-sdk-py."""
from typing import Awaitable, TypeVar, Union
from typing import Awaitable, TypeVar, Union, TypedDict

T = TypeVar("T")
SyncAsync = Union[T, Awaitable[T]]


class OAuthHeader(TypedDict):
client_id: str
client_secret: str
1 change: 0 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ def get_description():
"httpx >= 0.23.0",
],
classifiers=[
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
Expand Down
75 changes: 75 additions & 0 deletions tests/cassettes/test_client_request_oauth.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
interactions:
- request:
body: ''
headers:
accept:
- '*/*'
accept-encoding:
- gzip, deflate
connection:
- keep-alive
content-length:
- '0'
host:
- api.notion.com
notion-version:
- '2022-06-28'
method: POST
uri: https://api.notion.com/v1/oauth/introspect
response:
content: '{"error":"invalid_client","request_id":"141bd2e5-09c1-4697-b80b-5fd2fd4dc45b"}'
headers: {}
http_version: HTTP/1.1
status_code: 401
- request:
body: ''
headers:
accept:
- '*/*'
accept-encoding:
- gzip, deflate
authorization:
- ntn_...
connection:
- keep-alive
content-length:
- '0'
host:
- api.notion.com
notion-version:
- '2022-06-28'
method: POST
uri: https://api.notion.com/v1/oauth/introspect
response:
content: '{"error":"invalid_client","request_id":"f678e9ff-7a4e-4ba7-a74e-d9edb7b81047"}'
headers: {}
http_version: HTTP/1.1
status_code: 401
- request:
body: '{"token": "ntn_..."}'
headers:
accept:
- '*/*'
accept-encoding:
- gzip, deflate
authorization:
- Basic "Base64Encoded($client_id:$client_secret)"
connection:
- keep-alive
content-length:
- '63'
content-type:
- application/json
host:
- api.notion.com
notion-version:
- '2022-06-28'
method: POST
uri: https://api.notion.com/v1/oauth/introspect
response:
content: '{"active":true,"scope":"read_content insert_content update_content read_user_with_email
read_user_without_email","iat":1742416470043,"request_id":"498e8bad-8927-4dd9-9b82-bf7e051f86d4"}'
headers: {}
http_version: HTTP/1.1
status_code: 200
version: 1
29 changes: 29 additions & 0 deletions tests/cassettes/test_introspect_token.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
interactions:
- request:
body: '{"token": "ntn_..."}'
headers:
accept:
- '*/*'
accept-encoding:
- gzip, deflate
authorization:
- Basic "Base64Encoded($client_id:$client_secret)"
connection:
- keep-alive
content-length:
- '63'
content-type:
- application/json
host:
- api.notion.com
notion-version:
- '2022-06-28'
method: POST
uri: https://api.notion.com/v1/oauth/introspect
response:
content: '{"active":true,"scope":"read_content insert_content update_content read_user_with_email
read_user_without_email","iat":1742416470043,"request_id":"57f9e373-a28b-4b8f-b2dc-c0d687f6f743"}'
headers: {}
http_version: HTTP/1.1
status_code: 200
version: 1
28 changes: 28 additions & 0 deletions tests/cassettes/test_revoke_token.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
interactions:
- request:
body: '{"token": "ntn_..."}'
headers:
accept:
- '*/*'
accept-encoding:
- gzip, deflate
authorization:
- Basic "Base64Encoded($client_id:$client_secret)"
connection:
- keep-alive
content-length:
- '63'
content-type:
- application/json
host:
- api.notion.com
notion-version:
- '2022-06-28'
method: POST
uri: https://api.notion.com/v1/oauth/revoke
response:
content: '{"request_id":"a6dcf82b-8a97-48af-b851-8b9b3559ed69"}'
headers: {}
http_version: HTTP/1.1
status_code: 200
version: 1
28 changes: 28 additions & 0 deletions tests/cassettes/test_token.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
interactions:
- request:
body: '{"grant_type": "authorization_code", "code": "...", "redirect_uri": "http://..."}'
headers:
accept:
- '*/*'
accept-encoding:
- gzip, deflate
authorization:
- Basic "Base64Encoded($client_id:$client_secret)"
connection:
- keep-alive
content-length:
- '134'
content-type:
- application/json
host:
- api.notion.com
notion-version:
- '2022-06-28'
method: POST
uri: https://api.notion.com/v1/oauth/token
response:
content: '{"access_token":"...","token_type":"...","bot_id":"...","workspace_name":"...","workspace_icon":"...","workspace_id":"...","owner":"...","duplicated_template_id":"...","request_id":"..."}'
headers: {}
http_version: HTTP/1.1
status_code: 200
version: 1
Loading