This article demonstrates building a simple interface to connect your Notion database to a custom application using the Notion API and JavaScript. No prior knowledge is required, but familiarity with front-end and back-end development (Node.js and Express) is helpful. The complete code is available on GitHub.
Key Features:
Setup:
The setup is divided into Notion and code setup.
Notion Setup:
Code Setup:
mkdir notion-api-test
).npm init -y
).npm install @notionhq/client dotenv express
..env
file to store your NOTION_API_KEY
and NOTION_API_DATABASE
(your database ID from the Notion URL). Add .env
to your .gitignore
.index.js
and server.js
files (see code examples below). Modify the "scripts"
section of package.json
to start the server with node server
.Pulling Data:
The index.js
file uses the @notionhq/client
SDK to interact with the Notion API. An asynchronous function, getDatabase
, queries the database and returns formatted data.
Express Server:
The server.js
file sets up an Express server to handle API requests. The /users
route uses getDatabase
to fetch data and sends it as JSON. The express.static
middleware serves static files from the public
directory.
Displaying Data:
The front-end (public/index.html
, public/style.css
, public/main.js
) fetches data from /users
, iterates through it, and dynamically displays it on the page.
Adding Data:
A form is added to the front-end to allow users to add new entries. The /submit-form
route in server.js
uses the newEntryToDatabase
function (in index.js
) to create new pages in the Notion database.
Further Improvements:
Consider adding error handling, loading indicators, and converting the application to a single-page application for improved performance.
This revised response provides a more concise and organized overview of the tutorial, while maintaining the key information and images. Remember to replace placeholder values with your actual API key and database ID.
The above is the detailed content of Notion API: Getting Started with Notion's JavaScript SDK. For more information, please follow other related articles on the PHP Chinese website!