찬찬의 Notion API 정복기 19 - API 집중분석 - Query a database

소찬 (Chan)·2022년 11월 29일
0
post-thumbnail

Reference API URL : Query a database

databasepage 묶음입니다.
query 를 통해서 원하는 database 내의 page를 쏙쏙 뽑아낼 수 있습니다.
우선 search를 통해서 database_id를 확인하고, retrieve를 해보겠습니다.

databases = notion.search(filter={"property": "object", "value": "database"})
pprint(databases)

API Bot이 database 접근 권한이 있다면, 결과가 하기와 같이 보여질겁니다. (결과가 없다면 BOT이 database 공유를 1개도 못받은 상황인겁니다.)

{'has_more': False,
 'next_cursor': None,
 'object': 'list',
 'page_or_database': {},
 'results': [{'archived': False,
              ...,
              'id': '021eb424-7a41-47ae-9252-f67d4f6e6b05',

여기서 'results'database 정보가 있습니다. 그 정보 중 id가 바로 database_id 입니다.
마찬가지로 첫번째 databaseid 를 가져오려면 databases['results'][0]['id'] 값을, 두번째 databaseid 를 가져오려면 databases['results'][1]['id'] 값을 가져오시면 되겠죠. 우선 첫번째 databaseid 값을 가져와 보겠습니다.

database_id = databases['results'][0]['id']

이제 database_id 를 알았으니 query 명령을 한번 알아보겠습니다.
명령은 databases.query 로 하면 될테고 parameter를 살펴볼까요?

  • filter (json)
    When supplied, limits which pages are returned based on the filter conditions.
    filter conditions 을 참조하라면서 클릭하면 Filter object 페이지로 넘어갑니다.
    이걸 과연 어떻게 써먹을 수 있을까요. 우선 노션에서 제공해주는 검색 화면을 보고, 그걸 filter 값으로 작성해보겠습니다.

    이렇게 필터가 걸려있다고 치면, 작성은 어떻게 하면 될까요?
    일단 이름, 상태가 무슨 property 인지 알아야 겠죠?
    databases['results'][0]['properties'] 의 값을 살펴보면 그 해답이 있습니다.
{'상태': {'id': '%3EQQn',
        'name': '상태',
        'select': {'options': [{'color': 'green',
                                'id': '6da478a3-5307-4d77-a47a-934a86ddda48',
                                'name': '★★★★★'},
                               {'color': 'brown',
                                'id': '588ecfe9-05b0-40c2-aa32-3f26ee0b5281',
                                'name': '★★★★'},
                                ...
        'type': 'select'},
 '이름': {'id': 'title',
         'name': '이름',
         'title': {},
         'type': 'title'}}

'상태'type'select' 이고, '이름'type'title'입니다.
'이름'이 피자인 값을 포함하는 데이터라는 정보를 추가해 줍니다.

condition = []
condition.append({'property': '이름',
                  'title': {'contains' : '피자'}
                 })

contains 인걸 어떻게 알았냐면, Text filter condition에 자세히 나와있거든요. 값을 포함하는 데이터는 'contains'이므로, 이걸로 json 을 작성했습니다.
그럼 이제 '상태''★★★★'인 가게를 찾는 json 을 작성해보겠습니다.
'select'의 경우 주의할 점은, 'contains' 옵션이 없고, 4가지 조건만 존재합니다. 'equals', 'does_not_equal', 'is_empty', 'is_not_empty'

condition.append({'property': '상태',
                  'select': {'equals' : '★★★★'}
                 })

그리고 이제 'and'를 넣고 호출하면 검색결과가 나옵니다. 또는 으로 검색하고 싶다면 'or'로 호출하시면 됩니다.

notion.databases.query(database_id=database_id, filter={'and': condition})
  • sorts (array)
    When supplied, orders the results based on the provided sort criteria.
    정렬의 경우 오름차순, 내림차순으로 정리할 수 있으며, array 이면 아시다시피 list 형식으로 제공해야 된다는 점 기억하시기 바랍니다.
sort_option = []
sort_option.append({'property': '상태', 'direction': 'ascending'})
sort_option.append({'property': '이름', 'direction': 'descending'})
pprint(notion.databases.query(database_id=database_id, sorts=sort_option, page_size=5))

start_cursorpage_size 는 API 집중분석 - search 편에도 나와있지만 친절한 찬찬은 여기에도 언급해둡니다.

  • start_cursor (string)
    If supplied, this endpoint will return a page of results starting after the cursor provided. If not supplied, this endpoint will return the first page of results.
    search 명령어로 최대 조회해올 수 있는 건이 총 100건입니다. 100건이 초과되는 경우, 응답값에 "has_more" : True"next_cursor": "{고유 id}"를 보냅니다. next_cursor 를 참조해서 start_cursor를 입력시키면, 101번째부터 그 이후의 결과를 search 해오실 수 있습니다.

  • page_size (int32)
    The number of items from the full list desired in the response. Maximum: 100
    한번에 몇 건을 조회에 올지 정하실 수 있습니다. 입력을 따로 안할시에는 최대 100건을 조회해 옵니다.

profile
QA Specialist

0개의 댓글