轻松使用Notion API——Notion教程

18,919 阅读11分钟

Notion是一款可定制的项目管理软件,可以轻松地在项目和页面上进行协作,在内部或外部分享你的工作,并跟踪队友的情况。

Notion很容易使用,是科技公司和非科技公司的最爱。Notion的一些流行替代品是TrelloJiraAirtable

Notion最近发布了Notion API,它允许开发者在Notion的基础上进行构建。虽然仍处于公开测试阶段,但我们可以使用Notion API来开发和测试我们自己的应用程序。

在本教程中,我们将使用Notion创建一个数据库,连接到Notion API,并创建一个小型Node.js服务器,使用Fastify从Notion工作区提供内容。注意,本教程将只建立应用程序的后端。

要跟上本教程,你需要有JavaScript和Node.js的基本知识。

让我们开始吧!

在Notion上建立你的账户

前往Notion网站注册一个账户。在我们的例子中,我们将设置一个团队账户,然而,你可以选择注册一个个人账户。

Set Up Notion Account

输入你的团队工作区的详细信息。

Create Team Workspace

在最后的入职界面,你可以选择邀请队友或继续不邀请。对于我们的例子,我们将跳过这一步。

注意Notion已经在左边的侧边栏设置了一些工作空间,比如待办事项、路线图、工程维基、文件和会议记录。

Notion Prepared Workspaces

创建页面、日历和数据库

现在,让我们进入有趣的部分!假设我们是一家想象中的科技公司的一部分,该公司开办了一个编码训练营,来自世界各地的学生参加。

我们想根据项目协调人在Notion工作区输入的信息,在学生的仪表盘上提供他们当月应该学习什么课程的信息。我们还想收集新加入项目的学生的姓名和电子邮件,并将这些信息存储在我们将在Notion中创建的邮件列表中。

让我们先在Notion仪表板上创建一个新的页面。Notion中几乎所有的东西都是一个页面,而子页面是嵌套在一个页面中的一个页面。

当你创建一个新的工作区时,首先要创建一个页面。在侧边栏中工作区标题的右边,点击 "+"号来添加一个新的页面。我们将称我们的新工作区为 "Bootcamp"。

创建了Bootcamp页面后,我们来创建一个日历。日历是Notion中的一种视图,与表格、列表、板块、画廊和时间线一样。

Notion中的数据库视图是保持数据结构化和组织化的好方法,确保数据显示在我们使用它的背景下是有意义的。

Database Views Notion

要在Notion中创建一个日历数据库,请添加一个新页面,输入 "Bootcamp",然后从数据库列表中选择日历。Notion会显示一个日历视图,你可以开始输入数据。

通过点击悬停在某一天时显示的**"+**"图标,在日历上选择一个日子。现在,你就可以在那个日期输入数据了。

Add Data Notion Calendar

如果你选择的话,你可以随意为不同的日期添加数据。你也可以在日历上拖动日期,为一个页面创建一个开始和结束日期。

当我们输入数据后,我们的日历将看起来像下面的图片。

Data Entered Calendar

使用Notion来建立一个邮件列表

如前所述,我们想建立一个邮件列表,其中包含了我们Bootcamp中每个学生的电子邮件地址。当一个新的学生从前端应用程序注册时,我们将把他们的名字和电子邮件地址存储在Notion里面。

在左边的侧边栏,通过点击**+添加一个页面创建一个新的工作区。为你的页面添加一个标题;我们将称我们的页面为 "Bootcamp Mailing List"。选择数据库下的表**选项。设置你的表格,在第一列接受一个Name 文本字段,在第二列接受一个Email 字段。

Notion Bootcamp Mailing List

为我们的Notion API设置访问令牌

我们需要设置一个集成,通过Notion API连接你的数据库,然后生成一个访问令牌来访问Notion的API。

要设置你的第一个集成,请前往Notion API文档页面,点击右上角的我的集成按钮。点击**+** 创建新的集成按钮。

Set Up Tokens Integration

给你的集成取个名字。我们将称我们的为 "rc-bootcamp"。然后点击提交。现在,你会看到你的内部集成令牌。

Internal Integration Token Set Up

最后,为了使我们先前创建的数据库可用于我们的集成,前往Bootcamp工作区。点击页面右上角的共享按钮。选择我们刚刚创建的rc-bootcamp集成。

点击**邀请。**我们的集成现在应该可以访问我们的Bootcamp工作区。

对我们之前创建的Bootcamp Mailing List工作区重复这个过程。

Set Up Integration Notion Workspace

设置Notion客户端

现在我们有了工作区、数据库和集成的设置,我们可以开始为我们的学生仪表板应用程序创建后台服务器。

在你的终端,使用命令npm init -y ,创建一个新的Node.js项目,它会在项目的根部自动生成一个package.json 文件。

接下来,我们需要安装Notion API SDK。运行该命令。

npm install @notionhq/client

