Set up a Notion API integration, make a database connection, and write a Node.js script that retrieves an ID value for a Notion database from the API.
This is part of a four-part series on showing the potential of Notion as a CMS for complex websites:
Working with a Notion database using the API is pretty straightforward once you get going. But there's some setup to get started.
Begin by going to My Integrations and clicking New Integration.
Set the following information:
If you're following the four-part tutorial, we only need content capabilities. We will not be working with comments or users.
With many APIs, this is enough to have the access you need. But with Notion, you have to make a connection between the integration and the database.
Here's how you create a connection:
To be able to find and work with content in the database, you have to know the ID. This also isn't as simple as it seems like it might be. The ID doesn't come from the ID, but is an internal database ID that has to be retrieved through the API.
We'll write a Node.js script to help us.
Let's install the Node SDK.
npm install @notionhq/client
Your API key is listed on the integration detail page. You can get to each integration from My Integrations.
Store sensitive values like this as environment variables. In the example below, I'm accessing this value via a NOTION_API_KEY
environment variable.
To find the database, we have to use the search
method.
Here is a basic snippet that uses a query passed when running the script. The script loops through all results and print the title and ID for each database returned from the search.
const { Client } = require("@notionhq/client");
// Exit if no query is provided
const query = process.argv[2];
if (!query) {
console.log("Please provide a query");
process.exit(1);
}
const notion = new Client({ auth: process.env.NOTION_API_KEY });
async function getDatabaseId() {
const response = await notion.search({
query,
filter: { property: "object", value: "database" },
});
response.results.map((result) =>
console.log(`${result.title[0].plain_text} -> ${result.id}`)
);
}
getDatabaseId();
Running the script with a query matching the title of your database should produce at least one proper result. Assuming the script is called index.js
, usage would look something like this:
> node index.js "My Database"
[My Database] xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx
[My Other Database] xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx
You can then use the proper ID to access pages, blocks, and more within the database.
Here is a full example similar to the script above, using dotenv to load the secret key.
If you're following the four-part series, move on to Part 3 to write a script that retrieves page and block content from Notion.