Getting started with the Notion API JavaScript SDK
Tags: webdev, javascript, beginners, tutorial
Published: 2021-05-18 17:30:57

---
title: Getting started with the Notion API JavaScript SDK
published: true
description: 
tags: webdev, javascript, beginners, tutorial 
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9xp7qb6d0zid2wtoem88.png
---

The [public beta for the Notion API](https://www.notion.so/Getting-started-with-the-Notion-API-JavaScript-SDK-237536a12289464fa7ebfc3c70284343) 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](https://github.com/makenotion/notion-sdk-js).

## Account setup

This is covered better with gifs in the [official getting started page](https://developers.notion.com/docs/getting-started) 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](https://developers.notion.com/docs/getting-started#create-a-new-integration). Save the `Internal Integration Token` because we will be using that later.
4. [Share a database with your integration](https://developers.notion.com/docs/getting-started#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](https://github.com/makenotion/notion-sdk-js) but there is also a [Postman Workspace](https://www.postman.com/notionhq/workspace/notion-s-public-api-workspace/overview) which I highly recommend taking a look at.

There are also a couple of [integration examples](https://developers.notion.com/page/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

```plain-text
mkdir notion-api-example && cd notion-api-example
```

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

```plain-text
npm init -y
```

Install the [Notion JavaScript SDK](https://github.com/makenotion/notion-sdk-js)

```plain-text
npm install @notionhq/client
```

Create an index file for our code.

```plain-text
touch index.js
```

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:

```json
{
  "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"
  }
}
```

### 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.

```tsx
// 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);
})();
```

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.

```tsx
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'));
```

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](https://developers.notion.com/reference) and [code samples](https://developers.notion.com/page/examples) 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](https://www.fastify.io/)
- Start with your database but take a look at [user authentication](https://developers.notion.com/docs/authorization) 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](https://www.heroku.com/) or [Digital Ocean](https://www.digitalocean.com/)
- If you have trouble, 🌟 [ping me on Twitter](https://twitter.com/TheMrHolliday) 🌟

## Resources

[Public beta for the Notion API](https://www.notion.so/Getting-started-with-the-Notion-API-JavaScript-SDK-237536a12289464fa7ebfc3c70284343)

[Official getting started page](https://developers.notion.com/docs/getting-started)

[Notion JavaScript SDK](https://github.com/makenotion/notion-sdk-js)

[Postman Workspace](https://www.postman.com/notionhq/workspace/notion-s-public-api-workspace/overview)

[API documentation](https://developers.notion.com/reference)

[Build a simple Fastify server](https://www.fastify.io/)

[Heroku](https://www.heroku.com/)

[Digital Ocean](https://www.digitalocean.com/)

🌟 [ping me on Twitter](https://twitter.com/TheMrHolliday) 🌟

🌟🌟🌟

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](http://koalatea.io)

🌟🌟🌟