Skip to content

Instantly share code, notes, and snippets.

@mariocesar
Last active February 21, 2022 17:56
Show Gist options
  • Save mariocesar/f168cbaf18ec6baac0b944180342a7c0 to your computer and use it in GitHub Desktop.
Save mariocesar/f168cbaf18ec6baac0b944180342a7c0 to your computer and use it in GitHub Desktop.
Notion JS API Use examples

Some common variables for all functions

const NOTION_API_KEY = process.env.NOTION_API_KEY;

const headers = {
  Accept: "application/json",
  "Notion-Version": "2021-08-16",
  "Content-Type": "application/json",
};

type NotionPageProperties = {
  [key: string]: string | boolean | number;
};

type NotionAPIResponse = {
  body: { [key: string]: any };
  status: number;
};

Get Page by ID

async function getPageByID(pageID: string): Promise<NotionAPIResponse> {
  const response = await fetch(`https://api.notion.com/v1/pages/${pageID}`, {
    method: "GET",
    headers: { ...headers, Authorization: `Bearer ${NOTION_API_KEY}` },
  });

  const body = await response.json();

  return { body, status: response.status };
}

Update page properties

async function updatePageByID(
  pageID: string,
  properties: NotionPageProperties
): Promise<NotionAPIResponse> {
  const response = await fetch(`https://api.notion.com/v1/pages/${pageID}`, {
    method: "PATCH",
    headers: { ...headers, Authorization: `Bearer ${NOTION_API_KEY}` },
    body: JSON.stringify({
      properties: properties,
    }),
  });

  const body = await response.json();

  return { body, status: response.status };
}

Create a Page in a Parent/Database Page

async function createPageInParentID(
  parentID: string,
  properties: NotionPageProperties
): Promise<NotionAPIResponse> {
  const response = await fetch("https://api.notion.com/v1/pages", {
    method: "POST",
    headers: { ...headers, Authorization: `Bearer ${NOTION_API_KEY}` },
    body: JSON.stringify({
      parent: { database_id: parentID },
      properties: properties,
    }),
  });

  const body = await response.json();

  return { body, status: response.status };
}

Duplicate Page

async function duplicatePageByID(
  pageID: string,
  properties: NotionPageProperties
): Promise<NotionAPIResponse> {
  const page = await getPageByID(pageID);
  const newPage = await createPageInParentID(page["parent"], {
    ...page.body.properties,
    ...properties,
  });

  return { body: newPage.body, status: newPage.status };
}

Archive(Delete) Page by ID

async function archivePageByID(pageID: string): Promise<NotionAPIResponse> {
  const response = await fetch(`https://api.notion.com/v1/pages/${pageID}`, {
    method: "PATCH",
    headers: { ...headers, Authorization: `Bearer ${NOTION_API_KEY}` },
    body: JSON.stringify({
      properties: { archived: true },
    }),
  });

  const body = await response.json();

  return { body, status: response.status };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment