Skip to content

Sync

NotionAPI

Main class for Notion API wrapper.

Parameters:

Name Type Description Default
access_token str

Notion access token

required
api_version str

Version of the notion API

'2025-09-03'
page_limit int

Maximum number of results per request.

20
Source code in python_notion_api/sync_api/api.py
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
class NotionAPI:
    """Main class for Notion API wrapper.

    Args:
        access_token: Notion access token
        api_version: Version of the notion API
        page_limit: Maximum number of results per request.
    """

    def __init__(
        self,
        access_token: str,
        api_version: str = "2025-09-03",
        page_limit: int = 20,
    ):
        self._access_token = access_token
        self._base_url = "https://api.notion.com/v1/"
        self._api_version = api_version
        self._page_limit = page_limit

        self.default_retry_strategy = Retry(
            total=5,
            backoff_factor=0.1,
            status_forcelist=[429, 500, 502, 503, 504],
            allowed_methods=["HEAD", "GET", "OPTIONS"],
        )
        self.post_retry_strategy = Retry(
            total=5,
            backoff_factor=0.1,
            status_forcelist=[429, 500, 502, 503, 504],
            allowed_methods=["POST"],
        )

        self._http = PoolManager(retries=self.default_retry_strategy)

    def _request(
        self,
        request_type: Literal["get", "post", "patch"],
        endpoint: str = "",
        params: dict[str, Any] = {},
        data: Optional[str] = None,
        cast_cls: Type[NotionObjectBase] = NotionObject,
        retry_strategy: Retry = None,
    ) -> Optional[NotionObject]:
        """Main request handler.

        Should not be called directly, for internal use only.

        Args:
            request_type: Type of the http request to make.
            endpoint: Endpoint of the request. Will be prepened with the
                notion API base url.
            params: Params to pass to the request.
            data: Data to pass to the request.
            cast_cls: A NotionObjectBase class to auto-cast the response of the
                request to.

        Returns:
            Retrieved NotionObject or `None` if the request failed.
        """
        url = self._base_url + endpoint

        headers = {
            "Authorization": f"Bearer {self._access_token}",
            "Notion-Version": f"{self._api_version}",
            "Content-Type": "application/json",
            "Accept": "application/json",
        }

        response = self._http.request(
            request_type,
            url,
            fields=params,
            body=data,
            headers=headers,
            retries=retry_strategy,
        )

        decoded_data = response.data.decode("utf-8")
        if response.status == 200:
            return cast_cls.from_obj(json.loads(decoded_data))
        else:
            logger.error(
                f"Request to {url} failed:"
                f"\n{response.status}\n{decoded_data}"
            )
            return None

    def _post(
        self,
        endpoint: str,
        data: Optional[str] = None,
        cast_cls: Type[NotionObjectBase] = NotionObject,
        retry_strategy: Retry = None,
    ) -> Optional[NotionObject]:
        """Wrapper for post requests.

        Should not be called directly, for internal use only.

        Args:
            endpoint: Endpoint of the request. Will be prepened with the
                notion API base url.
            data: Data to pass to the request.
            cast_cls: A NotionObjectBase class to auto-cast the response of the
                request to.

        Returns:
            Retrieved NotionObject or `None` if the request failed.
        """
        return self._request(
            request_type="post",
            endpoint=endpoint,
            data=data,
            cast_cls=cast_cls,
            retry_strategy=retry_strategy,
        )

    def _get(
        self,
        endpoint: str,
        params: dict[str, str] = {},
        cast_cls: Type[NotionObjectBase] = NotionObject,
    ) -> Optional[NotionObject]:
        """Wrapper for post requests.

        Should not be called directly, for internal use only.

        Args:
            endpoint: Endpoint of the request. Will be prepened with the
                notion API base url.
            params: Params to pass to the request.
            cast_cls: A NotionObjectBase class to auto-cast the response of the
                request to.

        Returns:
            Retrieved NotionObject or `None` if the request failed.
        """
        return self._request(
            request_type="get",
            endpoint=endpoint,
            params=params,
            cast_cls=cast_cls,
        )

    def _patch(
        self,
        endpoint: str,
        params: dict[str, str] = {},
        data: Optional[str] = None,
        cast_cls=NotionObject,
    ) -> Optional[NotionObject]:
        """Wrapper for patch requests.

        Should not be called directly, for internal use only.

        Args:
            endpoint: Endpoint of the request. Will be prepened with the
                notion API base url.
            params: Params to pass to the request.
            data: Data to pass to the request.
            cast_cls: A NotionObjectBase class to auto-cast the response of the
                request to.

        Returns:
            Retrieved NotionObject or `None` if the request failed.
        """
        return self._request(
            request_type="patch",
            endpoint=endpoint,
            params=params,
            data=data,
            cast_cls=cast_cls,
        )

    def _post_iterate(
        self,
        endpoint: str,
        data: dict[str, str] = {},
        retry_strategy: Retry = None,
        page_limit: Optional[int] = None,
    ) -> Generator[PropertyItem, None, None]:
        """Wrapper for post requests where expected return type is Pagination.

        Should not be called directly, for internal use only.

        Args:
            endpoint: Endpoint of the request. Will be prefixed with the
                Notion API base url.
            data: Data to pass to the request.

        Returns:
            Generator yielding PropertyItem objects.
        """
        has_more = True
        cursor = None
        page_size = page_limit or self._page_limit

        while has_more:
            data.update({"start_cursor": cursor, "page_size": page_size})

            if cursor is None:
                data.pop("start_cursor")

            while page_size > 0:
                try:
                    response = self._post(
                        endpoint=endpoint,
                        data=json.dumps(data),
                        retry_strategy=retry_strategy,
                    )

                    assert response is not None

                    for item in response.results:
                        yield item

                    has_more = response.has_more
                    cursor = response.next_cursor

                    break
                except MaxRetryError as e:
                    page_size = floor(page_size / 2)
                    if page_size == 0:
                        raise e
                    data.update({"page_size": page_size})

    def _get_iterate(
        self,
        endpoint: str,
        params: dict[str, str] = {},
        page_limit: Optional[int] = None,
    ) -> Generator[tuple[Any, Any], None, None]:
        """Wrapper for get requests where expected return type is Pagination.

        Should not be called directly, for internal use only.

        Args:
            endpoint: Endpoint of the request. Will be prefixed with the
                notion API base url.
            params: Params to pass to the request.

        Returns:
            Generator yielding PropertyItem objects.
        """
        has_more = True
        cursor = None
        page_size = page_limit or self._page_limit

        while has_more:
            params.update({"start_cursor": cursor, "page_size": page_size})

            if cursor is None:
                params.pop("start_cursor")

            while page_size > 0:
                try:
                    response = self._get(endpoint=endpoint, params=params)

                    assert response is not None

                    if hasattr(response, "property_item"):
                        # Required for rollups
                        property_item = response.property_item
                    else:
                        # property doesn't exist for Blocks
                        property_item = None

                    for item in response.results:
                        yield item, property_item

                    has_more = response.has_more
                    cursor = response.next_cursor

                    break
                except MaxRetryError as e:
                    page_size = floor(page_size / 2)
                    if page_size == 0:
                        raise e
                    params.update({"page_size": page_size})

    def get_database(self, database_id: str) -> NotionDatabase:
        """Gets Notion database.

        Args:
            database_id: Id of the database to fetch.
        Returns:
            A Notion database with the given id.
        """
        return NotionDatabase(self, database_id)

    def get_data_source(self, data_source_id: str) -> NotionDataSource:
        """Wrapper for 'Retrieve a data source' action.

        Args:
            data_source_id: Id of the data source to fetch.
        """
        return NotionDataSource(self, data_source_id)

    def get_page(
        self, page_id: str, page_cast: Type[NotionPage] = NotionPage
    ) -> NotionPage:
        """Gets Notion page.

        Args:
            page_id: Id of the page to fetch.
            page_cast: A subclass of a NotionPage. Allows custom
                property retrieval.

        Returns:
            A Notion page with the given id casted to the provided class.
        """
        return page_cast(self, page_id)

    def get_block(self, block_id) -> NotionBlock:
        """Gets Notion block.

        Args:
            block_id: Id of the block to fetch.

        Returns:
            A Notion block with the given id.
        """
        return NotionBlock(self, block_id)

    def me(self) -> User:
        user = self._get("users/me")

        assert user is not None
        assert isinstance(user, User)

        return user

get_block(block_id)

Gets Notion block.

Parameters:

Name Type Description Default
block_id

Id of the block to fetch.

required

Returns:

Type Description
NotionBlock

A Notion block with the given id.

Source code in python_notion_api/sync_api/api.py
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
def get_block(self, block_id) -> NotionBlock:
    """Gets Notion block.

    Args:
        block_id: Id of the block to fetch.

    Returns:
        A Notion block with the given id.
    """
    return NotionBlock(self, block_id)

get_data_source(data_source_id)

Wrapper for 'Retrieve a data source' action.

Parameters:

Name Type Description Default
data_source_id str

Id of the data source to fetch.

required
Source code in python_notion_api/sync_api/api.py
969
970
971
972
973
974
975
def get_data_source(self, data_source_id: str) -> NotionDataSource:
    """Wrapper for 'Retrieve a data source' action.

    Args:
        data_source_id: Id of the data source to fetch.
    """
    return NotionDataSource(self, data_source_id)

get_database(database_id)

Gets Notion database.

Parameters:

Name Type Description Default
database_id str

Id of the database to fetch.

required

Returns: A Notion database with the given id.

Source code in python_notion_api/sync_api/api.py
959
960
961
962
963
964
965
966
967
def get_database(self, database_id: str) -> NotionDatabase:
    """Gets Notion database.

    Args:
        database_id: Id of the database to fetch.
    Returns:
        A Notion database with the given id.
    """
    return NotionDatabase(self, database_id)

get_page(page_id, page_cast=NotionPage)

Gets Notion page.

Parameters:

Name Type Description Default
page_id str

Id of the page to fetch.

required
page_cast Type[NotionPage]

A subclass of a NotionPage. Allows custom property retrieval.

NotionPage

Returns:

Type Description
NotionPage

A Notion page with the given id casted to the provided class.

Source code in python_notion_api/sync_api/api.py
977
978
979
980
981
982
983
984
985
986
987
988
989
990
def get_page(
    self, page_id: str, page_cast: Type[NotionPage] = NotionPage
) -> NotionPage:
    """Gets Notion page.

    Args:
        page_id: Id of the page to fetch.
        page_cast: A subclass of a NotionPage. Allows custom
            property retrieval.

    Returns:
        A Notion page with the given id casted to the provided class.
    """
    return page_cast(self, page_id)

NotionBlock

Wrapper for a Notion block object.

Parameters:

Name Type Description Default
api NotionAPI

Instance of the NotionAPI.

required
block_id str

Id of the block.

required
Source code in python_notion_api/sync_api/api.py
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
class NotionBlock:
    """Wrapper for a Notion block object.

    Args:
        api: Instance of the NotionAPI.
        block_id: Id of the block.
    """

    def __init__(self, api: NotionAPI, block_id: str):
        self._api = api
        self._block_id = block_id

    @property
    def block_id(self) -> str:
        """Gets block id.

        Returns:
            Id of the block.
        """
        return self._block_id.replace("-", "")

    def get_child_blocks(
        self, page_limit: Optional[int] = None
    ) -> BlockIterator:
        """Gets all child blocks in the block.

        Returns:
            An iterater of all blocks in the block
        """
        generator = self._api._get_iterate(
            endpoint=f"blocks/{self._block_id}/children", page_limit=page_limit
        )
        return BlockIterator(generator)

    def add_child_block(self, content: list[Block]) -> BlockIterator:
        """Adds new blocks as children.

        Args:
            content: Content of the new block.

        Returns:
            An iterator of the newly created blocks.
        """
        data = {
            "children": [
                block.dict(by_alias=True, exclude_unset=True)
                for block in content
            ]
        }
        new_blocks = self._api._patch(
            endpoint=f"blocks/{self.block_id}/children", data=json.dumps(data)
        )

        assert new_blocks is not None

        return BlockIterator(iter(new_blocks.results))

    def set(self, block: Block) -> Block:
        """Updates the content of a Block.

        The entire content is replaced.

        Args:
            block: Block with the new values.

        Returns:
            New block with the updated content.
        """
        data = block.dict(by_alias=True, exclude_unset=True)

        new_block = self._api._patch(
            endpoint=f"blocks/{self.block_id}", data=json.dumps(data)
        )

        assert new_block is not None

        return new_block

block_id property

Gets block id.

Returns:

Type Description
str

Id of the block.

add_child_block(content)

Adds new blocks as children.

Parameters:

Name Type Description Default
content list[Block]

Content of the new block.

required

Returns:

Type Description
BlockIterator

An iterator of the newly created blocks.

Source code in python_notion_api/sync_api/api.py
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
def add_child_block(self, content: list[Block]) -> BlockIterator:
    """Adds new blocks as children.

    Args:
        content: Content of the new block.

    Returns:
        An iterator of the newly created blocks.
    """
    data = {
        "children": [
            block.dict(by_alias=True, exclude_unset=True)
            for block in content
        ]
    }
    new_blocks = self._api._patch(
        endpoint=f"blocks/{self.block_id}/children", data=json.dumps(data)
    )

    assert new_blocks is not None

    return BlockIterator(iter(new_blocks.results))

get_child_blocks(page_limit=None)

Gets all child blocks in the block.

Returns:

Type Description
BlockIterator

An iterater of all blocks in the block

Source code in python_notion_api/sync_api/api.py
398
399
400
401
402
403
404
405
406
407
408
409
def get_child_blocks(
    self, page_limit: Optional[int] = None
) -> BlockIterator:
    """Gets all child blocks in the block.

    Returns:
        An iterater of all blocks in the block
    """
    generator = self._api._get_iterate(
        endpoint=f"blocks/{self._block_id}/children", page_limit=page_limit
    )
    return BlockIterator(generator)

set(block)

Updates the content of a Block.

The entire content is replaced.

Parameters:

Name Type Description Default
block Block

Block with the new values.

required

Returns:

Type Description
Block

New block with the updated content.

Source code in python_notion_api/sync_api/api.py
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
def set(self, block: Block) -> Block:
    """Updates the content of a Block.

    The entire content is replaced.

    Args:
        block: Block with the new values.

    Returns:
        New block with the updated content.
    """
    data = block.dict(by_alias=True, exclude_unset=True)

    new_block = self._api._patch(
        endpoint=f"blocks/{self.block_id}", data=json.dumps(data)
    )

    assert new_block is not None

    return new_block

NotionDataSource

Wrapper for a Notion data source object.

Parameters:

Name Type Description Default
api NotionAPI

Instance of the NotionAPI.

required
data_source_id str

Id of the data source.

