notion-objects


Namenotion-objects JSON
Version 0.6.3 PyPI version JSON
download
home_pagehttps://github.com/thrau/notion-objects
SummaryA python library to work with objects retrieved from the notion API
upload_time2024-10-29 19:26:47
maintainerNone
docs_urlNone
authorThomas Rausch
requires_pythonNone
licenseApache License 2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # notion-objects

[![Build Status](https://github.com/thrau/notion-objects/actions/workflows/test.yml/badge.svg)](https://github.com/thrau/notion-objects/actions/workflows/test.yml)
[![PyPI Version](https://badge.fury.io/py/notion-objects.svg)](https://badge.fury.io/py/notion-objects)
[![PyPI License](https://img.shields.io/pypi/l/notion-objects.svg)](https://img.shields.io/pypi/l/notion-objects.svg)
[![Codestyle](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

A Python library that makes it easy to work with notion databases, built on top of [notion-sdk-py](https://github.com/ramnes/notion-sdk-py).
It provides a higher-level API with a data mapper, allowing you to define custom mappings between notion database records and your Python objects.

With notion-objects you can:
* [Transform properties](#defining-models)
* [Query databases](#querying-databases)
* [Update records](#updating-records)
* [Create records](#creating-records)

## User guide

### Defining models

Suppose your database `tasks` has four fields, the title `Task`, a date range `Date`, and a person `Assigned to`, and a status field `Status`.
You want to transform notion database queries into records of:

```json
{
  "task": "my task",
  "date_start": "2022-01-01",
  "date_end": "2022-01-02",
  "assigned_to": "Thomas",
  "status": "In progress"
}
```

First, declare a model that contains all the necessary transformations as descriptors:

```python
from notion_objects import *

class Task(NotionObject):
    task = TitleText("Task")
    assigned_to = Person("Assigned to")
    date_start = DateRangeStart("Date")
    date_end = DateRangeEnd("Date")
    closed_at = Date("Closed at")
    status = Status("Status")
```

Now, when you have queried a database, you can instantiate `Task` objects with the results of the API call:

```python
response = requests.post("https://api.notion.com/v1/databases/{database_id}/query", ...)

for item in response.json()['results']:
    t = Task(item)
    print(t.task)  # access attribute values
    print(t.to_json())  # prints the record in the json format show earlier
```

### Querying Databases

notion-objects adds data-mapping around [notion-sdk-py](https://github.com/ramnes/notion-sdk-py). The `Database` class
is uses a type parameter to map notion objects to the data models you defined.

Here's a code snippet showing how to iterate over all pages in a databases that were updated after 2022-10-08, using
our built-in `Page` model that holds the root page attributes.

```python
from notion_client import Client
from notion_objects import Database, Page

notion = Client(auth=os.environ['NOTION_TOKEN'])

database: Database[Page] = Database(Page, database_id="123456789abcdef1234567890abcdef1", client=notion)

result = database.query({
    "filter": {
        "timestamp": "last_edited_time",
        "last_edited_time": {
            "after": "2022-10-08"
        }
    }
})
for page in result:
    print(page.id, page.created_time, page.last_edited_time)
```

You could also use `DynamicNotionObject` if you're too lazy to create a model for your database. notion-objects will map
the data types in a best-effort way. You can also iterate directly over the database to fetch all records:

```python
from notion_objects import Database, DynamicNotionObject

database = Database(DynamicNotionObject, ...)

for record in database:
    print(record.to_json())  # will print your database record as JSON
```

**NOTE** not all types have yet been implemented. Type mapping is very rudimentary.

### Updating records

You can update database records by simply calling attributes with normal python assignments.
The data mapper will map the types correctly to Notion's internal format.
You can then call `Database.update(...)` to run an update API call.
notion-objects keeps track of all the changes that were made to the object, and only sends the changes.

```python
database: Database[Task] = Database(Task, ...)

task = database.find_by_id("...")
task.status = "Done"
task.closed_at = datetime.utcnow()
database.update(task)
```

**Note** not all properties can be set yet.

### Creating records

Similarly, you can also create new pages.
You can use `NotionObject.new()` on any subclass to create new unmanaged instances of that type.
Then, call `Database.create(...)` to create a new item in the database.

```python
database: Database[Task] = Database(Task, ...)

task = Task.new()
task.task = "My New Task"
task.status = "In progress"
task.assigned_to = "6aa4d3cd-3928-4f61-9072-f74a3ebfc3ca"

task = database.create(task)
print(task.id)  # will print the page ID that was created
```

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/thrau/notion-objects",
    "name": "notion-objects",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": null,
    "author": "Thomas Rausch",
    "author_email": "thomas@thrau.at",
    "download_url": "https://files.pythonhosted.org/packages/66/15/b096b7cd349d8330b485277c5afd1e01a962770921d4e41505702212e956/notion_objects-0.6.3.tar.gz",
    "platform": null,
    "description": "# notion-objects\n\n[![Build Status](https://github.com/thrau/notion-objects/actions/workflows/test.yml/badge.svg)](https://github.com/thrau/notion-objects/actions/workflows/test.yml)\n[![PyPI Version](https://badge.fury.io/py/notion-objects.svg)](https://badge.fury.io/py/notion-objects)\n[![PyPI License](https://img.shields.io/pypi/l/notion-objects.svg)](https://img.shields.io/pypi/l/notion-objects.svg)\n[![Codestyle](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n\nA Python library that makes it easy to work with notion databases, built on top of [notion-sdk-py](https://github.com/ramnes/notion-sdk-py).\nIt provides a higher-level API with a data mapper, allowing you to define custom mappings between notion database records and your Python objects.\n\nWith notion-objects you can:\n* [Transform properties](#defining-models)\n* [Query databases](#querying-databases)\n* [Update records](#updating-records)\n* [Create records](#creating-records)\n\n## User guide\n\n### Defining models\n\nSuppose your database `tasks` has four fields, the title `Task`, a date range `Date`, and a person `Assigned to`, and a status field `Status`.\nYou want to transform notion database queries into records of:\n\n```json\n{\n  \"task\": \"my task\",\n  \"date_start\": \"2022-01-01\",\n  \"date_end\": \"2022-01-02\",\n  \"assigned_to\": \"Thomas\",\n  \"status\": \"In progress\"\n}\n```\n\nFirst, declare a model that contains all the necessary transformations as descriptors:\n\n```python\nfrom notion_objects import *\n\nclass Task(NotionObject):\n    task = TitleText(\"Task\")\n    assigned_to = Person(\"Assigned to\")\n    date_start = DateRangeStart(\"Date\")\n    date_end = DateRangeEnd(\"Date\")\n    closed_at = Date(\"Closed at\")\n    status = Status(\"Status\")\n```\n\nNow, when you have queried a database, you can instantiate `Task` objects with the results of the API call:\n\n```python\nresponse = requests.post(\"https://api.notion.com/v1/databases/{database_id}/query\", ...)\n\nfor item in response.json()['results']:\n    t = Task(item)\n    print(t.task)  # access attribute values\n    print(t.to_json())  # prints the record in the json format show earlier\n```\n\n### Querying Databases\n\nnotion-objects adds data-mapping around [notion-sdk-py](https://github.com/ramnes/notion-sdk-py). The `Database` class\nis uses a type parameter to map notion objects to the data models you defined.\n\nHere's a code snippet showing how to iterate over all pages in a databases that were updated after 2022-10-08, using\nour built-in `Page` model that holds the root page attributes.\n\n```python\nfrom notion_client import Client\nfrom notion_objects import Database, Page\n\nnotion = Client(auth=os.environ['NOTION_TOKEN'])\n\ndatabase: Database[Page] = Database(Page, database_id=\"123456789abcdef1234567890abcdef1\", client=notion)\n\nresult = database.query({\n    \"filter\": {\n        \"timestamp\": \"last_edited_time\",\n        \"last_edited_time\": {\n            \"after\": \"2022-10-08\"\n        }\n    }\n})\nfor page in result:\n    print(page.id, page.created_time, page.last_edited_time)\n```\n\nYou could also use `DynamicNotionObject` if you're too lazy to create a model for your database. notion-objects will map\nthe data types in a best-effort way. You can also iterate directly over the database to fetch all records:\n\n```python\nfrom notion_objects import Database, DynamicNotionObject\n\ndatabase = Database(DynamicNotionObject, ...)\n\nfor record in database:\n    print(record.to_json())  # will print your database record as JSON\n```\n\n**NOTE** not all types have yet been implemented. Type mapping is very rudimentary.\n\n### Updating records\n\nYou can update database records by simply calling attributes with normal python assignments.\nThe data mapper will map the types correctly to Notion's internal format.\nYou can then call `Database.update(...)` to run an update API call.\nnotion-objects keeps track of all the changes that were made to the object, and only sends the changes.\n\n```python\ndatabase: Database[Task] = Database(Task, ...)\n\ntask = database.find_by_id(\"...\")\ntask.status = \"Done\"\ntask.closed_at = datetime.utcnow()\ndatabase.update(task)\n```\n\n**Note** not all properties can be set yet.\n\n### Creating records\n\nSimilarly, you can also create new pages.\nYou can use `NotionObject.new()` on any subclass to create new unmanaged instances of that type.\nThen, call `Database.create(...)` to create a new item in the database.\n\n```python\ndatabase: Database[Task] = Database(Task, ...)\n\ntask = Task.new()\ntask.task = \"My New Task\"\ntask.status = \"In progress\"\ntask.assigned_to = \"6aa4d3cd-3928-4f61-9072-f74a3ebfc3ca\"\n\ntask = database.create(task)\nprint(task.id)  # will print the page ID that was created\n```\n",
    "bugtrack_url": null,
    "license": "Apache License 2.0",
    "summary": "A python library to work with objects retrieved from the notion API",
    "version": "0.6.3",
    "project_urls": {
        "Homepage": "https://github.com/thrau/notion-objects"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "5ab8013039771a584bd934dffa6aabcd36b1e25dc322949ad8dbed798654b995",
                "md5": "122d5d731a374cda78c651f7b7aaf7bc",
                "sha256": "6fb70188a8f9930240018d7ff66dbbac97d443df4dccd662dd918b9893b5f0e1"
            },
            "downloads": -1,
            "filename": "notion_objects-0.6.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "122d5d731a374cda78c651f7b7aaf7bc",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 18431,
            "upload_time": "2024-10-29T19:26:45",
            "upload_time_iso_8601": "2024-10-29T19:26:45.619941Z",
            "url": "https://files.pythonhosted.org/packages/5a/b8/013039771a584bd934dffa6aabcd36b1e25dc322949ad8dbed798654b995/notion_objects-0.6.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6615b096b7cd349d8330b485277c5afd1e01a962770921d4e41505702212e956",
                "md5": "7038e51cfd1f8171738aead6ce9496af",
                "sha256": "ab45072de79e7b53db3c7e914d81c0c0ecdca505d2d4c3d1d95e63ef6855de2c"
            },
            "downloads": -1,
            "filename": "notion_objects-0.6.3.tar.gz",
            "has_sig": false,
            "md5_digest": "7038e51cfd1f8171738aead6ce9496af",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 18626,
            "upload_time": "2024-10-29T19:26:47",
            "upload_time_iso_8601": "2024-10-29T19:26:47.285334Z",
            "url": "https://files.pythonhosted.org/packages/66/15/b096b7cd349d8330b485277c5afd1e01a962770921d4e41505702212e956/notion_objects-0.6.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-10-29 19:26:47",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "thrau",
    "github_project": "notion-objects",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "notion-objects"
}
        
Elapsed time: 1.32461s