Loading

记录Notion API Authorization中的一个坑

正文

Notion官方文档的Authorization部分提到:

In your integration code, include the token in the Authorization header with every API request, as in the following example:

GET /v1/pages/b55c9c91-384d-452b-81db-d1ef79372b75 HTTP/1.1 Authorization: Bearer {INTEGRATION_TOKEN}

由此可知,在每次提出请求的时候都要在头部加入认证信息。官方代码的Shell示例中明确表示了请求中--header 'Authorization: Bearer '"$NOTION_API_KEY"''的占位,而Javascript的代码示例却直接略过了这一点,这导致了复制使用官方Javascript代码的时候很容易因为忽略认证步骤而产生错误。

以创建数据库为例,根据官方文档Create a database的例子,其省略了请求中头部的Authorization,代码如下:

const options = {
  method: 'POST',
  headers: {
    accept: 'application/json',
    'Notion-Version': '2022-06-28',
    'content-type': 'application/json'
  }
};

fetch('https://api.notion.com/v1/databases', options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error(err));

如果直接使用如上所示官方文档的代码,则会返回401的错误,返回错误信息如下所示:

{
  object: 'error',
  status: 401,
  code: 'unauthorized',
  message: 'API token is invalid.'
}

完整的创建数据库请求代码为:

const options = {  
    method: 'POST',  
    headers: {  
        Authorization: "Bearer " + '这里应为Notion的密钥(token)',  
        accept: 'application/json',  
        'Notion-Version': '2022-06-28',  
        'content-type': 'application/json'  
    },  
    body: JSON.stringify(body)  
}

fetch('https://api.notion.com/v1/databases', options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error(err));

依此类推,在使用Notion API的时候,一定不要忘了在请求的头部加入"Authorization"部分的信息。

Reference

Notion API

posted @ 2022-12-26 19:07  realXuan  阅读(21)  评论(0编辑  收藏  举报  来源