찬찬의 Notion API 정복기 08 - API 집중분석 - search (상)

소찬 (Chan)·2022년 8월 29일
1
post-thumbnail

Reference API URL : Search

이번화 부터는 각 method의 사용방법을 예제로 알아보려고 합니다.
https://developers.notion.com/reference/post-search

notion API는 notion 객체에 점을 찍고 method 이름을 기입하시는 식으로 작성하시면 됩니다.
notion.search 라고 한뒤 괄호() 안에 파라메터 값을 입력해주시면 됩니다.
가령 page 인 정보를 가져오고 싶을 시, 10 건의 페이지만 가져오고 싶을 시 다음과 같이 선언해주시면 됩니다.

pages = notion.search(filter={"property": "object", "value": "page"}, page_size=10)

filter나 page_size는 notion API reference 문서의 BODY PARAMS에 기재되어 있습니다.
필요한 BODY PARAMS 를 입력하여, 저희가 원하는 결과를 search 해오시면 됩니다.

  • query
    When supplied, limits which pages are returned by comparing the query to the page title.
    page의 title이 존재할때 title에 매칭되는 문구가 있는지 확인하고 결과를 가져옵니다.
    예를들면 고객센터라고 검색하고 싶을 때 notion.search(query='고객센터') 로 호출하시면 됩니다.
    - 유의사항
    notion.search(query='고객센터 게시판') 로 입력 시
    실제 검색은 고객센터 키워드로 걸린 페이지와 게시판키워드로 검색된 페이지가 함께 검색됩니다.
    고객센터 게시판이 일치하는 키워드만 검색되지 않는 점 유의 바랍니다.

그러면 '고객센터 게시판'인 title 만 가져오고 싶으면 어떻게 해야되나요?

pages = notion.search(query='고객센터 게시판', filter={"property": "object", "value": "page"})
find_title = '고객센터 게시판'
for page in pages['result']:
   title_name = ['properties']['이름']['title'][0]['plain_text']
   if title_name == find_title:
      target_id = page['id']
   

title을 직접 가져와서 비교하신 뒤 일치하는 페이지 id 를 가져오는 방법이 있겠죠.
API bot이 100개 초과하여 가지고 있는 경우에는, has_more가 True 인지 체크해서 while 검색문으로 has_more가 True 일 때까지 찾아달라고 구문을 추가하실 수 있습니다.

pages = notion.search(query='고객센터 게시판', filter={"property": "object", "value": "page"})

has_more = pages['has_more']
if has_more:
   next_cursor = pages['next_cursor']
find_title = '고객센터 게시판'
for page in pages['result']:
   title_name = ['properties']['이름']['title'][0]['plain_text']
   if title_name == find_title:
      target_id = page['id']
while pages[has_more]:
   pages = notion.search(query='고객센터 게시판', filter={"property": "object", "value": "page"},
                         start_cursor=next_cursor)
   has_more = pages['has_more']
   if has_more:
      next_cursor = pages['next_cursor']
   if title_name == find_title:
      target_id = page['id']

코드를 이렇게 짜시다보면 중복되는 부분이 보이실 겁니다. def 함수로 선언해서 호출해주시면, 좀 더 깔끔하게 코드를 표현하실 수 있습니다.

def page_finder(cursor_id):
   if cursor_id:
      pages = notion.search(filter={"property": "object", "value": "page"},
                                 start_cursor=cursor_id)
      else:
         pages = notion.search(filter={"property": "object", "value": "page"}}
   return pages, pages['next_cursor']

def find_page_id_details(page_name, cursor_id=None):
   pages, cursor_id = page_finder(cursor_id)
   result_page_id = False
     for page in pages['results']:
         page_title = ""
         try:
             page_title = page['properties']['Task']['title'][0]['plain_text']
         except:
             pass
         if page_title == page_name:
             result_page_id = page['id']
             break
  return result_page_id, cursor_id, pages['has_more']
profile
QA Specialist

0개의 댓글