required
Source code in python_notion_api/sync_api/api.py
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
class NotionDataSource:
    """Wrapper for a Notion data source object.

    Args:
        api: Instance of the NotionAPI.
        data_source_id: Id of the data source.
    """

    class CreatePageRequest(BaseModel):
        parent: ParentObject
        properties: dict[str, PropertyValue]
        cover: Optional[FileObject]

    def __init__(self, api: NotionAPI, data_source_id: str):
        self._api = api
        self._data_source_id = data_source_id
        self._object = self._api._get(
            endpoint=f"data_sources/{self._data_source_id}",
            cast_cls=DataSource,
        )

        if self._object is None:
            raise Exception(
                f"Error accessing data source {self._data_source_id}"
            )

        self._properties = {
            key: NotionPropertyConfiguration.from_obj(val)
            for key, val in self._object.properties.items()
        }
        self._title = "".join(rt.plain_text for rt in self._object.title)

    @property
    def data_source_id(self) -> str:
        """Gets data source id.

        Returns:
            Id of the data source.
        """
        return self._data_source_id.replace("-", "")

    def query(
        self,
        filters: Optional[FilterItem] = None,
        sorts: Optional[list[Sort]] = None,
        cast_cls=NotionPage,
        page_limit: Optional[int] = None,
    ) -> Generator[NotionPage, None, None]:
        """Queries the data source.

        Retrieves all pages belonging to the data source that satisfy the given filters
        in the order specified by the sorts.

        Args:
            filters: Filters to apply to the query.
            sorts: Sorts to apply to the query.
            cast_cls: A subclass of a NotionPage. Allows custom
            property retrieval.

        Returns:
            Generator of NotionPage objects.
        """
        data: dict[str, Any] = {}

        if filters is not None:
            filters = filters.dict(by_alias=True, exclude_unset=True)
            data["filter"] = filters

        if sorts is not None:
            data["sorts"] = [
                sort.dict(by_alias=True, exclude_unset=True) for sort in sorts
            ]

        for item in self._api._post_iterate(
            endpoint=f"data_sources/{self._data_source_id}/query",
            data=data,
            retry_strategy=self._api.post_retry_strategy,
            page_limit=page_limit,
        ):
            yield cast_cls(
                api=self._api, data_source=self, page_id=item.page_id, obj=item
            )

    @property
    def title(self) -> str:
        """Get the title of the data source."""
        return self._title

    @property
    def properties(self) -> dict[str, NotionPropertyConfiguration]:
        """Gets all property configurations of the data source."""
        return self._properties

    @property
    def relations(self) -> dict[str, RelationPropertyConfiguration]:
        """Gets all property configurations of the data source that are
        relations.
        """
        return {
            key: val
            for key, val in self._properties.items()
            if isinstance(val, RelationPropertyConfiguration)
        }

    def get_property(self, prop_config: Any, prop_value: str) -> Any:
        """Create property for a given property configuration."""

        if isinstance(prop_value, (PropertyItem, PropertyItemIterator)):
            type_ = prop_value.property_type

            if type_ != prop_config.config_type:
                # Have a mismatch between the property type and the
                # given item
                raise TypeError(
                    f"Item {prop_value.__class__} given as "
                    f"the value for property "
                    f"{prop_config.__class__}"
                )
            new_prop = prop_value

        else:
            new_prop = prop_config.create_property(prop_value)

        return new_prop

    def create_page(
        self,
        properties: dict[str, Any] = {},
        cover_url: Optional[str] = None,
    ) -> NotionPage:
        """Creates a new page in the data source and updates the new page with
        the properties.

        Args:
            properties: Dictionary of property names and values. Value types
            will depend on the property type. Can be the raw value
            (e.g. string, float) or an object (e.g. SelectValue,
            NumberPropertyItem)
            cover_url: URL of an image for the page cover.

        Returns:
            A new page.
        """

        validated_properties = {}
        for prop_name, prop_value in properties.items():
            prop = self.properties.get(prop_name, None)
            if prop is None:
                raise ValueError(f"Unknown property: {prop_name}")
            value = generate_value(prop.config_type, prop_value)
            validated_properties[prop_name] = value

        request = NotionDataSource.CreatePageRequest(
            parent=ParentObject(
                type="data_source_id", data_source_id=self.data_source_id
            ),
            properties=validated_properties,
            cover=(
                FileObject.from_url(cover_url)
                if cover_url is not None
                else None
            ),
        )

        data = request.json(by_alias=True, exclude_unset=True)

        new_page = self._api._post(
            "pages", data=data, retry_strategy=self._api.post_retry_strategy
        )

        assert new_page is not None

        return NotionPage(
            api=self._api,
            page_id=new_page.page_id,
            obj=new_page,
            data_source=self,
        )

data_source_id property

Gets data source id.

Returns:

Type Description
str

Id of the data source.

properties property

Gets all property configurations of the data source.

relations property

Gets all property configurations of the data source that are relations.

title property

Get the title of the data source.

create_page(properties={}, cover_url=None)

Creates a new page in the data source and updates the new page with the properties.

Parameters:

Name Type Description Default
properties dict[str, Any]

Dictionary of property names and values. Value types

{}
cover_url Optional[str]

URL of an image for the page cover.

None

Returns:

Type Description
NotionPage

A new page.

Source code in python_notion_api/sync_api/api.py
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
def create_page(
    self,
    properties: dict[str, Any] = {},
    cover_url: Optional[str] = None,
) -> NotionPage:
    """Creates a new page in the data source and updates the new page with
    the properties.

    Args:
        properties: Dictionary of property names and values. Value types
        will depend on the property type. Can be the raw value
        (e.g. string, float) or an object (e.g. SelectValue,
        NumberPropertyItem)
        cover_url: URL of an image for the page cover.

    Returns:
        A new page.
    """

    validated_properties = {}
    for prop_name, prop_value in properties.items():
        prop = self.properties.get(prop_name, None)
        if prop is None:
            raise ValueError(f"Unknown property: {prop_name}")
        value = generate_value(prop.config_type, prop_value)
        validated_properties[prop_name] = value

    request = NotionDataSource.CreatePageRequest(
        parent=ParentObject(
            type="data_source_id", data_source_id=self.data_source_id
        ),
        properties=validated_properties,
        cover=(
            FileObject.from_url(cover_url)
            if cover_url is not None
            else None
        ),
    )

    data = request.json(by_alias=True, exclude_unset=True)

    new_page = self._api._post(
        "pages", data=data, retry_strategy=self._api.post_retry_strategy
    )

    assert new_page is not None

    return NotionPage(
        api=self._api,
        page_id=new_page.page_id,
        obj=new_page,
        data_source=self,
    )

get_property(prop_config, prop_value)

Create property for a given property configuration.

Source code in python_notion_api/sync_api/api.py
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
def get_property(self, prop_config: Any, prop_value: str) -> Any:
    """Create property for a given property configuration."""

    if isinstance(prop_value, (PropertyItem, PropertyItemIterator)):
        type_ = prop_value.property_type

        if type_ != prop_config.config_type:
            # Have a mismatch between the property type and the
            # given item
            raise TypeError(
                f"Item {prop_value.__class__} given as "
                f"the value for property "
                f"{prop_config.__class__}"
            )
        new_prop = prop_value

    else:
        new_prop = prop_config.create_property(prop_value)

    return new_prop

query(filters=None, sorts=None, cast_cls=NotionPage, page_limit=None)

Queries the data source.

Retrieves all pages belonging to the data source that satisfy the given filters in the order specified by the sorts.

Parameters:

Name Type Description Default
filters Optional[FilterItem]

Filters to apply to the query.

None
sorts Optional[list[Sort]]

Sorts to apply to the query.

None
cast_cls

A subclass of a NotionPage. Allows custom

NotionPage

Returns:

Type Description
None

Generator of NotionPage objects.

Source code in python_notion_api/sync_api/api.py
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
def query(
    self,
    filters: Optional[FilterItem] = None,
    sorts: Optional[list[Sort]] = None,
    cast_cls=NotionPage,
    page_limit: Optional[int] = None,
) -> Generator[NotionPage, None, None]:
    """Queries the data source.

    Retrieves all pages belonging to the data source that satisfy the given filters
    in the order specified by the sorts.

    Args:
        filters: Filters to apply to the query.
        sorts: Sorts to apply to the query.
        cast_cls: A subclass of a NotionPage. Allows custom
        property retrieval.

    Returns:
        Generator of NotionPage objects.
    """
    data: dict[str, Any] = {}

    if filters is not None:
        filters = filters.dict(by_alias=True, exclude_unset=True)
        data["filter"] = filters

    if sorts is not None:
        data["sorts"] = [
            sort.dict(by_alias=True, exclude_unset=True) for sort in sorts
        ]

    for item in self._api._post_iterate(
        endpoint=f"data_sources/{self._data_source_id}/query",
        data=data,
        retry_strategy=self._api.post_retry_strategy,
        page_limit=page_limit,
    ):
        yield cast_cls(
            api=self._api, data_source=self, page_id=item.page_id, obj=item
        )

NotionDatabase

Wrapper for a Notion database object.

Parameters:

Name Type Description Default
api NotionAPI

Instance of the NotionAPI.

required
database_id str

Id of the database.

required
Source code in python_notion_api/sync_api/api.py
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
class NotionDatabase:
    """Wrapper for a Notion database object.

    Args:
        api: Instance of the NotionAPI.
        database_id: Id of the database.
    """

    def __init__(self, api: NotionAPI, database_id: str):
        self._api = api
        self._database_id = database_id
        self._object: Optional[Database] = self._api._get(
            endpoint=f"databases/{self._database_id}", cast_cls=Database
        )

        if self._object is None:
            raise Exception(f"Error accessing database {self._database_id}")

        self._data_sources = [
            DataSourceObject(**val) for val in self._object.data_sources
        ]
        self._title = "".join(rt.plain_text for rt in self._object.title)

    @property
    def database_id(self) -> str:
        """Gets database id.

        Returns:
            Id of the database.
        """
        return self._database_id.replace("-", "")

    @property
    def title(self) -> str:
        """Gets title of the database."""
        return self._title

    @property
    def data_sources(self) -> list[DataSourceObject]:
        """Gets all data sources of the database."""
        return self._data_sources

data_sources property

Gets all data sources of the database.

database_id property

Gets database id.

Returns:

Type Description
str

Id of the database.

title property

Gets title of the database.

NotionPage

Wrapper for a notion page object.

