본문 바로가기

개발/효율적으로 도와주는 도구 또는 api

노션API 사용방법 - 3. 데이터베이스 행(row) 생성, 조회 with Python

  목차
  0.  헤더 설정
  1.  데이터베이스 가져오기
  2.  데이터베이스 항목(row) 생성
  3.  데이터베이스 항복(row) 조회

 

 

0. Header

 

token = '발급받은 노션 integration 토큰'

database_id = '사용할 database_id'

headers = {
    "Authorization": "Bearer " + token,
    "Content-Type": "application/json",
    "Notion-Version": "2021-05-13"
}

 

 

1. 데이터베이스 가져오기

 

1 - 1. GET 요청

 

url = f'https://api.notion.com/v1/database/{database_id}'

requests.get(url, header=header)

 

1 - 2. Response

 

{
    # 가져온 객체의 형태
    "object": "database",

    # 가져온 database의 id
    "id": database_id,  
    "cover": null,  
    "icon": null,  
    "created_time": "2023-01-05T04:34:00.000Z",
    "created_by": {
        "object": "user",
        "id": "123123"  
    },
    "last_edited_by": {
        "object": "user",
        "id": "123123" 
    },
    "last_edited_time": "2023-03-02T05:23:00.000Z",

    # 데이터베이스 (table) 의 이름
    "title": [  
        {
            "type": "text",
            "text": {

                # 테이블 이름
                "content": "연락처",
                "link": null
            },
            "annotations": {
                "bold": false,
                "italic": false,
                "strikethrough": false,
                "underline": false,
                "code": false,
                "color": "default"
            },

            # 테이블 이름
            "plain_text": "연락처",
            "href": null
        }
    ],
    "description": [],

    # 해당 테이블이 페이지 인라인으로 박혀있는지에 대한 유무
    "is_inline": true,  

    # 추가된 속성과 속성이름 (data type과 key name) 으로 schema에 해당
    "properties": {
        "법인번호": {  # 속성 이름 (key name)
            "id": "Kvmp",
            "name": "법인번호",  # 속성 이름 (key name)
            "type": "phone_number",  # 속성 (data type) : 휴대폰번호 형태
            "phone_number": {}
        },
        "직급": {  # 속성 이름 (key name)
            "id": "QXGM",
            "name": "직급",  # 속성 이름 (key name)
            "type": "select",  # 속성 (data type) : 단일 선택 형태

            # 속성이 select로 생성한 선택옵션들
            "select": {  
                "options": [
                    {
                        "id": "\\FkN",
                        "name": "대표이사",
                        "color": "orange"
                    },
                    {
                        "id": "H}|N",
                        "name": "이사",
                        "color": "gray"
                    },
                    {
                        "id": "Bn^h",
                        "name": "본부장",
                        "color": "green"
                    },
                    {
                        "id": "[xae",
                        "name": "과장",
                        "color": "default"
                    },
                    {
                        "id": "bSBS",
                        "name": "대리",
                        "color": "purple"
                    },
                    {
                        "id": "SpHB",
                        "name": "사원",
                        "color": "pink"
                    },
                    {
                        "id": "4f07accd-62e9-4eeb-8865-203de455a3aa",
                        "name": "차장",
                        "color": "red"
                    }
                ]
            }
        },
        "이름": {  # 속성 이름 (key name)
            "id": "Y%7Dg%7D",
            "name": "이름",  # 속성 이름 (key name)
            "type": "rich_text",  # 속성 (data type) : 일반 문자 형태
            "rich_text": {}
        },
        "사용자": {  # 속성 이름 (key name)
            "id": "%5CbRl",
            "name": "사용자",  # 속성 이름 (key name)
            "type": "people",  # 속성 (data type) : 노션 사용자 형태
            "people": {}
        },
        "번호": {  # 속성 이름 (key name)
            "id": "%5CrUP",
            "name": "번호",  # 속성 이름 (key name)
            "type": "phone_number",  # 속성 (data type) : 휴대폰번호 형태
            "phone_number": {}
        },
        "팀": {  # 속성 이름 (key name)
            "id": "dboS",
            "name": "팀",  # 속성 이름 (key name)
            "type": "select",  # 속성 (data type) : 단일 선택 형태
            "select": {
                "options": [  # 존재하는 선택 옵션들
                    {
                        "id": "f120a3a2-ee31-4e59-b6d9-5c98ca65dad1",
                        "name": "운영",
                        "color": "default"
                    },
                    {
                        "id": "7ddcec25-ecc3-4251-90c3-f117fda0eef0",
                        "name": "마케팅",
                        "color": "purple"
                    },
                    {
                        "id": "a8cf4cfc-b882-4c35-ac63-9f927bd376f7",
                        "name": "기획",
                        "color": "orange"
                    },
                    {
                        "id": "62d86a68-f814-4544-9222-f9c2f817b759",
                        "name": "디자인",
                        "color": "pink"
                    },
                    {
                        "id": "d1edadb2-8b89-4e54-a705-79693422836a",
                        "name": "개발",
                        "color": "brown"
                    },
                    {
                        "id": "2ae48d67-0de5-412d-abe9-0e98d4a5ed21",
                        "name": "데이터",
                        "color": "green"
                    },
                    {
                        "id": "c8e4d322-326b-48ea-913a-6a8e730ca58e",
                        "name": "MD",
                        "color": "yellow"
                    },
                    {
                        "id": "55af68c5-c2ee-43c5-8ba1-5ab85d163b73",
                        "name": "연구개발",
                        "color": "gray"
                    }
                ]
            }
        },
        "회사이메일": {  # 속성 이름 (key name)
            "id": "l%3B%60%3C",
            "name": "회사이메일",  # 속성 이름 (key name)
            "type": "email",  # 속성 (data type) : 메일주소 형태
            "email": {}
        },     
        "닉네임": {  # 속성 이름 (key name)
            "id": "title",
            "name": "닉네임",  # 속성 이름 (key name)
            "type": "title",  # 속성 (data type) : 제목 (페이지 이름)형태
            "title": {}
        }
    },

    # 데이터베이스가 속하고 있는 노션 페이지
    "parent": {
        "type": "page_id",
        "page_id": "asdasd"
    },

    # url
    "url": "https://www.notion.so/asdasd",

    # 삭제 유무
    "archived": false  
}

 

 

