DEV Community

Cover image for Getting started with the Notion API JavaScript SDK
Craig Holliday
Craig Holliday

Posted on

Getting started with the Notion API JavaScript SDK

The public beta for the Notion API went live recently and it is going to make Notion 10x more powerful.

That means it is the perfect time to jump on the bandwagon and start building integrations of your own.

In this post let's go over how to get started with the Notion API by using the Notion JavaScript SDK.

Account setup

This is covered better with gifs in the official getting started page so read through that for more detailed instructions.

Here is a short outline of setting up your account and first integration:

  1. Create a Notion account (If you don't already have one)
  2. Create a workspace or log into one as an Admin
  3. Create a new integration. Save the Internal Integration Token because we will be using that later.
  4. Share a database with your integration. You have to share databases with the integration for security purposes. You can have tons of databases on a single Notion account so it wouldn't be the best if an integration received access to everything connected to one account.
  5. Copy the Database ID. When I set this up I had Notion up in my browser so the URL with the Database ID looked like this https://www.notion.so/${DATABASE_ID}
  6. You are ready to go!

Ways to explore the Notion API

Before going into our example I want to say there are so many cool ways to explore the Notion API.

We will be using the Notion JavaScript SDK but there is also a Postman Workspace which I highly recommend taking a look at.

There are also a couple of integration examples you can check out.

Example Project

Let's hop into some code.

Project Setup

Navigate to where you want to create your project.

Create your example folder

mkdir notion-api-example && cd notion-api-example
Enter fullscreen mode Exit fullscreen mode

Initialize your project with NPM. (Using -y to say yes to all default configuration options)

npm init -y
Enter fullscreen mode Exit fullscreen mode

Install the Notion JavaScript SDK

npm install @notionhq/client
Enter fullscreen mode Exit fullscreen mode

Create an index file for our code.

touch index.js
Enter fullscreen mode Exit fullscreen mode

And we will add a script to our package.json to run our code.

Add "start": "node index.js" and your package.json should look like this:

{
  "name": "notion-api-example",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@notionhq/client": "^0.1.3"
  }
}
Enter fullscreen mode Exit fullscreen mode

Actual code

Now open up index.js and paste the code below. Then replace INTERNAL_INTEGRATION_TOKEN with the token we saved in the setup and DATABASE_ID with the Database ID we saved in the setup.

// Require the Client object from the Notion JS SDK
const { Client } = require('@notionhq/client');

// Create a notion client
const notion = new Client({ auth: 'INTERNAL_INTEGRATION_TOKEN' });

(async () => {
  const databaseId = 'DATABASE_ID';
  // Call `retrieve` on `databases` to retrieve a database object.
  const response = await notion.databases.retrieve({ database_id: databaseId });
  console.log(response);
})();
Enter fullscreen mode Exit fullscreen mode

With this code in place, we can now execute it by running the start script npm run start. If the database id and your integration token are entered correctly you should see a log of the JSON representing the retrieved database.

Refactor and creating a page

Before we wrap up, let's refactor what we currently have and add a function to create a new page in our database.

Change all the code in index.js to the code below.

This is a lot of code so check the added comments for what each piece of the code is doing.

const { Client } = require('@notionhq/client');

const notion = new Client({ auth: 'INTERNAL_INTEGRATION_TOKEN' });

// 1. Refactor `retrieveDatabase` to a function
async function retrieveDatabase(databaseId) {
  const response = await notion.databases.retrieve({ database_id: databaseId });
  console.log(response);
}

// 2. Build a `createPageInDatabase` function
async function createPageInDatabase(databaseId) {
  // The parent object to add to. Here just the ID of the database but this can also be the id of a page.
  const parent = {
    database_id: databaseId,
  };

  // Properties object. This has to match properties in the database.
  const properties = {
    Name: {
      title: [
        {
          text: {
            content: 'My Awesome New Page',
          },
        },
      ],
    },
  };

  // Children object that contains all the awesome Notion block objects.
  const children = [
    {
      object: 'block',
      type: 'heading_2',
      heading_2: {
        text: [
          {
            type: 'text',
            text: {
              content: 'My awesome cool page',
            },
          },
        ],
      },
    },
    {
      object: 'block',
      type: 'paragraph',
      paragraph: {
        text: [
          {
            type: 'text',
            text: {
              content:
                'I created my awesome new page while following along with the KoalaTea Getting started with the Notion API JavaScript SDK blog post. Now I should go read more KoalaTea blog posts. 😄',
              link: {
                url: 'https://koalatea.io/',
              },
            },
          },
        ],
      },
    },
  ];

  // The page object where we put all our other objects together to create a new page.
  const page = {
    parent: parent,
    properties: properties,
    children: children,
  };

  // Finally the request to create a page.
  const response = await notion.pages.create(page);
  console.log(response);
}

(async () => {})(createPageInDatabase('DATABASE_ID'));
Enter fullscreen mode Exit fullscreen mode

Now executing this code (npm run start) we should get a response telling us that a new page was created in our database.

What to do now?

Now that you have gotten started with the Notion API you should look at the API documentation and code samples to see more fleshed-out details of what you can do with the API.

After you have read through the rest of the documentation you should build a project. I suggest you try to build a CMS which is a fantastic project to explore the Notion API.

CMS with the Notion API

Here are some steps to build a Notion CMS.

  • Build a simple Fastify server
  • Start with your database but take a look at user authentication so others could use the CMS.
  • Build simple routes to retrieve data from a database based on certain property filters.
  • Create routes to add pages to the database with just the title and description. (Adding blocks seems more complicated for the first project)
  • Deploy to Heroku or Digital Ocean
  • If you have trouble, 🌟 ping me on Twitter 🌟

Resources

Public beta for the Notion API

Official getting started page

Notion JavaScript SDK

Postman Workspace

API documentation

Build a simple Fastify server

Heroku

Digital Ocean

🌟 ping me on Twitter 🌟

🌟🌟🌟

My brother and I write all the time about React, TypeScript, R, Data Science, you name it on our blog so check it out:

KoalaTea.io

🌟🌟🌟

Top comments (4)

Collapse
 
muuvmuuv profile image
Marvin Heilemann

Where do you get the database id from?

Collapse
 
alihusseindev profile image
Ali Hussein

go to your database page in Notion and get it from the search box.

Collapse
 
singhshemona profile image
Shemona Singh

Great tutorial! Works for me. Would this translate well to a React/TypeScript project?

Collapse
 
andrewbaisden profile image
Andrew Baisden

This is awesome it is on my list to try out later.