在你的根目录下创建一个.env 文件。复制我们先前生成的内部集成令牌,并将其分配给你的.env 文件中的一个NOTION_API_TOKEN 变量。

为了在我们的项目中使用.env 文件,我们将需要安装dotenv库。

npm i dotenv

在Notion中获取你的数据库ID

我们需要找到我们的数据库ID来连接到我们所创建的数据库。前往你的工作区,在notion.so/? 之间复制你的URL中的字母数字字符。

Find Database ID Notion

在这个例子中,我们的Bootcamp数据库ID是cab3c272b2f848e5ae0b85fa8dda5a1c 。在Bootcamp Mailing List工作区重复同样的过程。

在你的.env 文件中添加一个名为NOTION_DATABASE_ID 的新变量。用你的Bootcamp数据库ID更新这个变量。添加另一个名为NOTION_MAILING_LIST_ID 的变量,并添加你的Bootcamp Mailing List数据库ID。

现在,你的.env 文件应该包含你的NOTION_DATABASE_IDNOTION_MAILING_LIST_ID 、和NOTION_API_TOKEN

连接到Notion SDK

现在我们已经获得了我们的NOTION_API_TOKENNOTION_MAILING_LIST_ID 、和NOTION_DATABASE_ID ,我们可以开始使用Notion SDK。

设置你的项目的文件结构,使其看起来像下面的代码。

|___controllers
  |___bootcamp.controller.js
|___models
  |___bootcamp.model.js
|___routes
  |___index.js
|___services
  |___notion.js
|___.env
|___server.js

在我们继续之前,让我们快速看一下每个目录将负责什么。

  • controllers :存放我们应用程序的业务逻辑。
  • models :保存与Notion数据库集成的交互代码。
  • routes :持有我们应用程序内的路由代码
  • services :包含将我们的应用程序连接到外部服务的代码,如Notion。

让我们先从services 。在你的services 目录中,将以下代码块粘贴到你的notion.js 文件中。

// In this file, we connect to the Notion Service
require('dotenv').config()
const { Client } = require('@notionhq/client');
const notion = new Client({ auth: process.env.NOTION_API_TOKEN });
module.exports = notion;

接下来,让我们设置一下models 。下面的代码块将负责从我们的Notion数据库服务中写和读。

// models/bootcamp.model.js

// This file contains code to make operations on the DB
const notion = require("../services/notion");
const courseDatabaseId = process.env.NOTION_DATABASE_ID;
const mailingListDatabaseId = process.env.NOTION_MAILING_LIST_ID;
const bootcampModel = {
  // list all the courses in the DB
getCourses: async () => {
    try {
      const { results } = await notion.databases.query({
        database_id: courseDatabaseId,
      });
      const res = results.map((page) => {
        return {
          pageId: page.id,
          videoURL: page.properties["YouTube Video"].url,
          title: page.properties.Name.title[0].plain_text,
          tags: page.properties.Tags.multi_select.map((tag) => tag.name),
          summary: page.properties.Summary.rich_text[0].plain_text,
          author: page.properties.Author.rich_text[0].plain_text,
          startDate: page.properties.Date.date.start,
          endDate: page.properties.Date.date.end,
        };
      });
      return res;
    } catch (error) {
      console.error(error);
    }
  },
  getSubscribersFromDB: async () => {
    try {
      const { results } = await notion.databases.query({
        database_id: mailingListDatabaseId,
      });
      const res = results.map((page) => {
        return {
          name: page.properties.Name.title[0]?.text.content,
          email: page.properties["E-mail"].multi_select[0]?.name,
        };
      });
      return res;
    } catch (error) {
      console.error(error);
    }
  },
  addSubscriberToDB: async ({ name, email }) => {
    try {
      const res = await notion.pages.create({
        parent: {
          database_id: mailingListDatabaseId,
        },
        properties: {
          Name: {
            title: [
              {
                text: { content: name, link: null },
                plain_text: name,
              },
            ],
          },
          "E-mail": {
            multi_select: [
              {
                name: email,
              },
            ],
          },
        },
      });
      return res;
    } catch (error) {
      return {
        error: "Failed to add user to Mailing List",
      };
    }
  },
  findSubscriberByEmail: async ({ email }) => {
    try {
      const { results } = await notion.databases.query({
        database_id: mailingListDatabaseId,
        filter: {
          or: [
            {
              property: "E-mail",
              multi_select: {
                contains: email,
              },
            },
          ],
        },
      });
      // check if the results array contains a user
      if (results.length > 0) {
        return {
          isUserInDB: true,
        };
      }
      return {
        isUserInDB: false,
      };
    } catch (error) {
      console.error(error);
    }
  },
};
module.exports = bootcampModel;

可能需要一些练习来向你的数据库发出请求,以了解Notion是如何构造你的数据的。一旦你掌握了它,你会发现它是非常简单的。

在上面的models 文件中,我们创建了findSubscriberByEmail 方法,它检查一个电子邮件地址是否已经存在于我们的Bootcamp Mailing List中。