2. 데이터베이스 항목(row) 생성하기

 

2 - 1. 요청할 url

 

url = 'https://api.notion.com/v1/pages'

 

2 - 2. body (row data)

 

{
  'parent': {
    'type': 'database_id',
    
    # row(페이지)가 들어갈 database의 id (필수)
    'database_id': database_id,
  },
  
  # 생성한 속성을 지정하는 부분으로 title 속성은 필수로 넣어주어야하며 다른 형태의 속성은 주석을 참고
  'properties': {
    '닉네임': {  # 속성 이름(keyname) (필수)
      'title': [  # 속성(datatype) (필수)
        {
          'text': {
            'content': '닉네임'  # 넣을 속성의 값 (value)
          }
        }
      ]
    },
    
    # 날짜 형태의 필드의 경우
    '생일': {  # 속성이름 (keyname)
      'date': {  # 속성(datatype): date
        'start': 'yyyy-mm-dd'  # datefield는 start를 기본적으로 표시된다.
        # 기간으로써 종료일이 필요한 경우, 'end'키를 추가하면 된다.
      }
    },
    
    '번호': {
      'phone_number': '010-1111-1111'  # 속성(datatype): 전화번호
    },
    
    '회사이메일': {
	  'email': 'ys@naver.com'  # 속성(datatype): 이메일
    },
    
    #불리언필드의경우
    '교육 완료': {  # 속성이름 (keyname)
      'checkbox': True  # 속성(datatype): 불리언
    },
    
    # 단일 선택 필드의 경우
    '팀': {  # 속성이름 (key name)
      'select': {  # 속성 (datatype): select
        'name': '개발'  # 지정할 옵션들 중의 하나의 옵션 값
      }
    },
    
    # 복수 선택 필드의 경우
    "취미": {  # 속성 이름 (key name)
      "multi_select": [  # 속성(data type): multi select
        {
          "name": "게임"  # 지정할 옵션들 중의 하나의 옵션 값
        },
        {
          "name": "음악감상"  # 지정할 옵션들 중의 하나의 옵션 값
        }
      ]
    }
  },
  
  
  # 아래는 생성할 페이지의 본문(내용)으로 상단 속성들 부분의 밑에 들어간다.
  'children': [
  
    # 페이지에 넣을 첫번째 텍스트볼록
    {
      'object': 'block',
      'type': 'paragraph',
      'paragraph': {
        'rich_text': [
          {
            'type': 'text',
            'text': {
              
              # 본문 텍스트블럭의 값
              'content': '홍길동은 ~~ 를 통하여 지원했고...'
            }
          }
        ]
      }
    },
    
    # 페이지에 넣을 두번째 텍스트블록
    {
      'object': 'block',
      'type': 'paragraph',
      'paragraph': {
        'rich_text': [
          {
            'type': 'text',
            'text': {

               # 본문 텍스트블럭의 값
              'content': '해당 인원은 ~~할 것으로 보이며...'
            }
          }
        ]
      }
    },
    
  ]
}

 