Parameters:

Name Type Description Default
api NotionAPI

Instance of the NotionAPI.

required
page_id str

Id of the page.

required
Source code in python_notion_api/sync_api/api.py
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 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
208
209
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
281
282
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
class NotionPage:
    """Wrapper for a notion page object.

    Args:
        api: Instance of the NotionAPI.
        page_id: Id of the page.
    """

    class PatchRequest(BaseModel):
        properties: dict[str, PropertyValue]

    class AddBlocksRequest(BaseModel):
        children: list[Block]

    # Map from property names to function names.
    # For use in subclasses
    special_properties: dict[str, str] = {}

    def __init__(
        self,
        api: NotionAPI,
        page_id: str,
        obj: Optional[Page] = None,
        data_source: Optional[NotionDataSource] = None,
    ):
        self._api = api
        self._page_id = page_id
        self._object = obj
        self.data_source = data_source

        if self._object is None:
            self.reload()

        self._alive: Optional[bool] = None

        if self._object is None:
            raise ValueError(f"Page {page_id} could not be found")

        if data_source is None:
            parent_id = self.parent.data_source_id
            if parent_id is not None:
                self.data_source = self._api.get_data_source(parent_id)

    def __getattr__(self, attr_key: str):
        return getattr(self._object, attr_key)

    @property
    def object(self) -> Page:
        if self._object is None:
            self.reload()

        assert self._object is not None

        return self._object

    @property
    def page_id(self) -> str:
        """Gets the page id.

        Returns:
            Id of the page.
        """
        return self._page_id.replace("-", "")

    @property
    def alive(self) -> bool:
        """Get the current archive status of the page.
        Returns:
            `True` if the page is not archived, `False` otherwise.
        """
        if self._alive is None:
            self._alive = not self.object.archived

        return self._alive

    @alive.setter
    def alive(self, val: bool):
        archive_status = not val
        self._archive(archive_status)
        self._alive = val

    def _get_prop_name(self, prop_key: str) -> Optional[str]:
        """Gets property name from property key.

        Args:
            prop_key: Either a property name or property id.

        Returns:
            Property name or `None` if key is invalid.
        """
        _properties = self.object.properties
        prop_name = next(
            (
                key
                for key in _properties
                if key == prop_key or _properties[key]["id"] == prop_key
            ),
            None,
        )

        return prop_name

    def add_blocks(self, blocks: list[Block]) -> BlockIterator:
        """Adds new blocks to an existing page.

        Args:
            blocks: list of Blocks to add

        Returns:
            Iterator of blocks is returned.
        """
        request = NotionPage.AddBlocksRequest(children=blocks)

        data = request.json(
            by_alias=True, exclude_unset=True, exclude_none=True
        )

        new_blocks = self._api._patch(
            endpoint=f"blocks/{self.page_id}/children", data=data
        )

        assert new_blocks is not None

        return BlockIterator(iter(new_blocks.results))

    def get_blocks(self, page_limit: Optional[int] = None) -> BlockIterator:
        """Gets all blocks in the page.

        Args:
            page_limit: Limit the number of blocks to return. If `None`, will
                return all blocks.

        Returns:
            Iterator of the page blocks.
        """

        generator = self._api._get_iterate(
            endpoint=f"blocks/{self._page_id}/children", page_limit=page_limit
        )
        return BlockIterator(generator)

    def get(
        self,
        prop_key: str,
        cache: bool = True,
        safety_off: bool = False,
        page_limit: Optional[int] = None,
    ) -> Union[PropertyValue, PropertyItemIterator, None]:
        """Gets a single page property.

        First checks if the property is 'special', if so, will call the special
        function to get that property value.
        If not, gets the property through the api.

        Args:
            prop_key: Name or id of the property to retrieve.
            cache: If `True` and the property has been retrieved before, will return a cached value.
                Use `False` to force a new API call.
            safety_off: If `True` will use cached values of rollups and
                formulas.
        """
        if prop_key in self.special_properties:
            # For subclasses of NotionPage
            # Any special properties should have an associated function
            # in the subclass, and a mapping from the property name
            # to the function name in self.special_properties
            # Those functions must return PropertyItemIterator or PropertyItem
            attr = getattr(self, self.special_properties[prop_key])()
            assert isinstance(attr, PropertyValue)
            return attr
        else:
            return self._direct_get(
                prop_key=prop_key,
                cache=cache,
                safety_off=safety_off,
                page_limit=page_limit,
            )

    def _direct_get(
        self,
        prop_key: str,
        cache: bool = True,
        safety_off: bool = False,
        page_limit: Optional[int] = None,
    ) -> Union[PropertyValue, PropertyItemIterator, None]:
        """Wrapper for 'Retrieve a page property item' action.

        Will return whatever is retrieved from the API, no special cases.

        Args:
            prop_key: Name or id of the property to retrieve.
            cache: If `True` and the property has been retrieved before, will return a cached value.
                Use `False` to force a new API call.
            safety_off: If `True` will use cached values of rollups and
                formulas
        """
        prop_name = self._get_prop_name(prop_key)

        if prop_name is None:
            raise ValueError(f"Invalid property  name {prop_name}")

        prop = self.object.properties[prop_name]

        obj = PropertyItem.from_obj(prop)

        prop_id = obj.property_id
        prop_type = obj.property_type

        # We need to always query the API for formulas and rollups as
        # otherwise we might get incorrect values.
        if safety_off is False and prop_type in ("formula", "rollup"):
            cache = False

        if cache and not obj.has_more:
            return PropertyValue.from_property_item(obj)

        ret = self._api._get(
            endpoint=f"pages/{self._page_id}/properties/{prop_id}",
            params={"page_size": page_limit or self._api._page_limit},
        )

        if isinstance(ret, Pagination):
            generator = self._api._get_iterate(
                endpoint=f"pages/{self._page_id}/properties/{prop_id}",
                page_limit=page_limit,
            )
            return create_property_iterator(generator, obj)

        elif isinstance(ret, PropertyItem):
            return PropertyValue.from_property_item(ret)
        else:
            return None

    def _archive(self, archive_status: bool = True) -> None:
        """Wrapper for 'Archive page' action.
        If archive_status is True,
        or 'Restore page' action if archive_status is False.

        Args:
            archive_status: `True` to archive the page, `False` to restore it.
        """
        self._api._patch(
            endpoint=f"pages/{self._page_id}",
            data=json.dumps({"archived": archive_status}),
        )

    def set(self, prop_key: str, value: Any) -> None:
        """Wrapper for 'Update page' action.

        Args:
            prop_key: Name or id of the property to update
            value: A new value of the property
        """

        prop_name = self._get_prop_name(prop_key=prop_key)

        if prop_name is None:
            raise ValueError(f"Unknown property '{prop_name}'")

        prop_type = self.object.properties[prop_name]["type"]

        value = generate_value(prop_type, value)
        request = NotionPage.PatchRequest(properties={prop_name: value})

        data = request.json(by_alias=True, exclude_unset=True)

        self._api._patch(endpoint=f"pages/{self._page_id}", data=data)

    def update(self, properties: dict[str, Any]) -> None:
        """Update page with a dictionary of new values.

        Args:
            properties: A dictionary mapping property keys to new
                values.
        """
        values = {}
        for prop_key, value in properties.items():
            prop_name = self._get_prop_name(prop_key=prop_key)

            if prop_name is None:
                raise ValueError(f"Unknown property '{prop_name}'")

            prop_type = self.object.properties[prop_name]["type"]

            value = generate_value(prop_type, value)
            values[prop_name] = value

        request = NotionPage.PatchRequest(properties=values)

        data = request.json(by_alias=True, exclude_unset=True)

        self._api._patch(endpoint=f"pages/{self._page_id}", data=data)

    def reload(self):
        """Reloads page from Notion."""
        self._object = self._api._get(endpoint=f"pages/{self._page_id}")

    @property
    def properties(self) -> dict[str, PropertyValue]:
        """Returns all properties of the page."""
        return {
            prop_name: self.get(prop_name)
            for prop_name in self.object.properties
        }

    def to_dict(
        self,
        include_rels: bool = True,
        rels_only=False,
        properties: Optional[Union[str, list]] = None,
    ) -> dict[str, Union[str, list]]:
        """Returns all properties of the page as a dict of builtin type values.

        Args:
            include_rels: Include relations.
            rels_only: Return relations only.
            properties: List of properties to return. If `None`, will
                get values for all properties.
        """
        if properties is None:
            properties = self.object.properties
        vals = {}
        for prop_name in properties:
            prop = self.get(prop_name)
            if prop is None:
                continue
            if prop.property_type == "relation":
                if include_rels:
                    vals[prop_name] = prop.value
            else:
                if not rels_only:
                    vals[prop_name] = prop.value
        return vals

