노션 API 사용하여 데이터베이스로 이용하기 feat. postman으로 API 조회하기

2022. 11. 15. 17:31프론트엔드

반응형

 

 

첫 리액트 프로젝트는 로컬 스토리지를 데이터베이스를 사용하였는데,

이번 프로젝트는 노션을 데이터베이스를 사용하기 위해 API 연결을 진행했다.

 

기초작업

1. 노션에 데이터베이스 만들기

프로젝트에 사용될 데이터베이스 만들어야한다.

노션에서 새 페이지를 생성하여 /데이터베이스(인라인)을 작성한다.

 

2. Notion API 공식사이트에서 intergration 생성하기

https://www.notion.so/my-integrations

 

Notion (노션) – 모든 팀을 위한 하나의 워크스페이스

Notion은 단순한 워드프로세서가 아닙니다. 내 스타일에 맞게 커스텀해서 사용하세요.

www.notion.so

해당 사이트에서 API intergration을 만들고 프라이빗 토큰을 생성한다.

 

3. intergration 설정

1에서 만든 노션 데이터베이스 페이지로 돌아와 connection에서, 만들어둔 intergration을 연결한다.

그리고 해당 DB 페이지를 전체페이지로 열어 고유 ID 값을 확인한다.

 url 주소 중 ?v=부분은 url의 쿼리값이므로 id 값과는 무관하고,

? 앞 부분이 ID 값.

 

 

 

API 설정

Postman

Postman is an API platform for building and using APIs. Postman simplifies each step of the API lifecycle and streamlines collaboration so you can create better APIs—faster.

https://www.postman.com/

 

Postman API Platform | Sign Up for Free

Postman is an API platform for building and using APIs. Postman simplifies each step of the API lifecycle and streamlines collaboration so you can create better APIs—faster.

www.postman.com

 

포스트맨은 API를 좀 더 쉽고 빠르게 생성하고 사용할 수 있는 플랫폼으로,

여기서는 노션 API가 정상적으로 작동되는지 확인하기 위해 사용한다.

 

 

API 호출 (테스트 목적)

1. 먼저 공식 사이트에서 API 호출법을 확인한다.

https://developers.notion.com/reference/retrieve-a-database

 

Retrieve a database

Retrieves a Database object using the ID specified. Errors Returns a 404 HTTP response if the database doesn't exist, or if the integration doesn't have access to the database. Returns a 400 or 429 HTTP response if the request exceeds the request limits.

developers.notion.com

 

2. 해당 페이지에서 shell 언어로 변경 후 베어러토큰 부분 복사

curl 'https://api.notion.com/v1/databases/668d797c-76fa-4934-9b05-ad288df2d136' \
  -H 'Authorization: Bearer '"$NOTION_API_KEY"'' \
  -H 'Notion-Version: 2022-06-28'

 

3. 포스트맨으로 돌아와 아래의 작업을 진행한다.

import -> raw text -> 위의 복사한 내용 붙여넣기 -> send

new collection 추가 -> add request

get 부분에 api url 복사하여 데이터베이스 ID 변경 후 send

auth 의 bearer token 으로 시크릿 토큰 추가

headers에 'Notion-Version: 2022-06-28' 입력

 

포스트맨에서 body 부분에 들어온 정보 확인

 

 

API 호출 (프로젝트에 직접 사용 목적)

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

https://developers.notion.com/reference/post-database-query

 

Query a database

Gets a list of Pages contained in the database, filtered and ordered according to the filter conditions and sort criteria provided in the request. The response may contain fewer than page_size of results. [Filters](ref:post-database-query-filter) are simil

developers.notion.com

https://api.notion.com/v1/databases/{database_id}/query

 

 

우측의 예시 중 javascript 의 fetch 버젼인지 확인하고 복사해오기

 

 

2. 환경설정 파일 만들기

root 폴더에 .env.local 파일 생성

NOTION_TOKEN=" {/* intergration secrete key */} "
NOTION_DATABASE_ID=" {/* notion database id */} "

 

3. getStaticProps 함수 생성

// getStaticProps 빌드타임에 호출
export async function getStaticProps() {
  const options = {
    method: "POST",
    headers: {
      accept: "application/json",
      "Notion-Version": "2022-02-22",
      "content-type": "application/json",
      Authorization: `Bearer ${TOKEN}`,
    },
    body: JSON.stringify({
      sorts: [
        {
          property: "Name",
          direction: "ascending",
        },
      ],
      page_size: 100,
    }),
  };

  const res = await fetch(
    `https://api.notion.com/v1/databases/${DATABASE_ID}/query`,
    options
  );

  const notionData = await res.json();

  console.log(notionData);

  const projectNames = notionData.results.map(
    (it: Result) => it.properties.Name.title[0].plain_text
  );

  console.log(`(서버사이드)projectNames:${projectNames}`);

  return {
    props: { notionData }, // will be passed to the page component as props
  };
}

* 노션 버전 2022-06-28의 경우 프로퍼티 제공 방식이 변경되어 파싱 오류가 생기므로 2022-02-22 버전으로 변경할 것.

* TOKEN과 DATABASE_ID는 아까 작성한 .env.local 에서 가져옴

* 포스트맨 혹은 console에 뜬 프로퍼티 구조 확인 하여 가져올 내용의 위치 확인할 것

  ➡ 온라인 json formatter를 사용하면 더욱 편리한 확인 가능!

 

 

 

 

 

 

참고:

 

반응형