2 - 3. post 요청

앞서 정의한 body 데이터를 json 문자열로 변환(dumps)하여 요청한다.

 

requests.post(
    url=url,
    headers=header,
    data=json.dumps(body)
)

 

 

3. 데이터베이스 항목(row) 리스트 가져오기

 

3 - 1. post 요청

 

url = f'https://api.notion.com/v1/databases/{database_id}/query'
requests.post(url, header=header)

 

3 - 2. Response

 

{
  # 가져온 results의 형태
  "object": "list",

  # 검색 결과
  "results": [
    {
      "object": "page",
      
      # page_id 로 해당 항목을 수정하거나 삭제할 때 필요
      "id": "asdasd123123",
      
      # 생성일시
      "created_time": "2023-01-05T04:34:00.000Z",
      
      # 최근 수정일시
      "last_edited_time": "2023-01-05T04:34:00.000Z",
      "created_by": {
        "object": "user",
        "id": "8b17921d-f836-4292-9b34-90b536119873"
      },
      "last_edited_by": {
        "object": "user",
        "id": "8b17921d-f836-4292-9b34-90b536119873"
      },
      "cover": null,
      "icon": null,
      
      # 속한 데이터베이스의 id
      "parent": {
        "type": "database_id",
        "database_id": "asdasd123123123"
      },
      
      # 삭제유무
      "archived": false,
      
      # 속성 및 속성 값 부분
      "properties": {
        "직급": {  # 속성 이름 (key name)
          "id": "QXGM",
          "type": "select",  # 속성 (data type) : 단일 선택

          # 선택된 옵션의 경우
          "select": {  
            "id": "bSBS",  # 옵션 id
            "name": "대리",  # 옵션 이름
            "color": "purple"
          }
          # 만약 선택된 옵션이 없는 경우는 select가 null 로 온다.
          
        },
        
        "이름": {  # 속성 이름 (key name)
          "id": "Y%7Dg%7D",
          "type": "rich_text",  # 속성 형태 (type) : 문자열
          "rich_text": [
            {
              "type": "text",
              "text": {
                "content": "홍길동",  # value
                "link": null
              },
              "annotations": {
                "bold": false,
                "italic": false,
                "strikethrough": false,
                "underline": false,
                "code": false,
                "color": "default"
              },
              "plain_text": "홍길동",  # value
              "href": null
            }
          ]
        },
        
        "사용자": {  # 속성 이름 (key name)
          "id": "%5CbRl",
          "type": "people",  # 속성 (data type) : 선택된 노션 사용자
          "people": [
            {
              "object": "user",  # 사용자 객체
              "id": "ba04bdbe-dc19-4817-83bf-186db7a27f2f",  # 노션사용자 id
              "name": "홍길동 노션 사용자이름",
              "avatar_url": null,
              "type": "person",
              "person": {
                "email": "asdasd@naver.com"  # 사용자의 계정
              }
            }
          ]
        },
        
        "번호": {  # 속성 이름 (key name)
          "id": "%5CrUP",
          "type": "phone_number",  # 속성 (data type) : 휴대폰 번호 형태
          "phone_number": "010-1234-1234"  # 속성 값
        },
        
        "팀": {  # 속성 이름 (key name)
          "id": "dboS",
          "type": "select",  속성 (data type) : 단일 선택
          
          # 선택된 옵션이 있는 경우
          "select": {
            "id": "62d86a68-f814-4544-9222-f9c2f817b759",  # 선택된 옵션 id
            "name": "디자인",  # 선택된 옵션 이름
            "color": "pink"
          }
        },
        
        "회사이메일": {  # 속성 이름 (key name)
          "id": "l%3B%60%3C",
          "type": "email",  # 속성 (data type) : 이메일 형태
          "email": "asdasd@naver.com"  # 속성 값
        },
        
        "닉네임": {  # 속성 이름 (key name)
          "id": "title",
          "type": "title",  속성 (data type) : 제목 형태 (페이지의 제목)
          "title": [
            {
              "type": "text",
              "text": {
                "content": "길동이",  # 속성 값
                "link": null
              },
              "annotations": {
                "bold": false,
                "italic": false,
                "strikethrough": false,
                "underline": false,
                "code": false,
                "color": "default"
              },
              "plain_text": "길동이",  # 속성 값
              "href": null
            }
          ]
        }
      },
      "url": "https://www.notion.so/aaaaaaaasd"  # 해당 항목의 상세페이지
    },
     

    ...

    
  ],
  "next_cursor": null,
  "has_more": false,
  "type": "page",
  "page": {
    
  }
}