찬찬의 Notion API 정복기 11 - API 집중분석 - Create a page (상)

소찬 (Chan)·2022년 9월 19일
0
post-thumbnail

Reference API URL : Create a page

Create a page를 하려면 API bot이 권한이 있어야 합니다.
공유 클릭해서 bot을 추가하면 되는데, 궁금한 점이 생겼습니다. 과연 최상단 페이지를 API bot이 만들수 있을까?
짐작하셨겠지만, 최상단에는 bot을 추가하는 개념이 없습니다. User가 추가되는 개념이 있을 뿐이죠.
그래서 최상단 페이지에서 생성하는건 불가능하고, API bot이 공유받은 페이지의 하위 페이지 생성이 가능합니다.
그렇다고 해서 최상단 개념이 Notion API 에 없는 것은 아닙니다. 하기 링크에 workspace 라는 parent에 대한 설명을 참조하시면 됩니다.
https://developers.notion.com/reference/parent-object#workspace-parent
아무튼 parameter에 대해 살펴보도록 할께요.

  • parent (json) required
    A database parent or page parent
    생성할 부모 페이지 id 를 기입하시면 됩니다. 그런데 왠 json, id만 기재하면 되는게 아닌가보네요.
    json 형태는 dictionary {} 에 필요한 키와 키의 값이 있는 형태를 의미합니다.
    바로 하기와 같은 형태로 묶어서 보내주면 됩니다.
    {"database_id": "638746d9-9bd4-4a2f-a015-d38b41e0bd5e"}
    {"page_id": "aca05c96-1fa9-4e7c-b539-24533cb4da37"}
    위와 같이 써야 되는 이유도 API 문서에 기재되어있는데, https://developers.notion.com/reference/page#database-parent 페이지 참조하시면 됩니다.
  • properties (json) required
    Property values of this page. The keys are the names or IDs of the property and the values are property values.
    property는 페이지의 분류, 옵션 값 정보들의 묶음입니다. 형식이 조금이라도 틀리면 생성이 되지 않기 때문에, 제대로 생성하고 싶다면 참고할만한 Notion Page를 만들고, 거기에 원하는 property를 세팅한 다음, 그 페이지의 정보를 retrieve 하여서 property의 구성을 참조하시는게 좋습니다.

하나 예시로 properties 값을 retrieve로 가져왔습니다.

 'parent': {'database_id': '021eb424-7a41-47ae-9252-f67d4f6e6b05',
            'type': 'database_id'},
 'properties': {'상태': {'id': '%3EQQn',
                       'select': {'color': 'brown',
                                  'id': '588ecfe9-05b0-40c2-aa32-3f26ee0b5281',
                                  'name': '★★★★'},
                       'type': 'select'},
                '이름': {'id': 'title',
                       'title': [{'annotations': {'bold': False,
                                                  'code': False,
                                                  'color': 'default',
                                                  'italic': False,
                                                  'strikethrough': False,
                                                  'underline': False},
                                  'href': None,
                                  'plain_text': '네오피자',
                                  'text': {'content': '네오피자', 'link': None},
                                  'type': 'text'}],
                       'type': 'title'}}

이제 properties 값에서 'id'를 제외한 나머지 값들을 살려줍니다.
그런뒤 create 할 부분을 기존 데이터에서 바꿔줍니다.

properties_new = {'상태': {'select': {'color': 'red',
                                     'name': '★★★★★'},
                          'type': 'select'},
                  '이름': {'id': 'title',
                          'title': [{'annotations': {'bold': False,
                                                     'code': False,
                                                     'color': 'default',
                                                     'italic': False,
                                                     'strikethrough': False,
                                                     'underline': False},
                          'href': None,
                          'plain_text': '피자샵',
                          'text': {'content': '피자샵', 'link': None},
                          'type': 'text'}],
                  'type': 'title'}

물론 직접 입력하셔도 되지만, 변수 형태로 'properties' 키 값을 가져와서 필요한 값만 수정하는 형태로 진행하시는 것이 더 좋습니다.

page_sample = notion.pages.retrieve(page_id='1f217cc1-225f-4580-8e22-cd7eb8db3c5e')
properties_new = page_sample['properties']

properties_new['상태']['select']['color'] = 'red'
properties_new['상태']['select']['name'] = '★★★★★'
properties_new['이름']['title'][0]['plain_text'] = '피자샵'
properties_new['이름']['title'][0]['text']['content'] = '피자샵'

그러면 필요한 값만 수정하는 식으로 구현하면, 기존 id가 남아있을텐데 상관없나요?
보통의 경우, 상관없이 생성이 되긴 합니다. 다만 간혹 id 때문에 충돌이 나는 경우가 간혹 있으므로, 되도록이면 고유형태로 보여지는 id는 삭제해주시는 게 좋습니다.

del properties_new['상태']['id']
del properties_new['상태']['select']['id']

이제 위 정보를 바탕으로 pagecreate 해보도록 하겠습니다.

notion.pages.create(parent={'database_id': '021eb424-7a41-47ae-9252-f67d4f6e6b05'},
                    properties=properties_new)

properties 는 예민하기 때문에, 호출 시 조금이라도 오류가 발생하면 그 오류에서 알려주는 사항을 수정해주셔야 합니다.
한가지 오류 예를 들겠습니다.

notion_client.errors.APIResponseError: Select option color doesn't match existing for 588ecfe9-05b0-40c2-aa32-3f26ee0b5281.

위의 오류가 어떤 의미인가요? '★★★★★' 문구를 사전에 노란색('yellow') 옵션으로 설정해 놓았다면, 위와 같이 색깔이 불일치 합니다. 오류가 발생하실 수 있습니다. 이 경우 'color'의 값을 'yellow'로 변경하시면 해결됩니다.

properties_new['상태']['select']['color'] = 'yellow'
profile
QA Specialist

0개의 댓글