Notion API

FE.Doolgi·2024년 10월 2일

nextjs

목록 보기
4/4

https://developers.notion.com/docs/getting-started

  1. notion 로그인

  2. https://www.notion.so/profile/integrations 새로운 api 통합 등록 (integration 생성)
    이 때 생성된 프라이빗 API 통합 시크릿 키 복사

  3. 프로젝트에서 yarn add @notionhq/client 실행

  4. 워크스페이스에서 DB table 생성

  5. 원하는 페이지 - 설정에서 들어가서 integration 허용

  6. databaseID - 4번 주소창 https://www.notion.so/A/~
    ~ 표시 부분 (? 제외)

  7. example
    app/api/product/route.ts

'use server';

import { NextResponse } from 'next/server';

import { notion } from '@api/config';
import { databaseId } from '@api/product/config';

import type { NextApiResponse } from 'next';

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

type Data = {
  items?: Array<any>;
  message: string;
};

// post
async function addItem(name: string) {
  try {
    const response = await notion.pages.create({
      parent: { database_id: databaseId },
      properties: {
        title: [
          {
            text: {
              content: name,
            },
          },
        ],
      },
    });
    console.log(response);
  } catch (error) {
    console.error(JSON.stringify(error));
  }
}

export async function POST(req: Request, res: NextApiResponse<Data>) {
  const data = await req.json();

  const { name } = data ?? {};

  if (!name) {
    return NextResponse.json(
      { message: `no name` },
      {
        status: 400,
      },
    );
  }

  try {
    await addItem(String(name));

    return NextResponse.json(
      { message: `success ${name} added` },
      {
        status: 200,
      },
    );
  } catch (error) {
    return NextResponse.json(
      { message: `failed ${name} added` },
      {
        status: 400,
      },
    );
  }
}

// get
async function getItems() {
  try {
    const response = await notion.databases.query({
      database_id: databaseId,
      sorts: [
        {
          property: 'price',
          direction: 'ascending',
        },
      ],
    });

    return response;
  } catch (error) {
    console.error(JSON.stringify(error));
  }
}

export async function GET() {
  try {
    const response = await getItems();

    return NextResponse.json(
      { items: response?.results, message: 'success' },
      {
        status: 200,
      },
    );
  } catch (error) {
    return NextResponse.json(
      { message: 'failed' },
      {
        status: 400,
      },
    );
  }
}
profile
FE 개발 낙서장

0개의 댓글