addSubscriberToDB 方法将一个新的用户添加到我们的邮件列表中,而getCourses 方法返回我们日历中的课程列表和每个课程的细节。

接下来,让我们为我们的控制器设置代码。

// controllers/bootcamp.controller.js

// Handles the business Logic
const bootcampModel = require("../models/bootcamp.model");

const bootcampController = {
  getAllCourses: async () => await bootcampModel.getCourses(),

  addSubscriberToDB: async ({ name, email }) => {
    const { isUserInDB } = await bootcampModel.findSubscriberByEmail({
      name,
      email,
    });

    // check if the E-mail exists
    if (isUserInDB) {
      return {
        error: "That E-mail already exists in our mailing list.",
      };
    }

    // if the E-mail doesn't already exist, add to Notion DB
    const response = await bootcampModel.addSubscriberToDB({ name, email });

    // if something goes wrong, send an error message
    if (response.error) {
      return {
        error: response.error,
      };
    }

    // if adding a user is successful
    return { message: "Successfully added to the Bootcamp mailing list" };
  },
};

module.exports = bootcampController;

我们的控制器中有两个方法。一个连接到我们的Notion数据库,抓取我们在Notion上创建的日历中的所有课程细节,另一个是将用户添加到Bootcamp邮件列表。

设置一个Fastify服务器

现在,我们将使用Fastify框架启动一个Node.js服务器。尽管开发者通常在Node.js应用程序中使用Express,但Fastify是一个新的、令人兴奋的框架,它对Express的一些最佳功能进行了改进。

例如,Fastify允许我们通过解析JSON请求来编写更好、更干净的异步代码。有了Fastify插件,你不需要从不同的作者那里安装多个npm包来执行常见的任务,如认证验证

通过运行下面的代码将Fastify添加到你的应用程序。

npm i fastify

让我们来设置我们的路由目录和启动Fastify服务器的代码。在你的项目根目录下的server.js 文件中,添加以下代码块。

// server.js

const fastify = require('./routes')
  fastify.listen(5000, (err, address) => {
    if (err) throw err
})

上面的代码块将在localhost:5000 上启动我们的服务器。

在你创建的routes 目录中,在你的index.js 文件中添加下面的代码块。

// routes/index.js

const fastify = require("fastify")({
  logger: true,
});

// Controllers
const bootcampController = require("../controllers/bootcamp.controller");

// Routes
fastify.get("/", async (req, reply) => {
  try {
    const res = await bootcampController.getAllCourses();
    reply.type("application/json").code(200);
    return { data: res };
  } catch (error) {
    reply.type("application/json").code(400);
    return { error };
  }
});

fastify.post("/", async (req, reply) => {
  try {
    const { name, email } = req.body;
    const res = await bootcampController.addSubscriberToDB({ name, email });
    reply.type("application/json").code(200);
    return { data: res };
  } catch (error) {
    reply.type("application/json").code(400);
    return { data: error };
  }
});

module.exports = fastify;

上面的代码使用Fastify来创建两个路由。第一个路由接受一个GET请求。bootcampController 接受请求,然后返回课程列表和课程的元数据,这些数据是从我们的Notion数据库中检索的。

我们将通过使用VS Code中的REST Client扩展来测试我们的路由和端点。一旦你安装了REST客户端,在你的项目的根部创建一个名为rest.http 的文件。

让我们试着向我们的根路由发出一个GET请求。这个路由返回我们Notion数据库中的所有课程信息。点击发送请求按钮,向localhost:5000 发出一个GET请求。

Get request root route

第二个路由接受一个POST请求。这个路由负责向Bootcamp邮件列表添加一个新用户,并在请求正文中接受NameEmail

Post Request Rest Client

我们也可以在前端导航到我们的Bootcamp Mailing List页面,看到用户正在使用我们创建的应用程序被添加到我们的Notion列表。

Bootcamp Mailing List Notion

如果你想测试一下我的这个应用程序的版本,你可以使用notion-api-demo.glitch.me 端点向我托管在Glitch上的服务器发出GET和POST请求。只需将你目前在REST客户端中使用的localhost:5000 端点替换为我的Glitch URL。

在你向这个端点发出POST请求后,在Notion中导航到我的Bootcamp邮件列表,检查你的电子邮件是否被添加到邮件列表中。

总结

我们的服务器端代码现在已经完成,并且可以使用了!在本教程中,我们通过建立一个可以存储和检索数据的应用程序的后台来探索Notion的API。我们已经能够将我们的应用程序设置为

  • 获取Notion数据库中的所有课程以及这些课程的详细信息,包括课程的开始和结束日期、标题、描述以及相关的视频网址
  • 向我们在Notion中创建的Bootcamp邮件列表添加用户

如果要跟随本教程或快速测试这个应用程序,欢迎你从我的GitHubrepo中克隆这个项目。

The postGetting started with the Notion APIappeared first onLogRocket Blog.