npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

notion-api-wrapper

v5.0.3

Published

Zero dependency Notion API client.

Downloads

130

Readme

Notion API Wrapper

Zero dependency Notion API client.

Installation

npm install notion-api-wrapper

Or your favorite package manager, in which case you probably know the command.

Getting Started

Querying Database

  1. Create new integration at https://www.notion.so/my-integrations. Write down the secret key, you will need it to authenticate the API requests that this package makes. You can revoke the key at any time in the URL above.

  2. Give the integration permissions to read the database you want to query. You can do this in the database page: Connection To<Integration Name>.

  3. Make the secret key available as an environment variable under the name NOTION_API_KEY. You may also pass it as a parameter to the query functions. You should also store the database ID in an environment variable but this is not mandatory. The examples below assume that you have done so.

    You can find the database ID in the URL of the database page. For instance, in the URL: https://www.notion.so/<workspace>/00000000000000000000000000000000?v=1111111111111111111111111111111, the database ID is 00000000000000000000000000000000.

  4. Query the database.

    const data = await queryDatabaseFull(process.env.NOTION_DATABASE_ID);
    const json = JSON.stringify(data, null, 2);
    console.log(json)

    If you want to pass the secret key as a parameter, you can do so by passing the notionToken option.

    const data = await queryDatabaseFull(process.env.NOTION_DATABASE_ID, {
      notionToken: process.env.NOTION_API_KEY,
    });

Filtering Results

You can also use the FilterBuilder to create filters that will be used in the query.

const filterA: Filter = {
  property: 'Done',
  checkbox: {
    equals: true,
  },
};

const filterB: Filter = {
  property: 'Tags',
  multi_select: {
    contains: 'A',
  },
};

const filterC: Filter = {
  property: 'Tags',
  multi_select: {
    contains: 'B',
  },
};

const myFilter: Filter = new FilterBuilder()
  .addFilter(filterA)
  .addFilter(
    new FilterBuilder().addFilter(filterB).addFilter(filterC).build('OR')
  )
  .build('AND');

const data = await queryDatabaseFull(process.env.NOTION_DATABASE_ID, {
    filter: myFilter,
});

Sorting Results

You can also sort the results by specifying the sort option.

const data = await queryDatabaseFull(process.env.NOTION_DATABASE_ID, {
  sort: {
    direction: 'ascending',
    property: 'Name',
  },
});

Field and Prop Options

There is also options to remove built-in fields and props from the results. Here is a kitchen sink example of that.

const data = await queryDatabaseFull(process.env.NOTION_DATABASE_ID, {
  remove: {
    userIds: true,
    pageTimestamps: true,
    url: true,
    publicUrl: true,
    objectType: true,
    id: true,
    icon: true,
    cover: true,
    archived: true,
    parent: true,
    inTrash: true,
    customProps: ['Description', 'Priority'],
  }
});

You can also remove all props except certain ones by using the keep option.

const data = await queryDatabaseFull(process.env.NOTION_DATABASE_ID, {
  propOptions: {
    keep: ['Name', 'Tags', 'Done'],
  }
});

Notion API responses can be quite verbose, so there is also options to simplify the results.

const data = await queryDatabaseFull(process.env.NOTION_DATABASE_ID, {
  propOptions: {
    simplifyProps: true,
    simpleIcon: true,
  }
});

Advanced Usage

Pagination

There is also a function to query the database in a paginated way. A single query returns at most 100 records.

const { data, nextCursor } = await queryDatabase(process.env.NOTION_DATABASE_ID);
const { data2 } = await queryDatabase(process.env.NOTION_DATABASE_ID, nextCursor);

Database Search

You can easily search a database for a matching page by using the searchFromDatabase function.

const data = await searchFromDatabase(process.env.NOTION_DATABASE_ID, { query: 'kiwi' });

By default the search uses the Name property, but you can specify a different property. By default the search looks for excact matches, but you can modify this behavior too.

const data = await searchFromDatabase(process.env.NOTION_DATABASE_ID, { query: 'vegetab', property: 'Category', matchBy: 'startsWith' })

Database Metadata

You can get database metadata with the getDatabaseColumns function. This supports some of the same options as the query functions.

const columns = await getDatabaseColumns(process.env.NOTION_DATABASE_ID);

Database Iterator

This package also provides a DatabaseIterator class that can be used to iterate over the database in a paginated way.

The option batchSize controls the number of records that will be fetched at once from Notion and yieldSize controls the number of records that will be yielded at a time to the caller. By default both are set to 100.

const db = new DatabaseIterator(process.env.NOTION_DATABASE_ID, { batchSize: 10, yieldSize: 2 });

for await (const chunk of db) {
  const titles = chunk
    .map((c) =>
        c.properties.Name.type === 'title'
          ? c.properties.Name.title[0].plain_text
          : undefined
      )
      .filter((text) => text !== undefined);
}

You can also pass a custom response type to the iterator.


type CustomType = PageObjectResponse & {
  properties: { Name: { title: { plain_text: string }[] } };
};

const dbWithCustomType = new DatabaseIterator<CustomType>(
  process.env.NOTION_DATABASE_ID, { batchSize: 10, yieldSize: 2 }
);

for await (const chunk of dbWithCustomType) {
  const titles = chunk.map((c) => c.properties.Name.title[0].plain_text))
}