alive property writable

Get the current archive status of the page. Returns: True if the page is not archived, False otherwise.

page_id property

Gets the page id.

Returns:

Type Description
str

Id of the page.

properties property

Returns all properties of the page.

add_blocks(blocks)

Adds new blocks to an existing page.

Parameters:

Name Type Description Default
blocks list[Block]

list of Blocks to add

required

Returns:

Type Description
BlockIterator

Iterator of blocks is returned.

Source code in python_notion_api/sync_api/api.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def add_blocks(self, blocks: list[Block]) -> BlockIterator:
    """Adds new blocks to an existing page.

    Args:
        blocks: list of Blocks to add

    Returns:
        Iterator of blocks is returned.
    """
    request = NotionPage.AddBlocksRequest(children=blocks)

    data = request.json(
        by_alias=True, exclude_unset=True, exclude_none=True
    )

    new_blocks = self._api._patch(
        endpoint=f"blocks/{self.page_id}/children", data=data
    )

    assert new_blocks is not None

    return BlockIterator(iter(new_blocks.results))

get(prop_key, cache=True, safety_off=False, page_limit=None)

Gets a single page property.

First checks if the property is 'special', if so, will call the special function to get that property value. If not, gets the property through the api.

Parameters:

Name Type Description Default
prop_key str

Name or id of the property to retrieve.

required
cache bool

If True and the property has been retrieved before, will return a cached value. Use False to force a new API call.

True
safety_off bool

If True will use cached values of rollups and formulas.

False
Source code in python_notion_api/sync_api/api.py
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
208
209
210
211
212
213
214
215
216
217
218
def get(
    self,
    prop_key: str,
    cache: bool = True,
    safety_off: bool = False,
    page_limit: Optional[int] = None,
) -> Union[PropertyValue, PropertyItemIterator, None]:
    """Gets a single page property.

    First checks if the property is 'special', if so, will call the special
    function to get that property value.
    If not, gets the property through the api.

    Args:
        prop_key: Name or id of the property to retrieve.
        cache: If `True` and the property has been retrieved before, will return a cached value.
            Use `False` to force a new API call.
        safety_off: If `True` will use cached values of rollups and
            formulas.
    """
    if prop_key in self.special_properties:
        # For subclasses of NotionPage
        # Any special properties should have an associated function
        # in the subclass, and a mapping from the property name
        # to the function name in self.special_properties
        # Those functions must return PropertyItemIterator or PropertyItem
        attr = getattr(self, self.special_properties[prop_key])()
        assert isinstance(attr, PropertyValue)
        return attr
    else:
        return self._direct_get(
            prop_key=prop_key,
            cache=cache,
            safety_off=safety_off,
            page_limit=page_limit,
        )

get_blocks(page_limit=None)

Gets all blocks in the page.

Parameters:

Name Type Description Default
page_limit Optional[int]

Limit the number of blocks to return. If None, will return all blocks.

None

Returns:

Type Description
BlockIterator

Iterator of the page blocks.

Source code in python_notion_api/sync_api/api.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def get_blocks(self, page_limit: Optional[int] = None) -> BlockIterator:
    """Gets all blocks in the page.

    Args:
        page_limit: Limit the number of blocks to return. If `None`, will
            return all blocks.

    Returns:
        Iterator of the page blocks.
    """

    generator = self._api._get_iterate(
        endpoint=f"blocks/{self._page_id}/children", page_limit=page_limit
    )
    return BlockIterator(generator)

reload()

Reloads page from Notion.

Source code in python_notion_api/sync_api/api.py
335
336
337
def reload(self):
    """Reloads page from Notion."""
    self._object = self._api._get(endpoint=f"pages/{self._page_id}")

set(prop_key, value)

Wrapper for 'Update page' action.

Parameters:

Name Type Description Default
prop_key str

Name or id of the property to update

required
value Any

A new value of the property

required
Source code in python_notion_api/sync_api/api.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
def set(self, prop_key: str, value: Any) -> None:
    """Wrapper for 'Update page' action.

    Args:
        prop_key: Name or id of the property to update
        value: A new value of the property
    """

    prop_name = self._get_prop_name(prop_key=prop_key)

    if prop_name is None:
        raise ValueError(f"Unknown property '{prop_name}'")

    prop_type = self.object.properties[prop_name]["type"]

    value = generate_value(prop_type, value)
    request = NotionPage.PatchRequest(properties={prop_name: value})

    data = request.json(by_alias=True, exclude_unset=True)

    self._api._patch(endpoint=f"pages/{self._page_id}", data=data)

to_dict(include_rels=True, rels_only=False, properties=None)

Returns all properties of the page as a dict of builtin type values.

Parameters:

Name Type Description Default
include_rels bool

Include relations.

True
rels_only

Return relations only.

False
properties Optional[Union[str, list]]

List of properties to return. If None, will get values for all properties.

None
Source code in python_notion_api/sync_api/api.py
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
def to_dict(
    self,
    include_rels: bool = True,
    rels_only=False,
    properties: Optional[Union[str, list]] = None,
) -> dict[str, Union[str, list]]:
    """Returns all properties of the page as a dict of builtin type values.

    Args:
        include_rels: Include relations.
        rels_only: Return relations only.
        properties: List of properties to return. If `None`, will
            get values for all properties.
    """
    if properties is None:
        properties = self.object.properties
    vals = {}
    for prop_name in properties:
        prop = self.get(prop_name)
        if prop is None:
            continue
        if prop.property_type == "relation":
            if include_rels:
                vals[prop_name] = prop.value
        else:
            if not rels_only:
                vals[prop_name] = prop.value
    return vals

update(properties)

Update page with a dictionary of new values.

Parameters:

Name Type Description Default
properties dict[str, Any]

A dictionary mapping property keys to new values.

required
Source code in python_notion_api/sync_api/api.py
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
def update(self, properties: dict[str, Any]) -> None:
    """Update page with a dictionary of new values.

    Args:
        properties: A dictionary mapping property keys to new
            values.
    """
    values = {}
    for prop_key, value in properties.items():
        prop_name = self._get_prop_name(prop_key=prop_key)

        if prop_name is None:
            raise ValueError(f"Unknown property '{prop_name}'")

        prop_type = self.object.properties[prop_name]["type"]

        value = generate_value(prop_type, value)
        values[prop_name] = value

    request = NotionPage.PatchRequest(properties=values)

    data = request.json(by_alias=True, exclude_unset=True)

    self._api._patch(endpoint=f"pages/{self._page_id}", data=data)