You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python在Notion页面创建日历数据库?解决400 JSON解析错误

解决Notion API创建日历数据库时的400 Invalid JSON错误

错误原因

你遇到的invalid_json错误主要有两个核心问题:

  1. 请求数据未正确序列化:代码直接将Python字典传给requests.request的data参数,requests会默认把它编码为表单格式,而Notion API要求接收JSON格式的请求体。
  2. 数据库属性与视图配置不规范:属性定义存在冗余字段,且未配置日历视图(要创建日历类型数据库,必须显式指定视图类型)。

修复步骤

1. 修正请求数据传递方式

将requests.request中的data参数替换为json参数,requests会自动把Python字典序列化为JSON字符串,同时确保请求格式符合API要求。

2. 规范数据库属性定义

  • Title属性:不需要id和name字段,属性名直接由外层键名(如"to do")指定,内部只需保留type: "title"和title: {}。
  • Rich Text属性:外层键名即为属性名,内部无需重复定义name,结构为{"type": "rich_text", "rich_text": {}}。

3. 添加日历视图配置

要让数据库默认以日历形式展示,必须在请求体中加入views数组,指定日历视图并关联日期属性。

修复后的完整代码

import requests

token = '~~~~'
parent_pageID = "df0f2f4b-ca24-46e3-a48e-85650cbd5ba5"

page_header = {
    "Authorization": "Bearer " + token,
    "Content-Type": "application/json",
    "Notion-Version": "2022-06-28"
}

def CreateCalendarDatabase(page_id, headers):
    create_db_url = "https://api.notion.com/v1/databases"

    db_data = {
        "title": [
            {
                "type": "text",
                "text": {
                    "content": "我的日历数据库"
                }
            }
        ],
        "properties": {
            "to do": {
                "type": "title",
                "title": {}
            },
            "date": {
                "type": "date",
                "date": {}
            },
            "content": {
                "type": "rich_text",
                "rich_text": {}
            }
        },
        "parent": {
            "type": "page_id",
            "page_id": page_id
        },
        "views": [
            {
                "type": "calendar",
                "name": "日历视图",
                "calendar": {
                    "property": "date"  # 关联日期属性作为日历的时间维度
                }
            }
        ]
    }

    res = requests.post(create_db_url, headers=headers, json=db_data)
    print(res.status_code)
    print(res.text)

CreateCalendarDatabase(parent_pageID, page_header)

关键修改说明

  • 用requests.post替代requests.request,语法更简洁直观。
  • 移除了title数组中的冗余plain_text字段(Notion API会自动生成该字段)。
  • 添加views字段配置日历视图,指定关联date属性,确保数据库默认以日历形式展示。
  • 重命名函数为CreateCalendarDatabase,更贴合功能意图。

内容的提问来源于stack exchange,提问作者bin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:36:32