Notion API, how to retrieve the entries in a database
By Flavio Copes
Learn how to retrieve all entries in a Notion database with the official API by initializing the client and calling notion.databases.query().
To retrieve the entries in a Notion database, initialize the official Notion client with your integration token, then call notion.databases.query() with the database ID. You get back a list of pages, one per entry.
I use this to drive parts of my publishing workflow. I keep posts in a Notion database, and a Node.js script pulls the ones that are ready.
Before the code works, two things must be in place. You need an integration created in your Notion settings, which gives you the secret API key. And you need to connect the database to that integration, from the ••• menu on the database page. If you skip the second step, the API responds with an error saying it can’t find the database, even when the ID is correct. That one cost me some time.
Querying the database
First you need to have a reference to the Notion instance
import { Client } from '@notionhq/client'
//...
const notion = new Client({ auth: process.env.NOTION_API_KEY })
I keep the API key and the database ID in environment variables, so they stay out of the code.
Then you can call notion.databases.query() to retrieve the entries.
This retrieves all entries:
const postsReady = await notion.databases.query({
database_id: process.env.NOTION_DB_ID,
})
The response has a results array. Each item in it is a page object, with the database columns available under its properties field.
How to filter the entries
This retrieves all entries with the checkbox property named “Ready” checked:
const postsReady = await notion.databases.query({
database_id: process.env.NOTION_DB_ID,
filter: {
and: [
{
property: 'Ready',
checkbox: {
equals: true,
},
},
],
},
})
The property value must match the column name in Notion exactly, including the capital letter. A mismatch doesn’t return zero results quietly, the API rejects the request with a validation error, which at least makes the typo easy to spot.
You can do a lot more.
You can add more filtering rules, combining them with or or and logic.
You can sort them by a specific property, ascending or descending.
It’s pretty cool.
One thing to watch: pagination
A single call returns at most 100 entries. If your database is bigger, the response has has_more set to true, and a next_cursor value. Pass that cursor as start_cursor in the next call, and keep going until has_more is false. My first version of the script ignored this, and I wondered for a while why older posts never showed up.
See the official docs of notion.databases.query(): https://developers.notion.com/reference/post-database-query
Related posts about tools: