2023.05
How to Use the Notion API with Node.js | My Coding Story #1
What is "My Coding Story"?
Hey there! Before we dive into the topic, I’d like to welcome you to My Coding Story. As the name suggests, this is a collection of programming stories that I’ve either experienced firsthand or just witnessed. In every chapter of My Coding Story, you’ll be treated to a short story about a teenager waiting at an endless train station... oops, my bad... I mean a teenager with their imaginative stories about programming.
Introduction
click click clack clack clack click, the sound of Anggara's mouse and keyboard echoed through the room.
"Woah... this template looks really cool," he muttered. Janice Studies' Notion template was displayed on his classic square monitor. Apparently, he was looking for a Notion template to help boost his productivity.
click click click, he explored the template, "Very nice. Just needs a little tweaking, and it'll be perfect for me." click he duplicated the template into his own workspace.
Notion is a note-taking and productivity application that allows you to manage projects, organize notes, work collaboratively, and much more. On top of that, Notion is fully customizable, letting you optimize it as a powerful tool for your work.
"Yay, I've successfully duplicated the template. Next up is the customization phase," he said with sparkling eyes—he was genuinely thrilled about the next step. However, his eyes lit up even more after spotting a motivational quote inside the template. It wasn't just because of the quote itself, but something else that sparked his excitement.
"Tomorrow, this quote won't change unless I change it manually. What if this quote could update automatically every hour? Haha, that’s definitely worth a shot," it turned out he wanted to make the quote change automatically at specific time intervals.
He turned his head toward you and said, "Hey you... since when have you been standing there? Umm... you must have seen everything, right? Would you like to help me bring my idea to life?" After saying that, he went silent. You went silent. Suddenly, the atmosphere became dead quiet and awkward. He tilted his head, looking at you with a blank, curious face. But shortly after, he straightened up, put on a wide grin, and said, "Alright, silence means yes! Haha, let's get started."
Prerequisites
Before we move forward, there are a few things you need to master first:
- A Notion account.
- A Replit account.
- An UptimeRobot account.
- JavaScript programming language.
If you’ve checked all those boxes, let's roll!
Step 1: Create an Integration
A Notion integration allows you to connect information within Notion to other software. To create one, just follow these steps:
- Visit https://www.notion.com/my-integrations in your browser.
- Click the
+ New integrationbutton. - Give your integration a name.
- Click
Submit. - Click on Capabilities, then choose your integration's capabilities. Here, I checked
update contentto match Anggara's goal. Once done, clicksave changes.
Step 2: Give the Integration Access to the Database
After creating the integration, you need to grant it access to your database. To keep your information secure, integrations don't have access to any pages or databases in your workspace by default. You must share specific pages with the integration for the API to access them. Here are the steps to give your integration access to your database:
- Open the database page in your workspace (Check out the Help Center to learn more about databases in Notion).
- Click the
•••button in the top right corner of the page. - Scroll down to the bottom of the pop-up and click
Add connections. - Search for and select your integration in the
Search for connections...menu.
Your integration now has permission to edit the database.
Step 3: Save the Database ID
You need a database ID to edit your database using your Notion integration.
To get the database ID, copy your Notion database URL. If you're using an inline database, make sure you're viewing the database as a full page. If you're using the Notion desktop app, click Share and select Copy link to find the database URL.
The database ID is the string in the database URL that sits between the slash after your workspace name (if you named it) and the question mark. The ID is 32 characters long and contains both numbers and letters.
| source: https://files.readme.io/62e5027-notion_database_id.png |
Step 4: Manifesting the Idea into a Script
Now it's time to manifest Anggara's idea. Here, I'm going to use https://animechan.vercel.app for the API. Below is the code resulting from my manifestation of Anggara's idea.
const { Client } = require('@notionhq/client')
const notion = new Client({ auth: process.env.NOTION_API_KEY })
;(async () => {
setInterval(async () => {
const quoteResponse = await fetch('https://animechan.vercel.app/api/random')
const quoteJsonData = await quoteResponse.json()
const blockId = process.env.NOTION_QUOTE_BLOCK_ID
const response = await notion.blocks.update({
block_id: blockId,
callout: {
rich_text: [
{
text: {
content: `"${quoteJsonData.quote}" - `,
},
},
{
text: {
content: `${quoteJsonData.character}, ${quoteJsonData.anime}.`,
},
annotations: {
bold: true,
},
},
],
},
})
console.log(quoteJsonData)
}, 3600000)
})()
As you can see, on line 3 there is process.env.NOTION_API_KEY, which is the API key from the integration we created earlier. Then there is process.env.NOTION_QUOTE_BLOCK_ID on line 9, which is the ID of the block we want to tweak (yes, a block ID, not a database ID, because I want to change a specific block, not the entire database). For more details on using the Notion API, you can check out their website at https://developers.notion.com/reference/.
Step 5: Hosting with Replit
Now that the code is ready, let's host it so it can run continuously. We're going to use Replit as our hosting platform. Is it paid, bro? Don't worry... we can work around that using UptimeRobot.
Alright, for now, let's implement the code into Replit.
- Click the
+ Create Replbutton. - In the template field, select
Node.js. - Give your Repl a name.
- Click the
+ Create Replbutton. - Copy and paste your code into the
index.jsfile.
Awesome, now the code is inside Replit. If we click the Run button, your code will start running. However, 30 minutes after you close the Replit website, the code will stop running. To bypass this, we’ll use Express.js and UptimeRobot.
- Create a new file in your Repl and name it
server.js. - Copy and paste the following code into that file.
const express = require('express')
const server = express()
server.all('/', (req, res) => {
res.send('Hi, what are you doing here?')
})
function keepAlive() {
server.listen(3000, () => {
console.log('Server is now ready! | ' + Date.now())
})
}
module.exports = keepAlive
- Go back to the
index.jsfile, then add the codeconst keepAlive = require('./server');at the very top line, and callkeepAlive();at the bottom. Your code should look something like this:
const { Client } = require('@notionhq/client')
const keepAlive = require('./server')
const notion = new Client({ auth: process.env.NOTION_API_KEY })
;(async () => {
setInterval(async () => {
const quoteResponse = await fetch('https://animechan.vercel.app/api/random')
const quoteJsonData = await quoteResponse.json()
const blockId = process.env.NOTION_QUOTE_BLOCK_ID
const response = await notion.blocks.update({
block_id: blockId,
callout: {
rich_text: [
{
text: {
content: `"${quoteJsonData.quote}" - `,
},
},
{
text: {
content: `${quoteJsonData.character}, ${quoteJsonData.anime}.`,
},
annotations: {
bold: true,
},
},
],
},
})
console.log(quoteJsonData)
}, 3600000)
})()
keepAlive()
-
Now, log in to https://uptimerobot.com/.
-
Click the
Add New Monitorbutton. -
In the
Monitor Typedropdown, selectHTTP(s). -
In the
Friendly Namefield, give your monitor any name you like. -
In the URL field, paste the domain you get from your Replit project. It’s usually located in the top-right corner of the Replit workspace.
-
Set the
Monitoring Intervalto*every 5 minutes*. -
Click the
Create Monitorbutton.
Alright, we're down to the very last step: running your code. Go back to your Replit project and click the Run button located at the top center. If the string Server is now ready! pops up in the console, it means your script is up and running perfectly! :D
Closing
"Phew... finally done... Let's take a break, play some tic-tac-toe, and sip some hot chocolate..." Anggara said.
The End.