Wiki.js 2.5.x GraphQL API 创建页面 400 Bad Request 故障排查全记录

在 Ubuntu 环境中使用 Wiki.js 2.5.308 管理知识库时,我尝试通过 Python 脚本批量导入 Markdown 页面(含图片),但 GraphQL API 始终返回 400 Bad Request。本文记录完整排查过程、关键思路与最终解决方案,帮助同行避免类似坑。


问题复现


# 初始错误代码(REST 风格)
url = f"{URL}/api/pages/create"
r = requests.post(url, headers=HEADERS, json=payload)  # 404

切换 GraphQL 后:



# 仍 400
mutation = """
mutation CreatePage($input: CreatePageInput!) {
  pages { create(input: $input) { ... } }
}
"""

核心错误:误用 REST + 忽略 GraphQL 必填字段

错误一:Wiki.js 2.5.x 无 REST 创建端点,仅支持 /graphql。

来源:官方文档 requarks.io/docs/dev/api

错误二:pages.create mutation 6 个字段为非空(!):


description: String!
editor: String!
isPublished: Boolean!
isPrivate: Boolean!
locale: String!
tags: [String]!

来源:实际 400 响应 r.text 解析(GRAPHQL_VALIDATION_FAILED)

排查思路(分步验证法)

步骤 操作 目的
1 简化 mutation(仅
title

content

path
验证端点连通性
2 硬编码 mutation(无 variables) 排除 JSON 序列化问题
3 打印
r.text
获取 GraphQL 错误栈
4 逐个补全
!
字段
满足 schema 验证

# 关键诊断:打印原始响应
print(repr(r.text))

最终解决方案(关键代码)


# 硬编码 mutation(满足所有 ! 字段)
mutation = f'''
mutation {{
  pages {{
    create(
      title: "{title}",
      content: "{content_escaped}",
      path: "{path}",
      description: "",
      editor: "markdown",
      isPublished: true,
      isPrivate: false,
      locale: "zh",
      tags: {json.dumps(tags)}
    ) {{ responseResult {{ succeeded }} }}
  }}
}}
'''

API Key 隐藏:使用环境变量或配置文件注入 Bearer ***

验证结果


  "data": {
    "pages": {
      "create": {
        "responseResult": { "succeeded": true },
        "page": { "id": 3, "path": "airplane/军用运输机" }
      }
    }
  }
}

访问 URL:http://your-ip:3000/airplane/军用运输机

经验总结

优先使用 GraphQL Playground 测试 mutation。400 必查 r.text,GraphQL 错误极其明确。Wiki.js 2.5.x schema 与文档不完全一致,以实际响应为准。推荐替代方案:


# 使用官方 CLI 更稳定
docker run --rm ghcr.io/requarks/wiki-cli import /data/wiki.json

环境:Wiki.js 2.5.308 + Ubuntu + Python 3.11

© 版权声明

相关文章

暂无评论

none
暂无评论...